How do I bind a socket to one available port?

bind, python, sockets

Solution

Yes, you should use 0 as the port. The operating system will then choose the port for you, the same way it would do if you had not called `bind`.

Problem

I need to bind my socket to specific local IP 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 don't know which port to specify. I can't use a random port, because it may be already in use. Is there a way to bind to any available port?

Original source