Can two applications listen to the same port?

前端 未结 17 1225
天涯浪人
天涯浪人 2020-11-22 03:50

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 othe

17条回答
  •  面向向阳花
    2020-11-22 04:20

    In principle, no.

    It's not written in stone; but it's the way all APIs are written: the app opens a port, gets a handle to it, and the OS notifies it (via that handle) when a client connection (or a packet in UDP case) arrives.

    If the OS allowed two apps to open the same port, how would it know which one to notify?

    But... there are ways around it:

    1. As Jed noted, you could write a 'master' process, which would be the only one that really listens on the port and notifies others, using any logic it wants to separate client requests.
      • On Linux and BSD (at least) you can set up 'remapping' rules that redirect packets from the 'visible' port to different ones (where the apps are listening), according to any network related criteria (maybe network of origin, or some simple forms of load balancing).

提交回复
热议问题