Pergunta

Ideally I want to do this inside of C# so I'm including the C# tag.

I have several Window Communication Foundation Services that are running and open up TCP ports (one each) using System.ServiceModel.ServiceHost. I have a listing of the port numbers that are being using but I want to use the running service to map from the port number to the executable.

I have tried to use netstat, TCPView, and few other similar tools I've found trying to search this solution but nothing display my process, the closest I can get is the System (PID 4).

All of these are Windows WCF Services, operate as intended, and do show up in netstat and TCPView (by port number) but can only supply the "System" as the process.

The code is being managed by several different departments, so I'm not considering an common interface approach as a valid solution. I do have full admin rights to the machine.

Foi útil?

Solução

The WCF provides a WMI interface for diagnostics which you should be able to use in order to associate a WCF service port with a particular process. In particular the Service class looks promising.

(Please feel free to attach your example code here as discussed, or post it as another answer.)

Outras dicas

Adding my sample code to @HarryJohnston's answer:

String wcfNamespace = String.Format(@"\\{0}\Root\ServiceModel", "MachineName");

ConnectionOptions connection = new ConnectionOptions();
connection.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementScope scope = new ManagementScope(wcfNamespace, connection);
scope.Connect();

ObjectQuery query = new ObjectQuery("Select * From Service");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

ManagementObjectCollection queryCollection = searcher.Get();
ManagementObject[] listing = queryCollection.OfType<ManagementObject>().ToArray();

Dictionary<int, int> portToPID = new Dictionary<int, int>();

foreach (ManagementObject mo in queryCollection)
{
    //each of services only have one base address in my example
    Uri baseAddress = new Uri(((Array)mo.Properties["BaseAddresses"].Value).GetValue(0).ToString());
    int pid = Int32.Parse(mo.Properties["ProcessId"].Value.ToString());
    portToPID.Add(baseAddress.Port, pid);
}

Also requires add this to each service .config, not WMI Client

<system.serviceModel>
    …
    <diagnostics wmiProviderEnabled="true" />
    …
</system.serviceModel>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top