英文:
Google Go Lang - Getting socket id/fd of net/http to use with syscall.Bind
问题
我正在尝试获取net/http请求的套接字ID/FD,以便我可以将其与syscall.Bind()一起使用,将套接字绑定到我的多个公共出站IPV4地址之一。
我希望能够选择用于出站请求的IP地址。这是针对Windows的。
非常感谢任何帮助。
以下是一些针对Linux的代码,但我需要获取http.Client的套接字FD而不是net.Conn。
func bindToIf(conn net.Conn, interfaceName string) {
ptrVal := reflect.ValueOf(conn)
val := reflect.Indirect(ptrVal)
//下一行将获取net.netFD
fdmember := val.FieldByName("fd")
val1 := reflect.Indirect(fdmember)
netFdPtr := val1.FieldByName("sysfd")
fd := int(netFdPtr.Int())
//fd现在包含套接字的实际fd
err := syscall.SetsockoptString(fd, syscall.SOL_SOCKET,
syscall.SO_BINDTODEVICE, interfaceName)
if err != nil {
log.Fatal(err)
}
}
英文:
I'm trying to get the socket id/fd of a net/http request so that i can use it with syscall.Bind() to bind the socket to one of my many public outgoing IPV4 addresses.
I want to be able to select which IP address is used for the outgoing request. This is for Windows.
Any help is greatly appreciated.
Below is some code which is for linux, but i need to get the http.Client's socket fd and not net.Conn.
func bindToIf(conn net.Conn, interfaceName string) {
ptrVal := reflect.ValueOf(conn)
val := reflect.Indirect(ptrVal)
//next line will get you the net.netFD
fdmember := val.FieldByName("fd")
val1 := reflect.Indirect(fdmember)
netFdPtr := val1.FieldByName("sysfd")
fd := int(netFdPtr.Int())
//fd now has the actual fd for the socket
err := syscall.SetsockoptString(fd, syscall.SOL_SOCKET,
syscall.SO_BINDTODEVICE, interfaceName)
if err != nil {
log.Fatal(err)
}
}
答案1
得分: 2
我正在尝试获取net/http请求的套接字ID或文件描述符。
http.Request
和http.Client
都没有提供套接字供您获取。
您可以通过修改http.Client
的Transport来自定义如何创建TCP连接。请参阅Dial
和DialTLS
函数。
从文档中可以看到:
Dial
指定用于创建未加密TCP连接的拨号函数。如果Dial
为nil,则使用net.Dial
。
您可能会对这个问题感兴趣,该问题询问如何使用特定接口进行拨号。
您可以设置默认传输以执行以下操作:
http.DefaultTransport.(*http.Transport).Dial = func(network, addr string) (net.Conn, error) {
d := net.Dialer{LocalAddr: /* 在此处填写您的地址 */}
return d.Dial(network, addr)
}
如果您使用TLS,您需要对http.DefaultTransport.DialTLS
执行类似的操作。
英文:
>I'm trying to get the socket id/fd of a net/http request
Neither http.Request
or http.Client
have a socket for you to get.
You can customize how an http.Client
creates TCP connections by modifying it's Transport. See the Dial
and DialTLS
functions.
From the docs:
> Dial specifies the dial function for creating unencrypted TCP connections. If Dial is nil, net.Dial is used.
You may be interested in this question, which asks how to dial using a specific interface.
You could set up the default transport do something like this:
http.DefaultTransport.(*http.Transport).Dial = func(network, addr string) (net.Conn, error) {
d := net.Dialer{LocalAddr: /* your addr here */}
return d.Dial(network, addr)
}
If you're using TLS, you'll want to do something similar for http.DefaultTransport.DialTLS
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论