能否不同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。

猜你喜欢

转载自www.cnblogs.com/yanhc/p/10923505.html
0条评论
添加一条新回复