gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:38:21 27 4
gpt4 key购买 nike

我有一个简单的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com