2018-08-13 09:50

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


I want Get Client Cache DNS IP using Go

Look at the code I tried below

import (

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")

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

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

    // Listening 53 Port Like DNS Server
    for {

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

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 but this is not answer for me

I want simple server

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duanchen7703 duanchen7703 3年前

    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.

    点赞 评论 复制链接分享