Golang:源端口与拨号响应不同时的ReadFromUDP行为 [英] Golang: ReadFromUDP behavior when source port differs in reponse from dial

查看:221
本文介绍了Golang:源端口与拨号响应不同时的ReadFromUDP行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用golang编写了以下简单的udp服务器/客户端.该应用程序将当前时间发送到指定的ipv6链接本地地址.接收方发回一点答复.仅当答复的发送方端口与请求的目标端口相同时,此方法才有效.

i have written the following simple udp server/client in golang. The app sends the current time to a specified ipv6 link-local addrress. The receiver sends back a little reply. This works ONLY if the sender port of the reply is the same as the destination port of the request.

Wireshark比较: https://www.dropbox.com/s /ypaepz62sa4xtnh/go_simple_udp3.png?dl=0

Wireshark Comparison: https://www.dropbox.com/s/ypaepz62sa4xtnh/go_simple_udp3.png?dl=0

为什么会这样?

package main

import (
"net"
"log"
"fmt"
"time"
)

func main() {

//Remote Addr
BoxAddr, err := net.ResolveUDPAddr("udp6", "[fe80:0000:0000:0000:0211:7d00:0030:8e3f]:5684")
if(err != nil) {
    log.Fatal(err)
    return
}

/*
LocalAddr, err := net.ResolveUDPAddr("udp6", "[fe80::299f:4146:2e32:72fd%4]:50361")
if(err != nil) {
    log.Fatal(err)
    return
}
*/
c, err := net.DialUDP("udp6", nil, BoxAddr)
if(err != nil) {
    log.Fatal(err)
    return
}

defer c.Close()

fmt.Print(c.LocalAddr())

//read loop
go func(c *net.UDPConn) {

    for {
        rxMsg := make([]byte, 100);
        n,_, err := c.ReadFromUDP(rxMsg)
        if(err != nil) {
            log.Fatal(err)
            return
        } else {
            fmt.Print("Got from remote: ",n, " bytes\r\n")
        }
    }
}(c)

//write every second current time
for {
    b := []byte(time.Now().String())
    n, err := c.Write(b)

    if(err != nil) {
        log.Fatal(err)
        return
    } else {
        fmt.Print("Wrote to destination socket: ",n, " bytes\r\n")
    }

    time.Sleep(1000 * time.Millisecond)
}
}

推荐答案

使用DialUDP时,您正在创建一个已连接"的UDP套接字,该套接字仅侦听来自给定远程地址的数据报.底层的系统调用与connect相同,后者在手册页中指出:

When you use DialUDP, you're creating a "connected" UDP socket, which only listens for datagrams from the given remote address. The underlying syscall is the same as connect, which states in the man page:

如果套接字sockfd的类型为SOCK_DGRAM,则addr是默认情况下向其发送数据报的地址,也是唯一从其接收数据报的地址.

If the socket sockfd is of type SOCK_DGRAM then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received.

如果要侦听在特定UDP端口上收到的任何数据报,请使用 ListenUDP .

If you want to listen for any datagrams received on a particular UDP port, create the connection with ListenUDP.

这篇关于Golang:源端口与拨号响应不同时的ReadFromUDP行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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