2

I have a project where I spawn subprocesses, which again take a port number to bind to. The port number is assigned by my Python script, where I simply take a random port between 49152 and 65535.

I want to verify if the port is available and not used by any other tool on the local system (*nix).

From another question I have this snippet:

import socket;
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
   print "Port is open"
else:
   print "Port is not open"

Could I use this in my case? Would this not open a port and not close it for further use?

Community
  • 1
  • 1
SaAtomic
  • 619
  • 1
  • 12
  • 29
  • 1
    Possible duplicate of [On localhost, how to pick a free port number?](http://stackoverflow.com/questions/1365265/on-localhost-how-to-pick-a-free-port-number) – TessellatingHeckler Apr 07 '17 at 06:18
  • @TessellatingHeckler This is indeed very similar, but I just want to see if the random port is available. The python script should never really use it for itself. – SaAtomic Apr 07 '17 at 06:29
  • 1
    This approach is intrinsically open to failure, because you have a race condition between the check and the actual usage - what if in the meantime somebody else stole that port? – Matteo Italia Apr 07 '17 at 07:26

2 Answers2

4

Simply create a temporary socket and then try to bind to the port to see if it's available. Close the socket after validating that the port is available.

def tryPort(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = False
    try:
        sock.bind(("0.0.0.0", port))
        result = True
    except:
        print("Port is in use")
    sock.close()
    return result
selbie
  • 100,020
  • 15
  • 103
  • 173
  • 2
    Could you use a [context manager](https://docs.python.org/2/library/contextlib.html#contextlib.closing)? `with closing socket(...` – Peter Wood Apr 07 '17 at 06:36
  • 1
    See also [How to use socket in Python as a context manager?](http://stackoverflow.com/questions/16772465/how-to-use-socket-in-python-as-a-context-manager) – Peter Wood Apr 07 '17 at 06:44
1

The code is fine, it creates a socket and tries to connect. It wont open or close any ports. You just need to add this line at the end to colose the socket : sock.close()

t.m.adam
  • 15,106
  • 3
  • 32
  • 52