How to check if a network port is open? How to check if a network port is open? python python

How to check if a network port is open?


You can using the socket module to simply check if a port is open or not.

It would look something like this.

import socketsock = 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"sock.close()


If you want to use this in a more general context, you should make sure, that the socket that you open also gets closed. So the check should be more like this:

import socketfrom contextlib import closingdef check_socket(host, port):    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:        if sock.connect_ex((host, port)) == 0:            print "Port is open"        else:            print "Port is not open"


For me the examples above would hang if the port wasn't open. Line 4 shows use of settimeout to prevent hanging

import socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.settimeout(2)                                      #2 Second Timeoutresult = sock.connect_ex(('127.0.0.1',80))if result == 0:  print 'port OPEN'else:  print 'port CLOSED, connect_ex returned: '+str(result)