Skip to content
Advertisement

Linux/Unix Socket Self-connection

When a client try to connect to a server, if client and server are both localhost, self-connection may happen(source port and destination port happened to be the same.). But my problem is, client is not listening to that port, how can self-connection be possible?

Advertisement

Answer

We can simple reproduce this phenomenon with the following python program

import socket
for i in range(65536):
  try:
    s = socket.create_connection(('127.0.0.1', 50000))
    print 'connected to {0}'.format(s.getpeername())
  except Exception as e:
    pass

when we try to connect some socket in the same host. if we don’t bind your client to a specific port, operating system will provide ephemeral port for you. if it’s happened to be the one you want to connect to. it causes self connection. Make sure the port you are trying to connect is in /proc/sys/net/ipv4/ip_local_port_range

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement