gpt4 book ai didi

linux - UDP 数据包到达 Linux 上的错误套接字

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:06 24 4
gpt4 key购买 nike

我有两个绑定(bind)到同一地址并连接到地址 A 和 B 的 UDP 套接字。我还有两个绑定(bind)到 A 和 B 但未连接的 UDP 套接字。

这是我的 /proc/net/udp 的样子(为了便于阅读而修剪):

  sl  local_address rem_address
3937: 0100007F:DD9C 0300007F:9910
3937: 0100007F:DD9C 0200007F:907D
16962: 0200007F:907D 00000000:0000
19157: 0300007F:9910 00000000:0000

根据 connect(2):“如果套接字 sockfd 是 SOCK_DGRAM 类型,则 addr 是数据报默认发送到的地址,并且是唯一的地址从中接收数据报。”

出于某种原因,我连接的套接字正在接收发往彼此的数据包。 eg:连接到A的UDP套接字向A发送消息,A然后发回回复。连接到 B 的 UDP 套接字向 B 发送消息,B 然后发回回复。但是来自 A 的回复到达连接到 B 的套接字,来自 B 的回复到达连接到 A 的套接字。

到底为什么会发生这种情况?请注意,它是随机发生的——有时回复会到达正确的套接字,有时则不会。有什么方法可以防止这种情况或 connect 应该不起作用的任何情况?

最佳答案

嗯,据我所知,没有订购保证。

来自手册页:

      SO_REUSEPORT (since Linux 3.9)
Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all
of the processes binding to the same address must have the same effective UID. This option can be employed with both TCP and UDP sockets.

For TCP sockets, this option allows accept(2) load distribution in a multi-threaded server to be improved by using a distinct listener socket for each thread. This provides improved load distribution as compared to traditional
techniques such using a single accept(2)ing thread that distributes connections, or having multiple threads that compete to accept(2) from the same socket.

For UDP sockets, the use of this option can provide better distribution of incoming datagrams to multiple processes (or threads) as compared to the traditional technique of having multiple processes compete to receive datagrams on
the same socket.

因此,您使用的东西主要被视为服务器(或在某些情况下是客户端,但永远无法保证顺序 - 特别是在 UDP 中)的选项作为客户端。

我怀疑你的方法是错误的,需要重新考虑 =)

附言。只是快速浏览了一下,但恕我直言,这是您方法中的一个错误

关于linux - UDP 数据包到达 Linux 上的错误套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51630337/

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