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


当前回答

Yes.

Multiple listening TCP sockets, all bound to the same port, can co-exist, provided they are all bound to different local IP addresses. Clients can connect to whichever one they need to. This excludes 0.0.0.0 (INADDR_ANY). Multiple accepted sockets can co-exist, all accepted from the same listening socket, all showing the same local port number as the listening socket. Multiple UDP sockets all bound to the same port can all co-exist provided either the same condition as at (1) or they have all had the SO_REUSEADDR option set before binding. TCP ports and UDP ports occupy different namespaces, so the use of a port for TCP does not preclude its use for UDP, and vice versa.

参考资料:Stevens & Wright, TCP/IP画报,卷二。

其他回答

Yes.

Multiple listening TCP sockets, all bound to the same port, can co-exist, provided they are all bound to different local IP addresses. Clients can connect to whichever one they need to. This excludes 0.0.0.0 (INADDR_ANY). Multiple accepted sockets can co-exist, all accepted from the same listening socket, all showing the same local port number as the listening socket. Multiple UDP sockets all bound to the same port can all co-exist provided either the same condition as at (1) or they have all had the SO_REUSEADDR option set before binding. TCP ports and UDP ports occupy different namespaces, so the use of a port for TCP does not preclude its use for UDP, and vice versa.

参考资料:Stevens & Wright, TCP/IP画报,卷二。

另一种方法是使用一个程序在一个端口上监听,该程序分析流量类型(ssh、https等),它将在内部重定向到另一个“真正的”服务正在监听的端口。

例如,对于Linux, sslh: https://github.com/yrutschle/sslh

如果至少有一个远程ip是已知的,静态的,专用于只与你的一个应用程序对话,你可以使用iptables规则(表nat,链PREROUTING)来重定向从这个地址到“共享”本地端口的传入流量到任何其他端口,其中适当的应用程序实际监听。

分享一下@jnewton提到的内容。 我在我的mac上启动了一个nginx和一个嵌入式tomcat进程。我可以看到两个进程都运行在8080。

LT<XXXX>-MAC:~ b0<XXX>$ sudo netstat -anp tcp | grep LISTEN
tcp46      0      0  *.8080                 *.*                    LISTEN     
tcp4       0      0  *.8080                 *.*                    LISTEN   

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

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

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

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