dongyi2425 2017-02-17 19:07
浏览 391

如何找到Go http.Response的远程IP地址?

The http.Request struct includes the remote IP and port of the request's sender:

    // RemoteAddr allows HTTP servers and other software to record
    // the network address that sent the request, usually for
    // logging. This field is not filled in by ReadRequest and
    // has no defined format. The HTTP server in this package
    // sets RemoteAddr to an "IP:port" address before invoking a
    // handler.
    // This field is ignored by the HTTP client.
    **RemoteAddr string**

The http.Response object has no such field.

I would like to know the IP address that responded to the request I sent, even when I sent it to a DNS address.

I thought that net.LookupHost() might be helpful, but 1) it can return multiple IPs for a single host name, and 2) it ignores the hosts file unless cgo is available, which it is not in my case.

Is it possible to retrieve the remote IP address for an http.Response?

  • 写回答

1条回答 默认 最新

  • douluohan3403 2017-02-18 10:40
    关注

    Use the net/http/httptrace package and use the GotConnInfo hook to capture the net.Conn and its corresponding Conn.RemoteAddr().

    This will give you the address the Transport actually dialled, as opposed to what was resolved in DNSDoneInfo:

    package main
    
    import (
        "log"
        "net/http"
        "net/http/httptrace"
    )
    
    func main() {
        req, err := http.NewRequest("GET", "https://example.com/", nil)
        if err != nil {
            log.Fatal(err)
        }
    
        trace := &httptrace.ClientTrace{
            GotConn: func(connInfo httptrace.GotConnInfo) {
                log.Printf("resolved to: %s", connInfo.Conn.RemoteAddr())
            },
        }
    
        req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
    
        client := &http.Client{}
        _, err := client.Do(req)
        if err != nil {
            log.Fatal(err)
        }
    }
    

    Outputs:

    ~ go run ip.go
    2017/02/18 19:38:11 resolved to: 104.16.xx.xxx:443
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!