lsof stands for "list open files". So actually it shows all files used by some processes of a system. That command exist on most of linux derivates by default. It bases on architecture of a kernel which causes every process to hold it used files in /proc - (a virtual file-system). A typical hierarchy wold look like:
/proc/process id/fd/file descriptor
In the absence of any options, lsof lists all open files belonging to all active processes of a system. But that is to much for most cases, because many of cases are network related. An if you consider that sockets are files in linux we can use lsof to search for them too.
The interesting option here is the -i option and it should be followed by the Internet address which is specified in the following form:
4 and 6 stand for ip protocol versions, the rest should be self expanded. So now i think is best time to provide some examples. Here they are:
Show all open connections
Show all open TCP connections
lsof -i TCP
Show open TCP connection on on secure ldap port 636, http 80 and UDP protocol range
lsof -i TCP:636 lsof -i TCP:80 lsof -i UDP:3000-3025
Show LDAP *incoming * connections
lsof -i TCP@192.168.0.1:636 () #java 890 root 18u IPv6 8332031 #TCP myserver.com:42936 myserver.com:ldaps (ESTABLISHED)
Who uses SMTP?
lsof -i :25 #COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME #sendmail 401 root 5u IPv4 0x300023cc141 0t0 TCP *:smtp (LISTEN) #sendmail 401 root 6u IPv6 0x3000243c200 0t0 TCP *:smtp (LISTEN)
More Examples of lsof
-c option allows to see what files are open by a particular command.
lsof -c mysq lsof -c ruby
See what files are open by a particular device or a file
lsof /dev/cdrom lsof /tmp/obscure.lock
See what files are opened by a user shuron
lsof –u shuron #vi 5200 shuron txt REG 3,1 242601 245773 /bin/vi
And at last use -r option for monitoring. Here is example of periodically (every 10 seconds) refresh of connection status for a concrete application started as php.
lsof -r 10 -c php -a -i :1521
It gives periodically all 1521 port connections. 1521 is typical Oracle DB connection port, so that example may serve you as base for script that monitors connection growing of your PHP applications.
Next one uses the -t parameter which causes lsof return only a process id of a file using application. So following command allows you to kill all application that are using provided file.
kill -9 `lsof -t /tmp/obscure.lock`