How to Check Port Usage in Linux

(Add to your favorites for Linux enthusiasts to enhance Linux skills)

Source: Zifimu

www.cnblogs.com/wangtao1993/p/6144183.html

Today, I want to write a small program in Python to detect whether specific service ports are occupied. I suddenly realized that I didn’t know how to check port usage in Linux. Oh no, I need to learn this quickly. 😁

How to Check Ports in Linux

1. Use lsof -i:port_number to check the usage of a specific port. For example, to check the usage of port 8000, use lsof -i:8000.

# lsof -i:8000
COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
lwfs    22065 root    6u  IPv4 4395053      0t0  TCP *:irdmi (LISTEN)

You can see that port 8000 is already occupied by the lightweight file system forwarding service lwfs.

2. Use netstat -tunlp | grep port_number to check the process status of a specified port. For example, to check the status of port 8000, use netstat -tunlp | grep 8000.

# netstat -tunlp 
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      4814/rpcbind        
tcp        0      0 0.0.0.0:5908                0.0.0.0:*                   LISTEN      25492/qemu-kvm      
tcp        0      0 0.0.0.0:6996                0.0.0.0:*                   LISTEN      22065/lwfs          
tcp        0      0 192.168.122.1:53            0.0.0.0:*                   LISTEN      38296/dnsmasq       
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      5278/sshd           
tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN      5013/cupsd          
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      5962/master         
tcp        0      0 0.0.0.0:8666                0.0.0.0:*                   LISTEN      44868/lwfs          
tcp        0      0 0.0.0.0:8000                0.0.0.0:*                   LISTEN      22065/lwfs

# netstat -tunlp | grep 8000
tcp        0      0 0.0.0.0:8000                0.0.0.0:*                   LISTEN      22065/lwfs          

Let me explain the meaning of several parameters:

-t (tcp) only shows TCP-related options
                                 -u (udp) only shows UDP-related options
                                 -n refuse to display aliases, convert all displayable numbers to numbers
                                 -l only lists services in the Listen state
                                 -p shows the program name that established the related connection

Additionally, here is a Python program for monitoring port usage, which can check whether a specified IP’s port is occupied.

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import socket, time, thread
socket.setdefaulttimeout(3) # Set default timeout

def socket_port(ip, port):
    """
    Input IP and port number, scan to determine if the port is occupied
    """
    try:
        if port >=65535:
            print u'Port scan finished'
        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result=s.connect_ex((ip, port))
        if result==0:
            lock.acquire()
            print ip,u':',port,u'port is occupied'
            lock.release()
    except:
        print u'Port scan exception'

def ip_scan(ip):
    """
    Input IP, scan the port status of IP from 0 to 65534
    """
    try:
        print u'Starting scan %s' % ip
        start_time=time.time()
        for i in range(0,65534):
            thread.start_new_thread(socket_port,(ip, int(i)))
        print u'Scan completed, total time: %.2f' %(time.time()-start_time)
#       raw_input("Press Enter to Exit")
    except:
        print u'Error scanning IP'

if __name__=='__main__':
    url=raw_input('Input the ip you want to scan: ')
    lock=thread.allocate_lock()
    ip_scan(url)      

The execution result of this program is as follows:

# python scan_port.py
Input the ip you want to scan: 20.0.208.112
Starting scan 20.0.208.112
20.0.208.112 : 111 port is occupied
20.0.208.112 : 22 port is occupied
20.0.208.112 : 8000 port is occupied
20.0.208.112 : 15996 port is occupied
20.0.208.112 : 41734 port is occupied
Scan completed, total time: 9.38

Recommended Reading

(Click the title to jump to read)

How to Discover Hidden Processes and Ports

Comic: The Battle for Port 80

The Story Behind SSH Protocol Port 22

Did you gain something from this article? Please share it with more people.

Follow “Linux Enthusiasts” and add to favorites to enhance Linux skills.

How to Check Port Usage in Linux

If you like it, just give it a thumbs up~

Leave a Comment