2017-02-17 204 views
3

該http.Request結構包括請求的發送者的遠程IP地址和端口:如何找到Go http.Response的遠程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地址?

+0

@ B.Adler這個問題是問一個HTTP 。請求。我在詢問一個http.Response。 –

+1

最好的方法是讓服務器將它包含在標題中。在很多情況下,您甚至不會直接連接到服務器,只能通過代理或負載平衡器獲知地址。 – JimB

+0

您應該在問題的早期澄清您正在編寫HTTP *客戶端*。 – dolmen

回答

3

使用net/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) 
    } 
} 

輸出:

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