Tuesday, January 9, 2007

How to get all TCP/UDP ports in the system.

Recently my friend asked me how she can list all the opened TCP ports in the PC. After a quick search in google i found a utility netstat.exe.If you give the command netstat -p tcp this will lists all the established ports in the system. Established means TCP connection established .For getting all ports (which are in any state , like listeing , established etc) give netstat -a -p tcp. if we give netstat -b this will give the process name also, which opened this port.
 Fine.. But my friend need some functions not this exe. I have heared about functions like GetTcpTable and GetUdpTable . This functions gives information similar to netstat gives like local port , local ip , remote port ,remote ip. But it hides the process identifier. so is not possible to know the port owners. This leads me to open the utility came with Visual studio 6 . it is famous Depdency checker. the netstat.exe is in system32 folder. I opened the netstat.exe and i found thatit uses the following functions from IPHLPAPI.dll .( GetTcpTable is also from dll ).

AllocateAndGetTcpExTable2FromStack
AllocateAndGetTcpExTableFromStack
AllocateAndGetUdpExTable2FromStack
AllocateAndGetUdpExTableFromStack

I tried with the AllocateAndGetTcpExTableFromStack and AllocateAndGetUdpExTableFromStack function . it is very similar to GetTcpTable and GetUdpTable. These function are kept at undocumented. anyway i am happy.. Thats all for now....


2 comments:

Sarath said...

KD,It was a good post.BTW AllocateAndGetTcpExTableFromStack is not an undocumented API now.Please check MSDN AllocateAndGetTcpExTableFromStack

msnkd said...

Sarath ,
 
Thanks for this information, In my local MSDN (coming with .net 2005) it is not present. So i thought it is undocumented...