def get_unused_port():
 def try_bind(port, socket_type, socket_proto):
  s = socket.socket(socket.AF_INET, socket_type, socket_proto)
  try:
   s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
   s.bind(('', port))
   return s.getsockname()[1]
  except socket.error:
   return None
  finally:
   s.close()
 while True:
  port = try_bind(0, socket.SOCK_STREAM, socket.IPPROTO_TCP)
  if (port and try_bind(port, socket.SOCK_DGRAM, socket.IPPROTO_UDP)):
   return port

def get_unused_port ( ) : def try_bind ( port , socket_type , socket_proto ) : s = socket . socket ( socket . AF_INET , socket_type , socket_proto ) try : s . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) s . bind ( ( '' , port ) ) return s . getsockname ( ) [ 1 ] except socket . error : return None finally : s . close ( ) while True : port = try_bind ( 0 , socket . SOCK_STREAM , socket . IPPROTO_TCP ) if ( port and try_bind ( port , socket . SOCK_DGRAM , socket . IPPROTO_UDP ) ) : return port
finds a semi-random available port .