2

I have a windows services that bind to some TCP port, this port is use for IPC between my application.

Is there a programming (WinAPI/WinSocket and etc) way to know which application connected to my port?

i.e. in my Windows Services I would like to get a PID of the process that connected to my port.

Jon Seigel
  • 12,251
  • 8
  • 58
  • 92
Baget
  • 3,318
  • 1
  • 24
  • 44
  • This is similar to my problem: http://stackoverflow.com/questions/819708/pid-from-socket-number-on-windows The answer is moreless the same. – smok1 May 13 '09 at 11:36

2 Answers2

3

If you're looking for WinAPI way of doing the same as netstat. You probably want the following API: GetExtendedTcpTable

Look for the results with TCP_TABLE_OWNER_PID_ALL argument.

The resulting MIB_TCPTABLE_OWNER_PID structure has many MIB_TCPROW_OWNER_PID structures that has dwOwningPid which is the process ID you are looking for.

m_vitaly
  • 11,856
  • 5
  • 47
  • 63
  • This is supported on WinXP SP2+. If you look for older versions compatibility look for AllocateAndGetTcpExTableFromStack API. – m_vitaly May 05 '09 at 19:35
  • Sorry, but this was not my questions, I wanted to know the PID of the application that connected to my port, not the PID of the application that bind to the port. – Baget May 06 '09 at 06:32
  • You can't know that from remote machine. You only know the source port and IP. – m_vitaly May 06 '09 at 11:02
  • Your question is not so clear. In case you are looking for the PID of a LOCAL application that is connected to some local service, you can use GetExtendedTcpTable or AllocateAndGetTcpExTableFromStack to see both sides: the listening one and the connecting one. – m_vitaly May 06 '09 at 11:05
  • If that was helpful do you mind raising the rating of this answer ? – m_vitaly May 07 '09 at 19:44
0

If you mean what process is using (listening on or connected using) your ports, use the following command:

netstat -a -b -o -n

-a will show you all connection (even if they in LISTENING state)

-b will show you the application executable that uses that port

-o will show you the PID of the application

-n will not do dns translations (you probably don't need these for knowing about the application), not necessary

m_vitaly
  • 11,856
  • 5
  • 47
  • 63