0

How can I find which process is using a given TCP port? I know I can call out to netstat (How can you find out which process is listening on a port on Windows?), but if it's not too difficult I'd prefer to use the Windows API directly instead of launching an external process and parsing its output. I can see that netstat uses functions like GetTcpTable and GetOwnerModuleFromTcpEntry but I don't see how to connect those to a process id.

bmm6o
  • 5,719
  • 3
  • 26
  • 51

2 Answers2

1

Use the GetTcpTable / GetTcp6Table / GetUdpTable / GetUdp6Table functions, I am not aware of any way to do this without walking the table yourself (that is, you can't query directly by port number). And you have to use different calls for tcp, tcp6, udp and udp6.

SoronelHaetir
  • 11,346
  • 1
  • 8
  • 18
  • 1
    but `GetTcpTable` return `MIB_TCPROW` which not containing information about process owning port. need use `GetExtendedTcpTable` with `TCP_TABLE_OWNER_PID_*` here. and so on – RbMm Dec 05 '17 at 20:16
  • Thanks @RbMm, that's exactly the piece I was missing. If either of you want to make a complete answer that would be great. – bmm6o Dec 05 '17 at 22:16
0

GetExtendedTcpTable is the function you need to call, with one of the flags that indicates you want the owning process id (TCP_TABLE_OWNER_PID_*). This will cause it to return a MIB_TCPTABLE_OWNER_PID structure, which contains an array of MIB_TCPROW_OWNER_PID. There is a flag to specify if you want IPv4 or IPv6. For Udp, there is GetExtendedUdpTable with similar behavior.

bmm6o
  • 5,719
  • 3
  • 26
  • 51