Can two applications listen on the same port at the same time? Erik, 11 Aug 2017

We are integrating with an external system which makes to HTTP POST requests to an agreed URL. In order to learn about the exact format of the data posted to us, we set up a primitive server written in Python that logs the request body to a file and responds with a dummy response.

We kept this server running for several days while we were building our actual implementation. When we wanted to try out our implementation we decided to ssh into the server where the requests where coming to and port forward the traffic to our development machine. (ssh -R 8090:localhost:8090 user@server)

We expected the port forwarding to fail initially because our primitive server is already listening on the same port. To our great surprise it didn't fail. The forwarding was working just fine and we could test our implementation. We got disconnected from the server at some point and reconnected again when we needed to do more testing. To an even greater surprise - the primitive server had continued to receive requests after we had disconnected!

This was contrary to anything we had learned so far about sockets so we decided to investigate deeper how is this possible. We used netstat to see who is actually listening on that port:

$ sudo netstat -lp
tcp    0  0 *:8090             *:*           LISTEN      32256/python
tcp6   0  0 localhost:8090     [::]:*        LISTEN      4487/1


The primitive server was written in Python and it seems that it binds to all IPv4 interfaces on that machine. However ssh seems to bind to IPv6 localhost interface where no-one is listening on that port.

The system we are integrating with was running on that same machine and was configured to make requests with URL http://localhost:8090/. It seems that there is a hierarchy in place where localhost:8090 is first picked up by the IPv6 stack and if no-one is listening there then IPv4 gets a chance.

So when we had the ssh tunnel in place then IPv6 was used and we got all the requests to our development machine. However when we disconnected then IPv4 was used and our primitive logger server handled the requests.

This is a nice feature of the network stack and something that could be utilized again in the future.