How to bind an http.Client in Go to an IP Address

后端 未结 2 1947
南旧
南旧 2020-12-15 14:37

I have a client machine with multiple NICs, how do I bind an http.Client in Go to a certain NIC or to a certain SRC IP Address?

Say you have some very basic http cli

2条回答
  •  情歌与酒
    2020-12-15 15:08

    Similar to this question, you need to set the http.Client.Transport field. Setting it to an instance of net.Transport allows you to specify which net.Dialer you want to use. net.Dialer then allows you to specify the local address to make connections from.

    Example:

    localAddr, err := net.ResolveIPAddr("ip", "")
    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,
        },
    }
    

提交回复
热议问题