How to Quickly Detect Occupied Linux Ports with Python
This guide shows how to use Linux commands such as lsof and netstat to identify occupied ports, explains the meaning of key parameters, and provides a Python script that monitors specified IP ports for availability, complete with example output.
Today I needed a small Python program to probe ports and discovered I didn't know how to check occupied ports on Linux.
How to view occupied ports on Linux
1. lsof -i:<port> – shows which process is using a specific port, e.g., lsof -i:8000.
2. netstat -tunlp | grep <port> – displays the process details for a given port, e.g., netstat -tunlp | grep 8000.
The above commands reveal that port 8000 is occupied by the lightweight file system forwarding service lwfs .
Explanation of the parameters used in the commands is provided in the accompanying image.
Below is a Python script that checks whether a specified IP and port are occupied:
import socket
def is_port_open(ip, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
try:
s.connect((ip, port))
return True
except socket.error:
return False
if __name__ == "__main__":
ip = "127.0.0.1"
port = 8000
if is_port_open(ip, port):
print(f"Port {port} on {ip} is occupied")
else:
print(f"Port {port} on {ip} is free")The script’s execution result is shown in the following image.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
