To see if a port in Linux is occupied (netstat,lsof)
The netstat command can display information such as network connections, routing tables, interface states, spoofing connections, network link information, and multicast member groups.
Command format: netstat [options]
Common parameters:
-A,--all displays all sockets that are or are not listening.
-P,--program displays the PID and name of the process to which the socket belongs.
-N,--numeric displays the numeric address instead of parsing the host, port, or user name.
Usage Example: View all process and port usage.
$ netstat–anp
Further, you can use the lsof command to display the process that occupies the port.
Command format: lsof-i: Port
NETSTAT-TUNLP will show all the ports and all the corresponding programs, and the GREP pipeline will filter out the key fields you want.
Make a list of the 22 port-occupied programs
[[email protected] tmp]# NETSTAT-TUNLP |grep 22tcp 0 0 0.0.0.0:42957 0.0.0.0:* LISTEN 2230/rpc.statd TCP 0 0 0.0.0.0:22 0 .0.0.0:* LISTEN 2443/sshd TCP 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 2292/cupsd TCP 0 0::::::* LISTEN 2443/sshd TCP 0 0:: 1:631:::* LISTEN 2292/cupsd TCP 0 0::: 57609:::* LISTEN 2230/rpc.statd UDP 0 0 0.0.0.0:5353 0.0.0.0:* 2211/avahi-daemon UDP 0 0 0.0.0.0:631 0.0.0.0:* 2292/cupsd UDP 0 0 0.0.0.0:37167 0.0.0.0:* 2230/rpc.statd UDP 0 0 0.0.0.0:52291 0.0.0.0:* 22 11/avahi-daemon UDP 0 0 0.0.0.0:68 0.0.0.0:* 2207/dhclient UDP 0 0 0.0.0.0:710 0.0.0.0:* 2230/rpc.statd UDP 0 0::: 39834: ::* 2230/rpc.statd
To view the occupancy of an end port: lsof-i: Port number
[[email protected] ~]# lsof-i:21command PID USER FD TYPE DEVICE SIZE NODE namepure-ftpd 2651 Root 4u IPv4 7047 TCP *:ftp (LISTEN) pure-ftpd 2651 root 5u IPv6 7048 TCP *:ftp (LISTEN)
This shows that port 21st is being used by PURE-FTPD and the state is listen.
NETSTAT-ANP display of System port usage
To see if a port in Linux is occupied (netstat,lsof)