如何使用Go获取客户端DNS IP

I want Get Client Cache DNS IP using Go

Look at the code I tried below

import (
    "fmt"
    "net"
)

func main() {
    // Usually DNS Server using 53 port number
    // This case, TCP protocol is not considered
    port := ":53"
    protocol := "udp"

    var buf [2048]byte

    //Build the address
    udpAddr, err := net.ResolveUDPAddr(protocol, port)
    if err != nil {
        fmt.Println("Wrong Address")
        return
    }

    fmt.Println("Listened " + protocol + " from " + udpAddr.String())

    //Create the connection
    udpConn, err := net.ListenUDP(protocol, udpAddr)
    if err != nil {
        fmt.Println(err)
    }

    // Listening 53 Port Like DNS Server
    for {

        // If get request,
        _, err := udpConn.Read(buf[0:])
        if err != nil {
            fmt.Println("Error Reading")
            return
        } else {
            // Print Remote Address,
            // I Guess this is the Client Cache DNS IP, but this is print <nil>
            fmt.Println(udpConn.RemoteAddr())
        }
    }
}

How do I get the Client Cache DNS IP in this case? Pleas Help me I Want to Build Client DNS IP Collector, seem whoami

I also refer to this as https://github.com/miekg/exdns/blob/master/reflect/reflect.go but this is not answer for me

I want simple server

dns
dqsp60748
dqsp60748 在这种情况下,不考虑使用TCP协议,否则您将遇到问题……如果您不实施EDNS,则更是如此。
大约 2 年之前 回复

1个回答



UDP是无状态的。 没有用于连接的单个客户端地址。 每个数据包都可以从不同的地址发送,因此 RemoteAddr </ code>仅对客户端有用,而对服务器不起作用。</ p>

使用 * UDPConn.ReadFrom </ code> * UDPConn.ReadFromUDP </ code> * UDPConn.ReadMsgUDP </ code> 而不是 Read </ code>。 它们全部返回读取数据包的客户端地址。</ p>
</ div>

展开原文

原文

UDP is stateless. There is no single client address for a connection. Each packet can be sent from a different address, so RemoteAddr is only useful on the client, but not the server.

Use one of *UDPConn.ReadFrom, *UDPConn.ReadFromUDP, or *UDPConn.ReadMsgUDP instead of Read. All of them return the client address for the read packet.

droos02800
droos02800 哇,谢谢,效果很好!
大约 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐