Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the ports opened by a Windows Service?

I want to get the list of window services and their ports in C#. I'm able to get all window services by using ServiceController but I'm unable to get ports of these services.

like image 674
Muhammad Umar Avatar asked Oct 07 '22 07:10

Muhammad Umar


2 Answers

Please check this question on stackoverlow. It is not exactly the same as you are asking, but it points to a useful function called GetExtendedTcpTable available through PInvoke, that can do what you need. Also check this one.

like image 61
Neolisk Avatar answered Oct 10 '22 02:10

Neolisk


After a lot of looking around I found that there's undocumented "OwningModuleInfo" in MIB_TCPROW_OWNER_MODULE structure.

Then looking for that I found this comment:

Weird issue regarding GetOwnerModuleFromTcpEntry when targeting x64

"I have reached the conclusion that the first item in the array is the index of the service in the list of running services, ..."

So the answer to the question would then be to use that to get name info that netstat -b shows (service name and address+port), filtering for your desired service. I found this https://github.com/Loriowar/IpHlpApidotnet lib which has bunch of related code already set up except for this feature.

Other useful links :

Marshalling Struct with Array of Struct Member

https://msdn.microsoft.com/en-us/library/windows/desktop/aa366911(v=vs.85).aspx

like image 31
Anonymous Coward Avatar answered Oct 10 '22 02:10

Anonymous Coward