同一机器上的两个应用程序可以绑定到相同的端口和IP地址吗?更进一步,一个应用程序可以侦听来自某个IP的请求,而另一个应用程序可以侦听来自另一个远程IP的请求吗? 我知道我可以让一个应用程序启动两个线程(或分支)具有类似的行为,但是两个没有任何共同之处的应用程序也可以这样做吗?


当前回答

Yes.

从这篇文章中: https://lwn.net/Articles/542629/

新的套接字选项允许同一主机上的多个套接字绑定到同一个端口

其他回答

您可以让两个应用程序侦听同一个网络接口上的同一个端口。

指定的网络接口和端口只能有一个监听套接字,但该套接字可以在多个应用程序之间共享。

如果你在一个应用进程中有一个监听套接字,并且你fork了这个进程,这个套接字将被继承,所以从技术上讲,现在将有两个进程监听同一个端口。

Yes (for TCP) you can have two programs listen on the same socket, if the programs are designed to do so. When the socket is created by the first program, make sure the SO_REUSEADDR option is set on the socket before you bind(). However, this may not be what you want. What this does is an incoming TCP connection will be directed to one of the programs, not both, so it does not duplicate the connection, it just allows two programs to service the incoming request. For example, web servers will have multiple processes all listening on port 80, and the O/S sends a new connection to the process that is ready to accept new connections.

SO_REUSEADDR

允许其他套接字bind()绑定到该端口,除非已经有一个活动监听套接字绑定到该端口。这使您能够在崩溃后尝试重新启动服务器时绕过“地址已在使用”错误消息。

我用socat尝试过以下方法:

socat TCP-L:8080,fork,reuseaddr -

而且,即使我没有建立到套接字的连接,我也不能在同一个端口上侦听两次,尽管有reuseaddr选项。

我得到了这条消息(这是我之前预期的):

2016/02/23 09:56:49 socat[2667] E bind(5, {AF=2 0.0.0.0:8080}, 16): Address already in use

您可以让一个应用程序侦听一个网络接口的一个端口。因此你可以有:

HTTPD监听远程可访问的接口,例如192.168.1.1:80 另一个守护进程监听127.0.0.1:80

示例用例可以是使用httpd作为负载均衡器或代理。

答案取决于所考虑的操作系统。总的来说:

对于TCP,没有。同一时间只能有一个应用程序侦听同一端口。现在,如果您有2个网卡,您可以让一个应用程序在第一个IP上侦听,第二个应用程序在第二个IP上侦听,使用相同的端口号。

对于UDP (Multicasts),多个应用程序可以订阅同一个端口。

编辑:自Linux Kernel 3.9及更高版本以来,使用SO_REUSEPORT选项添加了对多个应用程序侦听同一端口的支持。更多信息可以在lwn.net文章中找到。