gpt4 book ai didi

戈朗 : ReadFromUDP behavior when source port differs in reponse from dial

转载 作者:数据小太阳 更新时间:2023-10-29 03:29:54 27 4
gpt4 key购买 nike

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

Wireshark 比较: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 相同,在手册页中指出:

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 创建连接.

关于戈朗 : ReadFromUDP behavior when source port differs in reponse from dial,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32483075/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com