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

标签 http go

http.Request 结构包括请求发送者的远程 IP 和端口:

    // 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**

http.Response 对象没有这样的字段。

我想知道响应我发送的请求的 IP 地址,即使我将它发送到 DNS 地址。

我认为 net.LookupHost() 可能会有帮助,但 1) 它可以为单个主机名返回多个 IP,并且 2) 它忽略主机文件,除非 cgo 可用,但在我的情况下不可用。

是否可以检索 http.Response 的远程 IP 地址?

最佳答案

使用 net/http/httptrace打包并使用 GotConnInfo钩子(Hook)捕获 net.Conn 及其对应的 Conn.RemoteAddr()

这将为您提供 Transport 实际调用的地址,而不是在 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)
    }
}

输出:

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

关于http - 如何找到 Go http.Response 的远程 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42305636/

相关文章:

javascript - 关于使用 Node.js 作为 Braintree 的本地服务器有疑问吗?

ASP.NET 如何一次只处理来自指定用户的 1 个 HTTP 处理程序?

go - 如何在Golang中使用seekdir/telldir?

go - 是否可以获取返回了返回值的源代码行?

mongodb - 如何在 MongoDB 中执行带有搜索的 Joinquery 然后继续?

c# - 404 for web.api cors 选项

javascript - 网站自动登录是如何实现的?

json - 在 Go 中表示 JSON 策略

api - 用于添加/删除数组元素的 RESTful API 端点?

go - 检查方法类型是否与函数类型匹配