同一机器上的两个应用程序可以绑定到相同的端口和IP地址吗?更进一步,一个应用程序可以侦听来自某个IP的请求,而另一个应用程序可以侦听来自另一个远程IP的请求吗? 我知道我可以让一个应用程序启动两个线程(或分支)具有类似的行为,但是两个没有任何共同之处的应用程序也可以这样做吗?
当前回答
Yes.
从这篇文章中: https://lwn.net/Articles/542629/
新的套接字选项允许同一主机上的多个套接字绑定到同一个端口
其他回答
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画报,卷二。
我用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
简短的回答:
根据这里给出的答案。您可以让两个应用程序侦听相同的IP地址和端口号,只要其中一个端口是UDP端口,而另一个是TCP端口。
解释:
端口的概念与TCP/IP堆栈的传输层相关,因此只要使用堆栈的不同传输层协议,就可以让多个进程侦听相同的< IP -address>:<port>组合。
人们有一个疑问,如果两个应用程序运行在相同的<ip-address>:<端口>组合上,那么在远程机器上运行的客户机如何区分这两个应用程序?如果你看一下IP层数据包头(https://en.wikipedia.org/wiki/IPv4#Header),你会发现第72位到第79位是用来定义协议的,这就是如何区分的。
然而,如果你想让两个应用程序在相同的TCP < IP -address>:<port>组合上,那么答案是否定的(一个有趣的练习是启动两个vm,给它们相同的IP地址,但不同的MAC地址,看看会发生什么——你会注意到有些时候VM1将获得数据包,而其他时候VM2将获得数据包——这取决于ARP缓存刷新)。
我认为,通过让两个应用程序在相同的<op-address>:<端口>上运行,可以实现某种负载平衡。为此,您可以在不同的端口上运行应用程序,并编写IP表规则来划分它们之间的流量。
请参见@user6169806的回答。
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()绑定到该端口,除非已经有一个活动监听套接字绑定到该端口。这使您能够在崩溃后尝试重新启动服务器时绕过“地址已在使用”错误消息。
Yes.
从这篇文章中: https://lwn.net/Articles/542629/
新的套接字选项允许同一主机上的多个套接字绑定到同一个端口
推荐文章
- 我如何找到哪个程序正在使用端口80在Windows?
- WebSockets和纯TCP之间的根本区别是什么?
- 有效地测试Linux上的端口是否打开?
- 127.0.0.1和localhost之间的区别是什么
- 为什么SCTP不常用/不为人所知
- 无法启动IIS Express Web服务器,注册URL失败,访问被拒绝
- 我可以在/etc/hosts中映射主机名*和端口*吗?
- 如何修改Play执行run命令时使用的默认端口(9000)?
- 如何找到可用的端口?
- UDP和TCP比起来快多少?
- ssh -L转发多个端口
- 套接字的连接超时和读超时之间的区别是什么?
- 将主机端口转发到docker容器
- 远程主机强制关闭现有连接
- TCP连接的最大数据包大小