[Windows specific answer]
On Windows, you might consider using ETW (Event Tracing for Windows). In general, ETW is the technology used to provide tracing / logging information on Windows, and most Microsoft programs are already equipped with ETW providers that you can use. In your case, I think that the Microsoft-Windows-TCPIP provider has information (for example, local / remote address and port, operation, sent / received bytes, etc.) that may be useful to you.
For example, I was able to start collecting TCPIP events into a file using the command:
logman start MyTcpipLog -p Microsoft-Windows-TCPIP -ets
And stop with
logman stop MyTcpipLog -ets
Then, the MyTcipipLog.etl file can be opened using several different tools (for example, xperf), but there are APIs that you can use to analyze this file yourself.
If you want to do this at run time, you can create a “real-time” ETW session to process events as they arrive at.
If you are new to ETW, here is a useful article on MSDN that I used.
Matt
source share