0

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!

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks :) your solution is exactly what I was searching for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.