get IP addresses a program wants to connect to

Viewed 93

my goal is that my code (C#) outputs the IP addresses another program is trying to connect to. Example: my browser.exe wants to connect to a website at 12.34.567.89 so my code would output that IP.

Note: my main trouble is to also list unsuccessful connection attempts as everything else Ive found seems to only work with established connections.

I don't have a lot of experience and this is my first post so anything could help. Thanks in advance

2 Answers

This answer is not pure C#, but links to example invocations written in C#.

In general on MS Windows platforms many of the tasks like in the question may be performed using WMI in WQL language.

To achieve the requested it's possible to query MSFT_NetTCPConnection class and use properties OwningProcess and RemoteAddress

select OwningProcess, RemoteAddress from MSFT_NetTCPConnection

You can execute queries to WMI with ManagementObjectSearcher. See examples here and here

In case it's required to get process details - another query can help

select * from Win32_Process where ProcessID = PID_FROM_NET_TCP_CONNECTION

Unfortunately it's not possible to join tables in WQL, but it's possible to create and register own WMI class combining required values resembling join behavior. For example like here. Or just handle it in your code.

I think Raw Sockets are well suited for these purposes.

new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

Try to see that example of raw sockets(you need replace _fcaptureIp with your ip)

Related