NPE
NPE

Reputation: 500277

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.

Upvotes: 2

Views: 949

Answers (2)

Devon_C_Miller
Devon_C_Miller

Reputation: 16518

The information nos refers to is available from C with:

#include <linux/tcp.h>
...
struct tcp_info info;
socklen_t optlen;
getsockopt(sd, IPPROTO_TCP, TCP_INFO, &info, &optlen)

Unfortunately, as this is Linux specific, it is not exposed through the Java Socket API. If there is a way to obtain the raw file descriptor from the socket, you might be able to implement this as a native method.

I do not see a way to get to the descriptor. However, it might be possible with your own SocketImplFactory and SocketImpl.

It's probably worth noting that the TCP(7) manual page says this re TCP_INFO:

This option should not be used in code intended to be portable.

Upvotes: 2

nos
nos

Reputation: 229088

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.

Upvotes: 1

Related Questions