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


当前回答

分享一下@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   

其他回答

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画报,卷二。

不。一次只能有一个应用程序绑定到一个端口,强制绑定时的行为是不确定的。

使用多播套接字(听起来与您想要的相距甚远),只要在每个套接字的选项中设置SO_REUSEADDR,就可以有多个应用程序绑定到一个端口。

您可以通过编写一个“主”进程来实现这一点,该进程接受并处理所有连接,然后将它们交给需要侦听同一端口的两个应用程序。这是Web服务器等采用的方法,因为许多进程需要侦听80。

除此之外,我们将讨论细节——您同时标记了TCP和UDP,是哪个?还有,什么平台?

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

如果你所说的应用程序是指多个进程,那么是,但通常不是。 例如Apache服务器在同一个端口上运行多个进程(通常是80)。它通过指定一个进程实际绑定到端口,然后使用该进程向接受连接的各个进程进行切换来实现。

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

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