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**
Run Code Online (Sandbox Code Playgroud)
http.Response 对象没有这样的字段。
我想知道响应我发送的请求的 IP 地址,即使我将它发送到 DNS 地址。
我认为 net.LookupHost() 可能会有所帮助,但是 1) 它可以为单个主机名返回多个 IP,并且 2) 它忽略主机文件,除非 cgo 可用,这在我的情况下不是。
是否可以检索 http.Response 的远程 IP 地址?
使用网/ HTTP / httptrace包,并使用GotConnInfo
钩子捕获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)
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
~ go run ip.go
2017/02/18 19:38:11 resolved to: 104.16.xx.xxx:443
Run Code Online (Sandbox Code Playgroud)