Search code examples
c#ippidetw

How can I monitor new IPv4 connections in C#


I need to monitor any new IPv4 connection made by a computer. The information I need is the process ID making the connection as well as the IP address the process is connecting to. I would need a callback function that gets called as soon as a new connection is discovered.

I have tried using ETW with Microsoft-Windows-Kernel-Network, but I only get integer representations of some daddr and saddr that I can't seem to map back to an IP address. Any help would be appreciated.


Solution

  • You should use the Microsoft-Windows-TCPIP provider. You can use TraceEvent to create a Realtime session, and TraceEvent has a KernelSourceParser which allows you to parse for IP data

    _kernelTraceEventParser = new KernelTraceEventParser(_source);
    _kernelTraceEventParser.TcpIpConnect += KernelParserOnTcpIpConnect;
    
    
    
    private void KernelParserOnTcpIpConnect(TcpIpConnectTraceData tcpIpConnectTraceData)
    {
         lokalAddress = tcpIpConnectTraceData.saddr + ":" + tcpIpConnectTraceData.sport;
         serverAddress = tcpIpConnectTraceData.daddr + ":" + tcpIpConnectTraceData.dport;
    }
    

    Because TcpIpConnectTraceData is inherit from TraceEvent class you have access to ProcessName and ProcessID.