Like netstat
you can ask the kernel directly. Its info comes from /proc/net/tcp
and /proc/net/tcp6
. Both files are formatted in the same way and are slightly (cough) harder to read that the netstat
output, but are language independent
This is a chopped and slightly masked sample output:
$ cat /proc/net/tcp
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 00000000:0385 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 5126 1 f4807080 100 0 0 10 -1
1: 00000000:2328 00000000:0000 0A 00000000:00000000 00:00000000 00000000 113 0 5264 1 f62ff540 100 0 0 10 -1
2: 00000000:008B 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 4535 1 f5bf1540 100 0 0 10 -1
9: 0200000A:08AE xxxxxxxx:D512 01 00000030:00000000 01:00000018 00000000 0 0 759198 4 f63e95c0 24 4 3 10 19
10: 0200000A:0D9B xxxxxxxx:7582 01 00000000:00000000 00:00000000 00000000 113 0 634192 1 f63e90c0 21 4 22 5 3
The key fields you're looking at at the hex following the :
under local_address
(Local port) and the st
column (Status).
The status columns are referred to in the kernel source ./include/net/tcp_states.h
, but helpfully someone has asked the question over on StackExchange: https://stackoverflow.com/questions/5992211/list-of-possible-internal-socket-statuses-from-proc
I'll duplicate here for completeness:
enum {
TCP_ESTABLISHED = 1,
TCP_SYN_SENT,
TCP_SYN_RECV,
TCP_FIN_WAIT1,
TCP_FIN_WAIT2,
TCP_TIME_WAIT,
TCP_CLOSE,
TCP_CLOSE_WAIT,
TCP_LAST_ACK,
TCP_LISTEN,
TCP_CLOSING, /* Now a valid state */
TCP_MAX_STATES /* Leave at the end! */
};
As one of the comments states, this is an enum
so the states are numbered sequentially from 1. Mostly you're looking for 0A
(LISTENING) and 01
(ESTABLISHED)
NB: To find out where netstat was getting this info from, I ran strace -e open,write netstat -an
.
There's a deeper dive into the field headers, here: http://www.onlamp.com/pub/a/linux/2000/11/16/LinuxAdmin.html