views:

1939

answers:

4

As simple as it gets - can two application 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?

thanks.

+11  A: 

For TCP/IP, no. You can only have one application listening on a single 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.

Chris Dail
"one application listening on a single port" that's the reason why ports exist -- to allow multiple applications to share the network without conflicts.
S.Lott
One listener per port per IP address. Adding another network interface is a way to get a second IP address. Your platform probably supports virtual interfaces which is another way to get two IP addresses with one physical network card.
John M
+2  A: 

No. Only one application can bind to a port at a time, and behavior if the bind is forced is indeterminate.

With multicast sockets -- which sound like nowhere near what you want -- more than one application can bind to a port as long as SO_REUSEADDR is set in each socket's options.

You could accomplish this by writing a "master" process, which accepts and processes all connections, then hands them off to your two applications who need to listen on the same port. This is the approach that Web servers and such take, since many processes need to listen to 80.

Beyond this, we're getting into specifics -- you tagged both TCP and UDP, which is it? Also, what platform?

Jed Smith
both are of interest to me. The platform is windows, but if the answer is different for Linux, it would be nice to know
nadiv
+3  A: 

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 the the only one that really has the port and notifies others, using any logic it wants to separate client requests.
  2. 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 balance).
Javier
`iptables -m statistic --mode random --probability 0.5` is fun.
Jed Smith
@Jed: +1 for sheer awesomeness.
Paul Lammertsma
A: 

Yes, it happened to me, as described here

Jader Dias