登录
首页 >  Golang >  Go问答

获取TCP服务器连接域地址的方法

来源:stackoverflow

时间:2024-02-23 20:18:25 272浏览 收藏

一分耕耘,一分收获!既然都打开这篇《获取TCP服务器连接域地址的方法》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我有一个简单的 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 连接,原始域名不会随请求一起发送。

由于您有时需要用户尝试连接的原始名称,因此某些协议会在连接后发送域名。例如,HTTP 通过 Host header 执行此操作。

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

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《获取TCP服务器连接域地址的方法》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>