同一机器上的两个应用程序可以绑定到相同的端口和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 (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.
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画报,卷二。
您可以让一个应用程序侦听一个网络接口的一个端口。因此你可以有:
HTTPD监听远程可访问的接口,例如192.168.1.1:80 另一个守护进程监听127.0.0.1:80
示例用例可以是使用httpd作为负载均衡器或代理。
原则上,没有。
这不是刻在石头上的;但这是所有api的编写方式:应用程序打开一个端口,获得它的句柄,当客户端连接(或UDP情况下的数据包)到达时,操作系统(通过该句柄)通知它。
如果操作系统允许两个应用程序打开同一个端口,它怎么知道该通知哪一个呢?
但是…有一些方法可以解决这个问题:
正如Jed所指出的,您可以编写一个“主”进程,这将是唯一一个真正侦听端口并通知其他端口的进程,使用任何它想要分离客户端请求的逻辑。 在Linux和BSD(至少)上,你可以设置“重映射”规则,将数据包从“可见”端口重定向到不同的端口(应用程序正在侦听的端口),根据任何与网络相关的标准(可能是原始网络,或一些简单的负载平衡形式)。
如果至少有一个远程ip是已知的,静态的,专用于只与你的一个应用程序对话,你可以使用iptables规则(表nat,链PREROUTING)来重定向从这个地址到“共享”本地端口的传入流量到任何其他端口,其中适当的应用程序实际监听。
推荐文章
- 我如何找到哪个程序正在使用端口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连接的最大数据包大小