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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With