给定一个TCP服务器,如何获取连接域地址

Rom*_*cea -1 tcp go

我有一个简单的 TCP 服务器,当客户端连接时,我想获取用于连接的域地址:

package main

import (
    "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()
}
Run Code Online (Sandbox Code Playgroud)

我尝试调试conn net.Conn参数,但找不到任何对域地址的引用。尝试使用http://test.127.0.0.1.xip.io:3333/,我有兴趣以test.127.0.0.1.xip.io某种方式获得。有任何想法吗?

Luc*_*weg 5

使用普通 TCP 无法实现您想要做的事情。TCP 在没有域的普通 IP 地址上工作。

解释一下发生了什么:

当您建立连接时,例如example.com,首先example.com完成 DNS 查找。在这种情况下,DNS 查找将产生93.184.216.34. 您可以在此处阅读有关 DNS 的更多信息。

之后建立TCP 连接93.184.216.34,原始域名不会随请求一起发送。

由于您有时需要用户尝试连接的原始名称,因此某些协议会在连接后发送域名。例如,HTTP 通过Hostheader来实现这一点。

也许你可以做类似的事情,并要求首先通过 TCP 连接发送原始主机!