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/