Socket getting created with same IP and port on local host

linux, networking, sockets, tcp

Solution

A connection is identified by a 4-tuple ((source ip, source port), (target ip, target port)), and the source and target ports could conceivably be the same without any issues. This connection could even be established by one process, which would lead to the output you're seeing.

However, I just got bitten by a nasty bug, where a client socket would try to connect to a server socket with a port number in the ephemeral port range on the same machine. The connection operation would be retried operation until it succeeded.

The retry feature was the issue: if the server application wasn't running AND the source port that got picked at random was the same as the target port (which is possible because the target port was in the ephemeral range), the client socket would CONNECT TO ITSELF (which was wreaking havoc on the internal logic of the client application, you can imagine).

Since the client was performing retries as quickly as possible, the 1 in 30.000 odds that this can happen were hit quickly enough.

The following Python script reproduces it:

import socket

host = 'localhost'
port = 35911

ctr = 0
while True:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(5)
        ctr += 1
        s.connect((host, port))
        print "Connected to self after", ctr, "tries"
        break
    except socket.error, e:
        print e
        # Retry

Problem

I am seeing weird behavior on Linux where I am seeing that remote end and local end are both showing same IP and port combination. Following is the netstat output netstat -anp | grep 6102 tcp 0 0 139.185.44.123:61020 0.0.0.0:* LISTEN 3361/a.out tcp 0 0 139.185.44.123:61021 139.185.44.123:61021 ESTABLISHED 3361/a.out Can anyone tell me if this is even possible ? If yes, then what could be the scenario ?

Original source