dongzhang0243 2016-11-30 20:19
浏览 227
已采纳

无法读取UDP回复(golang)

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) prints a diagnostic and exits if err is not nil, BTW.

The information in the replies looks like:

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)

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!

  • 写回答

1条回答 默认 最新

  • dongliyun3301 2016-11-30 20:31
    关注

    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)
    

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示