如何绑定转到IP地址的http.Client [英] How to bind an http.Client in Go to an IP Address

查看:332
本文介绍了如何绑定转到IP地址的http.Client的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台带有多个网卡的客户端机器,如何绑定一个http.client到某个网卡或某个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?

解决方案

类似于这个问题

a>,您需要设置 http.Client.Transport 字段。将它设置为 net.Transport 的一个实例允许您指定要使用哪个 net.Dialer net.Dialer 然后允许您指定本地地址以建立连接。



示例:

  localAddr,err:= net.ResolveIPAddr(ip,< my local address>)
if err!=无{
恐慌(错误)
}

//您还需要这样做才能使其工作,而不会给您
//不匹配的本地地址输入ip
//这将使ResolveIPAddr成为一个TCPAddr,而不需要
//说明要使用的SRC端口号。
localTCPAddr:= net.TCPAddr {
IP:localAddr.IP,
}


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


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 client code that looks like:

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()
}

Is there a way to bind to a certain NIC or IP?

解决方案

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", "<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,
    },
}

这篇关于如何绑定转到IP地址的http.Client的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆