Binding multiple times to the same port?

£可爱£侵袭症+ 提交于 2019-12-04 17:33:46

You can bind on the same port number on different IP addresses. The operating system can distinguish the incoming packets by their target IP address as well as their TCP port number.

The operating system has no problem keeping a separate serverSocket for 127.0.0.1:1000 and 127.0.0.2:1000. It knows where each packet belongs - even if it opens a new connection.

Note that the IP address 0.0.0.0 is just that - an IP address (it is not a valid IP address in the sense IP packets could be sent there, but I can't any support for 0.0.0.0 == any either). If you want to listen on all addresses, supply null to the InetSocketAddress instead. At this point, you have a greater chance of getting the desired exception (unless the OS decides that wildcard listens have lower priority and don't really overlap specific listens, so they can bind both).

Also note that setting setReuseAddress will not affect the binding. It only affects some specifics of what connections get refused or accepted.

As a side note - what's the point of waiting three hundred million years?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!