我有一個(gè)簡單的 TCP 服務(wù)器,當(dāng)客戶端連接時(shí),我想獲取用于連接的域地址: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()}我嘗試調(diào)試conn net.Conn參數(shù),但找不到對(duì)域地址的任何引用。嘗試使用http://test.127.0.0.1.xip.io:3333/并且我有興趣以test.127.0.0.1.xip.io某種方式獲得。有任何想法嗎?
1 回答

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