Use lsof instruction in terminal to quickly view port information

Sometimes we need to know which port is being used by which process / application in the computer. At this time, we need a very convenient instruction: lsof
The command lsof means list open files. In unix system, everything is file, including tcp/udp connection.
Example: lsof -n -P -i TCP | grep LISTEN
flag:
-n refers to number instead of letter display
-P refers to port displayed by numbers instead of letters
-i refers to internet related protocols, where we specify TCP
|grep LISTEN searches for results with "LISTEN" i n all results given by the current instruction lsof -n -P -i TCP
For example:

caoda1@CaoDas-MBP:~/Documents$ lsof -n -P -i TCP | grep LISTEN
pycharm     407 caoda1  143u  IPv4 0x15532e64ce8c66af      0t0  TCP 127.0.0.1:6942 (LISTEN)
pycharm     407 caoda1  222u  IPv4 0x15532e64d4531a8f      0t0  TCP 127.0.0.1:63342 (LISTEN)
rapportd    449 caoda1    3u  IPv4 0x15532e64ce3bd6af      0t0  TCP *:56197 (LISTEN)
rapportd    449 caoda1    4u  IPv6 0x15532e64ce3e5007      0t0  TCP *:56197 (LISTEN)
com.apple   631 caoda1   45u  IPv4 0x15532e64d9f7a6af      0t0  TCP *:60496 (LISTEN)
com.apple   631 caoda1   48u  IPv6 0x15532e64ce3e6147      0t0  TCP *:60497 (LISTEN)
mongod      673 caoda1    6u  IPv4 0x15532e64d1a763ef      0t0  TCP 127.0.0.1:27017 (LISTEN)
BlueJeans   695 caoda1    3u  IPv4 0x15532e64ce3bba8f      0t0  TCP 127.0.0.1:18171 (LISTEN)
Adobe\x20   831 caoda1   10u  IPv4 0x15532e64d453112f      0t0  TCP 127.0.0.1:15292 (LISTEN)
Avast\x20   849 caoda1    4u  IPv6 0x15532e64ce3e4a47      0t0  TCP *:27275 (LISTEN)
mysqld    39165 caoda1   28u  IPv4 0x15532e64fa16c6af      0t0  TCP 127.0.0.1:3306 (LISTEN)

We can see: application name, process id, ip address and port number, as well as their status of being listed
If I just want to know which port mysql is using, just:

caoda1@CaoDas-MBP:~/Documents$ lsof -n -P -i TCP | grep mysql
mysqld     887 caoda1   29u  IPv4 0x21154199f4055439      0t0  TCP 127.0.0.1:3306 (LISTEN)

We can clearly see that mysql is using the 3306 port.

Tags: Linux lsof MySQL Pycharm Unix

Posted on Fri, 01 Nov 2019 12:30:52 -0700 by riffy