能否不同udp socket绑定到同一IP地址和port

Posted yanhc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了能否不同udp socket绑定到同一IP地址和port相关的知识,希望对你有一定的参考价值。

http://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-4.html

 

https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/b8a3395f-938b-4347-b6c3-431851e68884/sockets-multicastbroadcast-udp-tcp-soreuseaddr-soreuseport-and-soexclusiveaddruse

The main differences between BSD and Windows are conveniently described on https://stackoverflow.com/questions/14388706/socket-options-so-reuseaddr-and-so-reuseport-how-do-they-differ-do-they-mean-t. According to that, one would say that a solution:

1) For BSD "0" and for Windows "SO_EXCLUSIVEADDRUSE"

2) For BSD "SO_REUSEPORT | SO_REUSEADDR" and for Windows "SO_REUSEADDR"

https://docs.microsoft.com/zh-cn/windows/desktop/WinSock/using-so-reuseaddr-and-so-exclusiveaddruse

Using SO_REUSEADDR

The SO_REUSEADDR socket option allows a socket to forcibly bind to a port in use by another socket. The second socket calls setsockopt with the optname parameter set to SO_REUSEADDR and the optval parameter set to a boolean value of TRUE before calling bindon the same port as the original socket. Once the second socket has successfully bound, the behavior for all sockets bound to that port is indeterminate. For example, if all of the sockets on the same port provide TCP service, any incoming TCP connection requests over the port cannot be guaranteed to be handled by the correct socket — the behavior is non-deterministic. A malicious program can use SO_REUSEADDR to forcibly bind sockets already in use for standard network protocol services in order to deny access to those service. No special privileges are required to use this option.

If a client application binds to a port before a server application is able to bind to the same port, then problems may result. If the server application forcibly binds using the SO_REUSEADDR socket option to the same port, then the behavior for all sockets bound to that port is indeterminate.

The exception to this non-deterministic behavior is multicast sockets. If two sockets are bound to the same interface and port and are members of the same multicast group, data will be delivered to both sockets, rather than an arbitrarily chosen one.

 

windows没有SO_REUSEPORT选项,只有SO_REUSEADDR,但

windows的SO_REUSEADDR 等同于BSD的SO_REUSEADDR和SO_REUSEPORT

但如果两个socket同时绑定到同一地址和同一port的话,这些socket的行为是不确定的,主要体现在接收数据上,数据会投递给随机选择的一个socket。

所以,两个socket绑定到同一地址和同一port,同时用udp接收数据的话,只有一个socket能够收到数据。

这样是不行的。只能用一个socket。

以上是关于能否不同udp socket绑定到同一IP地址和port的主要内容,如果未能解决你的问题,请参考以下文章

Linux Socket - UDP链接包

同一台机 TCP 和 UDP 能否使用同一个端口号?

同一端口,如何区分不同的socket

linux系统UDP的socket通信编程3

如何从 udp-socket (C/C++) 获取您自己的(本地)IP 地址

关于socket UDP通信,接收到乱码的问题!!急急急!SOS!