Home > other >  Find OS generated port before using socket.connect() in Python
Find OS generated port before using socket.connect() in Python

Time:12-21

I would like to ask if there any way to to create a socket in Python, using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

And then, extract the port which going to be generated by the OS, before using:

sock.connect((SERVER_IP, SERVER_PORT)

i.e. my goal is to find the source port of the first SYN packet which will be sent to the server, as part of the 3-way handshake, before actually executing the 3-way handshake.

Note: I figured out that finding out the generated port is possible using:

generated_port = sock.getsockname()[1]

But, unfortunately, the value of generated_port is set just after using sock.connect().

Any help will be much appreciated!

CodePudding user response:

The local port is only available after the socket is bound to a local IP and port. If not explicitly done by calling bind this will be implicitly done doing connect. Therefore to get the local port before calling connect one has to explicitly call bind before that:

import socket
s = socket.socket()
s.bind(('0.0.0.0',0))
print(s.getsockname()[1])  
s.connect((host,port))
  • Related