同一机器上的两个应用程序可以绑定到相同的端口和IP地址吗?更进一步,一个应用程序可以侦听来自某个IP的请求,而另一个应用程序可以侦听来自另一个远程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
其他回答
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画报,卷二。
如果你所说的应用程序是指多个进程,那么是,但通常不是。 例如Apache服务器在同一个端口上运行多个进程(通常是80)。它通过指定一个进程实际绑定到端口,然后使用该进程向接受连接的各个进程进行切换来实现。
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/
新的套接字选项允许同一主机上的多个套接字绑定到同一个端口
如果至少有一个远程ip是已知的,静态的,专用于只与你的一个应用程序对话,你可以使用iptables规则(表nat,链PREROUTING)来重定向从这个地址到“共享”本地端口的传入流量到任何其他端口,其中适当的应用程序实际监听。
推荐文章
- UDP和TCP比起来快多少?
- ssh -L转发多个端口
- 套接字的连接超时和读超时之间的区别是什么?
- 将主机端口转发到docker容器
- 远程主机强制关闭现有连接
- TCP连接的最大数据包大小
- HTTP 1.1和HTTP 2.0的区别是什么?
- connectexception:拒绝连接
- Docker -绑定0.0.0.0:4000失败:端口已经分配
- Node.js中的process.env.PORT是什么?
- 互联网上最大的安全UDP包大小是多少
- 关闭vs关闭套接字?
- 在套接字编程中AF_INET和PF_INET的区别是什么?
- read()和recv(), send()和write()之间有什么区别?
- mysqld_safe UNIX套接字文件目录“/var/run/mysqld”不存在