How to associate a socket with one available port?

I need to associate my socket with a specific local IP address before connecting as a client.

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("192.168.1.2", 33333)) s.connect(("google.com", 80)) s.send("test") 

I know how to bind to a specific local IP address, but I do not know which port to specify. I cannot use a random port because it may already be used. Is there any way to bind to any available port?

+4
source share
1 answer

Yes, you should use 0 as the port. Then, the operating system will select the port for you, just as if you had not called bind .

+8
source

All Articles