Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading