Understanding lsof and lsof -i
What is lsof
?
lsof
(List Open Files) is a versatile command-line utility on UNIX and Linux systems that displays information about files opened by processes. Since UNIX treats many resources as files—including disk files, network sockets, and devices—lsof
can list:
- Regular files
- Directories
- Block and character devices
- Network sockets (TCP, UDP)
- Named pipes (FIFOs)
Why Use lsof
?
- Debug stuck files
Determine which process holds a file open, preventing unmounting or deletion. - Investigate network usage
Find which processes are listening on or connected to specific ports. - Security audits
Spot unexpected open sockets or file handles. - Resource leak detection
Track down processes that aren’t closing files properly.
Basic Syntax
lsof [options] [names or filters]
Common options:
-u <user>
Show files opened by a given user.-p <pid>
Show files opened by a specific process ID.+D <directory>
Recursively list all files opened under a directory tree.-c <command>
Filter output by command name.
Inspecting Network Ports: lsof -i :<portnumber>
The -i
filter restricts output to network files whose address matches the criteria. Appending :<portnumber>
limits results to that TCP or UDP port.
Usage
lsof -i :8080
What this does:
- Scans all Internet sockets (IPv4 & IPv6).
- Filters for port
8080
(both TCP and UDP). - Displays each process holding that port.
Sample Output
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 1045 root 6u IPv4 23456 0t0 TCP *:http-alt (LISTEN)
nginx 1046 www-data 6u IPv4 23456 0t0 TCP *:http-alt (LISTEN)
java 20501 ubuntu 10u IPv6 34567 0t0 TCP [::1]:8080->[::1]:53214 (ESTABLISHED)
- COMMAND: Process name (e.g.,
nginx
,java
) - PID: Process ID
- USER: Owner of the process
- FD: File descriptor (e.g.,
6u
means FD 6 in “u”—read/write—mode) - TYPE: Protocol (
IPv4
orIPv6
) - NAME: Local and, if applicable, remote endpoint details
Interpretation
- The first two lines show
nginx
listening on port 8080 (http-alt
) on all interfaces (*
). - The third line shows a
java
process with an established loopback connection from port 53214 to 8080.
Common Variations
- Show only listening TCP sockets on port 22
lsof -iTCP:22 -sTCP:LISTEN
- Filter by IP and port
lsof -i @192.168.1.100:3306
- List all open UDP sockets
lsof -i udp
Why It Matters
Knowing which process holds a port is crucial when:
- You can’t start a service because the port is already in use.
- You’re diagnosing unexpected network connections or potential intrusions.
- You’re performing routine system audits.
By mastering lsof
, you gain deep visibility into your system’s file and network activity, empowering you to troubleshoot effectively and keep your environment secure.