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

标签 go tcp

我有一个简单的 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()
}

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

最佳答案

使用纯 TCP 无法实现您尝试做的事情。 TCP 适用于没有域的普通 IP 地址。

解释发生了什么:

当您建立连接时,例如example.com ,首先是example.com的DNS查找已经完成了。在这种情况下,DNS 查找将导致 93.184.216.34 .您可以阅读有关 DNS here 的更多信息.

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

因为您有时需要用户尝试连接的原始名称,所以某些协议(protocol)会在连接后发送域名。 HTTP 例如通过 Host header .

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

关于go - 给定一个TCP服务器,如何获取连接域地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61889538/

相关文章:

git - Go 开发需要付费的 Github 账号才能私密开发吗?

go - 包装的 HandleFunc 从哪里获取 responseWriter 和请求?

google-app-engine - Google App Engine Go 内存管理

sockets - Chrome 实验性套接字 API : What Does `chrome.experimental.socket.sendTo()` And `recvFrom()` Do?

tcp - 是否可以通过 TCP 发送数据报?

go - 将接口(interface)断言为其类型

握手后的 TCP 数据包

c# - 在 C 中使用 WinSock 将数据发送到同一台机器上的 c# 应用程序,“目标主机拒绝连接(c# 部分)

C#从套接字中读取二进制数据

gorm如何外国 self