gpt4 book ai didi

sockets - Google Go Lang - 获取 net/http 的套接字 ID/fd 以与 syscall.Bind 一起使用

转载 作者:IT王子 更新时间:2023-10-29 02:05:30 25 4
gpt4 key购买 nike

我正在尝试获取 net/http 请求的套接字 ID/fd,以便我可以将它与 syscall.Bind() 一起使用,以将套接字绑定(bind)到我的许多公共(public)传出 IPV4 地址之一。

我希望能够选择哪个 IP 地址用于传出请求。这是针对 Windows 的。

非常感谢任何帮助。

下面是一些用于 linux 的代码,但我需要获取 http.Client 的套接字 fd 而不是 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)
}

最佳答案

I'm trying to get the socket id/fd of a net/http request

http.Requesthttp.Client 都没有供您获取的套接字。

您可以通过修改它的 Transport 来自定义 http.Client 创建 TCP 连接的方式。 .请参阅 DialDialTLS 函数。

来自文档:

Dial specifies the dial function for creating unencrypted TCP connections. If Dial is nil, net.Dial is used.

您可能对 this question 感兴趣,询问如何使用特定接口(interface)拨号。

你可以设置默认传输做这样的事情:

http.DefaultTransport.(*http.Transport).Dial = func(network, addr string) (net.Conn, error) {
d := net.Dialer{LocalAddr: /* your addr here */}
return d.Dial(network, addr)
}

如果您使用的是 TLS,则需要对 http.DefaultTransport.DialTLS 执行类似的操作。

关于sockets - Google Go Lang - 获取 net/http 的套接字 ID/fd 以与 syscall.Bind 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28677286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com