无法读取UDP回复(golang) [英] Can't read UDP reply (golang)

查看:76
本文介绍了无法读取UDP回复(golang)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Go程序,该程序发出UDP广播以查询本地网络上设备的存在,然后读取答复.使用Wireshark,我确认该数据包已广播,并且(我)网络上的单个设备已答复(实际上是10次),但我的应用程序在读取时被阻止,好像它看不到传入的数据包.这是代码:

I'm working on a Go program that sends out a UDP broadcast to query existence of devices on the local network and then reads the replies. Using Wireshark I confirm that the packet is broadcast and that the single device on (my) network replies (ten times, in fact) but my application blocks on the read as if it does not see the incoming packet. Here is the code:

func Discover(timeout int) ([]string, error) {
    inBuf := make([]byte, 1024)
    devices := make([]string, 0)
    var readLen int
    var fromAddr *net.UDPAddr

    // get server connection
    server := fmt.Sprintf("%s:%d", bcastIP, udpDiscoverPort) // "255.255.255.255", 10000
    serverAddr, err = net.ResolveUDPAddr("udp", server)
    checkErr(err)
    ourAddr, err = net.ResolveUDPAddr("udp", "192.168.1.132:10000")
    checkErr(err)
    conn, err = net.DialUDP("udp", ourAddr, serverAddr)
    checkErr(err)
    defer conn.Close()

    // send the Discover message
    discoverMsg := []byte(magic)
    discoverMsg = append(discoverMsg, discovery...)
    sendLen, err := conn.Write(discoverMsg)
    checkErr(err)
    fmt.Println("Sent", sendLen, "bytes")

    // read one reply
    readLen, fromAddr, err = conn.ReadFromUDP(inBuf)
    fmt.Println("Read ", readLen, "bytesfrom ", fromAddr)
    txtutil.Dump(string(inBuf[:readLen]))
    return devices, nil
}

checkErr(err)打印诊断信息,如果err不为零(BTW),则退出.

checkErr(err) prints a diagnostic and exits if err is not nil, BTW.

答复中的信息如下:

Internet Protocol Version 4, Src: 192.168.1.126 (192.168.1.126), Dst: 192.168.1.132 (192.168.1.132)
User Datagram Protocol, Src Port: ndmp (10000), Dst Port: ndmp (10000)

我尝试用"0.0.0.0:10000"、:10000"和"127.0.0.1:10000"代替"192.168.1.132:10000",但似乎没有任何区别.

I have tried "0.0.0.0:10000", ":10000" and "127.0.0.1:10000" in place of "192.168.1.132:10000" and none seem to make any difference.

欢迎提出关于我在做什么的任何建议!

Any suggestions as to what I'm doing wrong are welcome!

推荐答案

您需要使用ListenUDP而不是DialUDP.当您使用DialUDP时,它将创建一个已连接"的UDP端口,并且仅在读取时返回源自远程地址的数据包.

You need to use ListenUDP instead of DialUDP. When you use DialUDP, it creates a "connected" UDP port, and only packets originating from the remote address are returned on read.

conn, err = net.ListenUDP("udp", ourAddr)

由于连接没有默认目的地,因此您还需要使用WriteTo*方法发送数据包:

Since the connection doesn't have a default destination, you will also need to use WriteTo* methods to send packets:

sendLen, err := conn.WriteToUDP(discoverMsg, serverAddr)

这篇关于无法读取UDP回复(golang)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆