Search code examples
javacnetwork-programmingnetstat

Netstat for a single connection?


On Linux, is there any way to programmatically get stats for single TCP connection? The stats I am looking for are the sort that are printed out by netstat -s, but for a single connection rather than in the aggregate across all connections. To give some examples: bytes in/out, retransmits, lost packets and so on.

I can run the code within the process that owns the socket, and it can be given the socket file descriptor. The code that sends/receives data is out of reach though, so for example there's no way to wrap recv()/send() to count bytes in/out.

I'll accept answers in any language, but C or Java are particularly relevant hence the tags.


Solution

  • Most of the statistics you see with netstat -s is not kept track of on a per connection basis, only overall counters exists.

    What you can do, is pull out the information in /proc/net/tcp

    First, readlink() on /proc/self/fd, you want to parse the inode number from that symlink, and match it against a line with the same inode number in /proc/net/tcp , which will contain some rudimentary info about that socket/connection. That fil is though not very well documented, so expect to spend some time on google and reading the linux kernel source code to interpret them.