Golang UDP 服务器只接收本地发送的数据包

Golang UDP Server only recieving locally sent packets

我用 Go 写了一个 UDP Server(监听 666 端口),它似乎只接收本地发送的数据包。为了确认流量,我一直在使用:

sudo tcpdump -n udp dst port 666

我的(缩写)服务器代码:

import "net"

func startServer() {
    // Bind the port.
    ServerAddr, err := net.ResolveUDPAddr("udp", "localhost:666")
    if err != nil {
        fmt.Println("Error binding port!")
    }

    ServerConn, _ := net.ListenUDP("udp", ServerAddr)
    defer ServerConn.Close()

    buf := make([]byte, 1024)
    for {
        // Recieve a UDP packet and unmarshal it into a protobuf.
        n, _, _ := ServerConn.ReadFromUDP(buf)
        fmt.Println("Packet received!")
        // Do stuff with buf.
    }
}

如果服务器运行正在从机器上打开,我使用:

echo -n “foo” | nc -4u -w1 127.0.0.1 666

然后服务器接收到该数据包,并打印消息(tcpdump 显示没有输出)。

但是,如果我 运行 来自网络上另一台计算机的以下内容:

echo -n “foo” | nc -4u -w1 192.168.1.134 666

然后,当 tcpdump 报告收到一个数据包时(15:05:43.634604 IP 192.168.1.113.59832 > 192.168.1.134.666: UDP, length 9 确认我得到了正确的 IP 地址),Go 服务器没有响应。

我需要做些什么来让 Go 响应非本地请求吗?

它正在按照您的指示进行操作:在 127.0.0.1 上收听。如果你想让它在所有接口上监听,你必须指定 0.0.0.0.

别问我 Go 是怎么做到的。

只需监听任何地址,您只监听本地主机。

ServerAddr, err := net.ResolveUDPAddr("udp", ":666")