我有一台带有多个 NIC 的客户端机器,如何将 Go 中的 http.Client 绑定(bind)到某个 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()
}
有没有办法绑定(bind)到某个网卡或IP?
最佳答案
类似于this question ,您需要设置 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,
},
}
关于http - 如何在 Go 中绑定(bind)一个 http.Client 到一个 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41718408/