LLI Wiki — My Digital Knowledge Base

Find when an open TCP connection was created on Linux

List open TCP connections with lsof and timestamp their /proc file descriptors to estimate when each connection was opened.

On Linux, lsof lists the open TCP sockets with their process IDs. Combined with stat on the matching /proc/<pid>/fd/<fd> entries, it gives a timestamp for each open connection, sorted from most recent to oldest.

Command

lsof -P -i tcp | awk '{print $2,$4}' | tr -d 'u' | sort -u \
| while read pid fd; do stat --printf "%z %N\n" /proc/$pid/fd/$fd ; done | sort -r

%z prints the last change time of each /proc file descriptor entry.

Run with sudo

Processes owned by other users are only visible to root. The same pipeline can be run through sudo sh:

echo $'lsof -P -i tcp | awk \'{print $2,$4}\' | tr -d \'u\' | sort -u | while read pid fd; do stat --printf "%z %N\n" /proc/$pid/fd/$fd ; done | sort -r' | sudo sh
Mastodon LLIMastodon SocialFosstodon