我有两个绑定到同一地址并连接到地址A和B的UDP套接字。我还有另外两个绑定到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是默认发送数据报的地址,也是唯一接收数据报的地址< / strong>。”
由于某种原因,我连接的套接字正在接收发往彼此的数据包。例如:连接到A的UDP套接字向A发送一条消息,然后A发送回一个答复。连接到B的UDP套接字向B发送一条消息,然后B发送回一个答复。但是,来自A的答复到达连接到B的套接字,而来自B的答复到达到达A的套接字。
为什么这会发生?请注意,它是随机发生的-有时答复到达正确的套接字,有时却没有。有什么方法可以防止这种情况或在connect
无法正常工作的任何情况下?
答案 0 :(得分:0)
嗯,据我所知,没有订购保证。
在手册页中:
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)作为客户端的选项。
我怀疑您的方法是错误的,需要重新考虑=)
PS。乍一看,但是恕我直言,这是您的方法中的错误