Monitoring network activity is a cornerstone of Linux system administration and cybersecurity auditing. When troubleshooting blocked services, port conflicts, or diagnosing unexpected network connections in Ubuntu, you must determine which applications own active network sockets. The lsof (List Open Files) utility treats network sockets as files, providing comprehensive real-time visibility into local IP bindings, remote connections, listening daemon states, and the exact Process IDs (PIDs) managing them.
Basic Syntax for Inspecting Network Sockets with lsof
Because socket descriptors are tied to system processes and kernel subsystems, running lsof for network auditing requires administrative privileges via sudo. The -i flag specifies network file inspection.
sudo lsof -i
By default, lsof attempts to resolve IP addresses to hostnames and port numbers to service names. This reverse DNS lookup can cause command delays. To speed up output dramatically, pass the -P (prevent port name resolution) and -n (prevent IP address resolution) flags:
sudo lsof -i -P -n
Filtering by Protocol: TCP vs UDP
You can isolate network traffic by transport protocol to focus specifically on reliable connection-oriented daemons or stateless datagram services:
# Display only open TCP sockets and connections
sudo lsof -i TCP -P -n
# Display only open UDP sockets and listeners
sudo lsof -i UDP -P -n
Listing Only Listening Network Ports
To detect server daemons (such as Nginx, Apache, OpenSSH, or PostgreSQL) that are actively waiting for incoming client connections, filter for the LISTEN state:
sudo lsof -i TCP -sTCP:LISTEN -P -n
The terminal will output clean columns including:
- COMMAND: The binary name executing the socket (e.g.
sshd,nginx). - PID: The process identification number.
- USER: The user account running the process (e.g.
root,www-data). - NODE: Transport protocol (
TCP). - NAME: The bound IP address and listening port (e.g.
0.0.0.0:22or127.0.0.1:3306).
Finding Which Process Owns a Specific Port
When starting a container or web server fails with an “Address already in use” error, you can pinpoint the offending process instantly by querying the port number directly:
# Check what process is occupying port 80
sudo lsof -i :80 -P -n
# Check what process is occupying port 8080
sudo lsof -i :8080 -P -n
Once you identify the conflicting Process ID (PID) from the output, you can inspect or terminate the daemon using sudo kill -15 <PID> or manage its systemd unit accordingly.