【问题标题】:Golang UDP Server only recieving locally sent packetsGolang UDP Server 只接收本地发送的数据包
【发布时间】:2015-08-14 07:42:00
【问题描述】:

我在 Go 中编写了一个 UDP 服务器(侦听端口 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 响应非本地请求,我需要做些什么特别的事情吗?

【问题讨论】:

    标签: linux go network-programming udp


    【解决方案1】:

    只收听任何地址,你只收听本地主机。

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

    【讨论】:

      【解决方案2】:

      它正在做你告诉它做的事情:在 127.0.0.1 收听。如果你想让它监听所有接口,你必须指定 0.0.0.0。

      不要问我在 Go 中是如何做到的。

      【讨论】:

      • 是的。哇,那是我对 IP 理解的一个大漏洞。谢谢!
      猜你喜欢
      • 2012-10-03
      • 2012-05-20
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      相关资源
      最近更新 更多