Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get open TCP port in Python [duplicate]

I want to get any random open TCP port on localhost in Python. What is the easiest way?

like image 761
Albert Avatar asked May 14 '10 23:05

Albert


2 Answers

My current solution:

def get_open_port():         import socket         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         s.bind(("",0))         s.listen(1)         port = s.getsockname()[1]         s.close()         return port 

Not very nice and also not 100% correct but it works for now.

like image 122
Albert Avatar answered Oct 24 '22 01:10

Albert


The free port can be found by binding a socket to a port selected by the operating system. After the operating system selects a port the socket can be disposed. However, this solution is not resistant to race conditions - in the short time between getting the free port number and using this port other process may use this port.

import socket  def find_free_port():     with socket.socket() as s:         s.bind(('', 0))            # Bind to a free port provided by the host.         return s.getsockname()[1]  # Return the port number assigned. 

https://godbolt.org/z/fs13K13dG

like image 24
Paweł Bylica Avatar answered Oct 24 '22 01:10

Paweł Bylica