我有一個簡單的 TCP 服務器,當客戶端連接時,我想獲取用于連接的域地址:package mainimport ( "fmt" "net" "os")const ( CONN_HOST = "localhost" CONN_PORT = "3333" CONN_TYPE = "tcp")func main() { // Listen for incoming connections. l, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT) if err != nil { fmt.Println("Error listening:", err.Error()) os.Exit(1) } // Close the listener when the application closes. defer l.Close() fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT) for { // Listen for an incoming connection. conn, err := l.Accept() if err != nil { fmt.Println("Error accepting: ", err.Error()) os.Exit(1) } // Handle connections in a new goroutine. go handleRequest(conn) }}// Handles incoming requests.func handleRequest(conn net.Conn) { // Make a buffer to hold incoming data. buf := make([]byte, 1024) // Read the incoming connection into the buffer. _, err := conn.Read(buf) if err != nil { fmt.Println("Error reading:", err.Error()) } // Send a response back to person contacting us. conn.Write([]byte("Message received.")) // Close the connection when you're done with it. conn.Close()}我嘗試調試conn net.Conn參數,但找不到對域地址的任何引用。嘗試使用http://test.127.0.0.1.xip.io:3333/并且我有興趣以test.127.0.0.1.xip.io某種方式獲得。有任何想法嗎?
1 回答

千萬里不及你
TA貢獻1784條經驗 獲得超9個贊
使用純 TCP 無法實現您嘗試做的事情。TCP 適用于沒有域的普通 IP 地址。
解釋發生了什么:
當您建立連接時,例如example.com
,首先example.com
完成 DNS 查找。在這種情況下,DNS 查找將導致93.184.216.34
. 您可以在此處閱讀有關 DNS的更多信息。
之后建立TCP 連接93.184.216.34
,原始域名不會隨請求一起發送。
因為您有時需要用戶嘗試連接的原始名稱,所以某些協議會在連接后發送域名。例如,HTTP 通過Host
header做到這一點。
也許您可以做類似的事情并要求首先通過您的 TCP 連接發送原始主機!
- 1 回答
- 0 關注
- 164 瀏覽
添加回答
舉報
0/150
提交
取消