Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind a socket to one available port?

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?

like image 300
artyomboyko Avatar asked Feb 20 '23 03:02

artyomboyko


1 Answers

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.

like image 111
lvella Avatar answered Feb 25 '23 16:02

lvella