On Linux systems, there are several methods to determine when an active TCP connection was established. The most straightforward approach is using the ss
command with timestamp options:
ss -t -o state established '( sport = :22 or dport = :22 )'
This example shows established SSH connections (port 22) with timing information. The output includes:
- Connection state (established)
- Local and remote addresses
- Timer information showing connection duration
For more precise timing information, you can inspect the proc filesystem:
ls -l /proc/$(pgrep sshd)/fd | grep socket
cat /proc/net/tcp | grep -i "0A" # 0A is hex for ESTABLISHED state
The timestamp can be derived from the inode information and correlated with process start times.
For production systems requiring historical tracking, consider this SystemTap script:
probe kernel.function("tcp_set_state") {
if ($newstate == TCP_ESTABLISHED) {
printf("%s: %s:%d -> %s:%d\\n", ctime(gettimeofday_s()),
ip_ntop($sk->__sk_common.skc_rcv_saddr),
$sk->__sk_common.skc_num,
ip_ntop($sk->__sk_common.skc_daddr),
$sk->__sk_common.skc_dport)
}
}
Modern Linux kernels support eBPF for efficient connection monitoring:
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
struct event {
u32 saddr;
u32 daddr;
u16 sport;
u16 dport;
u64 timestamp;
};
SEC("kprobe/tcp_connect")
int bpf_prog(struct pt_regs *ctx) {
struct event ev = {};
ev.timestamp = bpf_ktime_get_ns();
// Populate other connection fields
bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU, &ev, sizeof(ev));
return 0;
}
When debugging network issues or monitoring system activity, you often need to check when a specific TCP connection was established. The standard netstat
command won't show this information, but Linux provides several alternative methods.
The modern replacement for netstat, ss
from iproute2 package, can display TCP timers including connection establishment time:
sudo ss -t -o state established '( dport = :443 || sport = :443 )'
This shows all established connections on port 443 with timer information. The timer:(keepalive,XXmin,YY)
field indicates how long the connection has been active.
For more precise timestamping, you can use this SystemTap script to track new connections:
probe kernel.tcp.accept {
printf("%s: New connection from %s:%d to %s:%d\n",
ctime(gettimeofday_s()), saddr, sport, daddr, dport)
}
Each active connection has an entry in /proc/net/tcp
containing creation time in jiffies:
cat /proc/net/tcp | grep -i "01BB"
The 10th field represents the connection duration in jiffies (1/100 sec on most systems). Convert it to seconds:
jiffies=$(awk '{print $10}' /proc/net/tcp_entry)
seconds=$((jiffies / 100))
For long-term tracking, use the conntrack tool which maintains connection state:
sudo conntrack -L -o extended | grep ESTABLISHED
This displays detailed timing information including start time for each tracked connection.