Checking Port Usage in Linux
Category Programming Techniques
In Linux, you can check port usage with the lsof and netstat commands.
lsof
lsof (list open files) is a tool that lists the files currently opened by the system.
Syntax for using lsof to check port usage:
lsof -i:port_number
Example
Check the port usage of the server at port 8000:
# lsof -i:8000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nodejs 26993 root 10u IPv4 37999514 0t0 TCP *:8000 (LISTEN)
It can be seen that port 8000 has been occupied by the light nodejs service.
Executing lsof -i requires root user privileges, as shown in the figure below:
More lsof commands are as follows:
lsof -i:8080: Check port 8080 usage
lsof abc.txt: Show processes that have opened the file abc.txt
lsof -c abc: Show files currently opened by the abc process
lsof -c -p 1234: List files opened by the process with process ID 1234
lsof -g gid: Show the process status belonging to gid
lsof +d /usr/local/: Show files opened by processes in the directory
lsof +D /usr/local/: Same as above, but searches directories within the directory, takes longer
lsof -d 4: Show processes using fd as 4
lsof -i -U: Show all open ports and UNIX domain files
netstat
netstat -tunlp
is used to display the status of tcp, udp ports, and related processes.
Syntax for using netstat to check port usage:
netstat -tunlp | grep port_number
-t (tcp) Only show tcp-related options
-u (udp) Only show udp-related options
-n Refuse to display aliases, convert all numbers to numbers
-l Only list services in the Listen (listening) state
-p Show the name of the program that has established a related link
# netstat -tunlp | grep 8000 tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 26993/nodejs
More commands:
netstat -ntlp //View all current tcp ports
netstat -ntulp | grep 80 //View all 80 port usage
netstat -ntulp | grep 3306 //View all 3306 port usage
kill
After finding the process that occupies the port, if you want to kill the corresponding process, you can use the kill command:
kill -9 PID
As in the example above, we see that the PID corresponding to port 8000 is 26993, and use the following command to kill the process:
kill -9 26993
** Click to Share Notes
-
-
-