开发者

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 prin开发者_如何学编程ted 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜