Can two applications listen to the same port?

2018-12-31 08:31发布

Can two applications on the same machine bind to the same port and IP address? Taking it a step further, can one app listen to requests coming from a certain IP and the other to another remote IP? I know I can have one application that starts off two threads (or forks) to have similar behavior, but can two applications that have nothing in common do the same?

16条回答
若你有天会懂
2楼-- · 2018-12-31 09:20

Another way is use a program listening in one port that analyses the kind of traffic (ssh, https, etc) it redirects internally to another port on which the "real" service is listening.

For example, for Linux, sslh: https://github.com/yrutschle/sslh

查看更多
只若初见
3楼-- · 2018-12-31 09:21

For TCP, no. You can only have one application listening on the same port at one time. Now if you had 2 network cards, you could have one application listen on the first IP and the second one on the second IP using the same port number.

For UDP (Multicasts), multiple applications can subscribe to the same port.

查看更多
情到深处是孤独
4楼-- · 2018-12-31 09:21

If by applications you mean multiple processes then yes but generally NO. For example Apache server runs multiple processes on same port (generally 80).It's done by designating one of the process to actually bind to the port and then use that process to do handovers to various processes which are accepting connections.

查看更多
查无此人
5楼-- · 2018-12-31 09:24

I have tried the following, with socat:

socat TCP-L:8080,fork,reuseaddr -

And even though I have not made a connection to the socket, I cannot listen twice on the same port, in spite of the reuseaddr option.

I get this message (which I expected before):

2016/02/23 09:56:49 socat[2667] E bind(5, {AF=2 0.0.0.0:8080}, 16): Address already in use
查看更多
有味是清欢
6楼-- · 2018-12-31 09:25

Yes and no. Only one application can actively listen on a port. But that application can bequeath its connection to another process. So you could have multiple processes working on the same port.

查看更多
闭嘴吧你
7楼-- · 2018-12-31 09:25

You can make two applications listen for the same port on the same network interface.

There can only be one listening socket for the specified network interface and port, but that socket can be shared between several applications.

If you have a listening socket in an application process and you fork that process, the socket will be inherited, so technically there will be now two processes listening the same port.

查看更多
登录 后发表回答