小编典典

如何在转到IP地址中绑定http.Client

go

我有一台具有多个NIC的客户端计算机,如何将Go中的http.Client绑定到某个NIC或某个SRC IP地址?

假设您有一些非常基本的http客户端代码,如下所示:

package main

import (
    "net/http"
)

func main() {
    webclient := &http.Client{}
    req, _ := http.NewRequest("GET", "http://www.google.com", nil)
    httpResponse, _ := webclient.Do(req)
    defer httpResponse.Body.Close()
}

有没有办法绑定到特定的NIC或IP?


阅读 233

收藏
2020-07-02

共1个答案

小编典典

与此问题类似,您需要设置http.Client.Transport字段。将其设置为的实例net.Transport可以让您指定net.Dialer要使用的对象。net.Dialer然后允许您指定进行连接的本地地址。

例:

localAddr, err := net.ResolveIPAddr("ip", "<my local address>")
if err != nil {
  panic(err)
}

// You also need to do this to make it work and not give you a 
// "mismatched local address type ip"
// This will make the ResolveIPAddr a TCPAddr without needing to 
// say what SRC port number to use.
localTCPAddr := net.TCPAddr{
    IP: localAddr.IP,
}


webclient := &http.Client{
    Transport: &http.Transport{
        Proxy: http.ProxyFromEnvironment,
        DialContext: (&net.Dialer{
            LocalAddr: &localTCPAddr,
            Timeout:   30 * time.Second,
            KeepAlive: 30 * time.Second,
            DualStack: true,
        }).DialContext,
        MaxIdleConns:          100,
        IdleConnTimeout:       90 * time.Second,
        TLSHandshakeTimeout:   10 * time.Second,
        ExpectContinueTimeout: 1 * time.Second,
    },
}
2020-07-02