Python - How to check if a port is in use

NOTE: This works on both Python 2.7 and Python 3.6.5

import socket

HOST = "localhost"
PORT = 443

# Creates a new socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Try to connect to the given host and port
if sock.connect_ex((HOST, PORT)) == 0:
print("Port " + str(PORT) + " is open") # Connected successfully
else:
print("Port " + str(PORT) + " is closed") # Failed to connect because port is in use (or bad host)

# Close the connection
sock.close()

If you’re executing this on Windows, you can add import os at the top and os.system('pause') at the bottom. That should prevent the python file from automatically closing, assuming you’re not executing this directly from the command line.

Also, I guess I should probably point out that “port … is open” means that the port is currently in use, whereas “port … is closed” means that it’s currently not in use.