dougaodi8895 2015-02-23 15:31
浏览 474
已采纳

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

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条回答 默认 最新

  • dsg435665475 2015-02-23 17:18
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏