Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get PID of process using some port [duplicate]

Tags:

c#

.net

tcp

I need a way of, given a tcp port number, discover if there's some process using that port (and get the process id).

Something like netstat does but programmatically.

like image 910
Zé Carlos Avatar asked Oct 18 '25 15:10

Zé Carlos


1 Answers

This is probably too late for the original poster but someone else may find it useful. You can use the PowerShell class in the System.Management.Automation namespace.

private static IEnumerable<uint> ProcessesUsingPorts(uint id)
{
    PowerShell ps = PowerShell.Create();
    ps.AddCommand("Get-NetTCPConnection").AddParameter("LocalPort", id);
    return ps.Invoke().Select(p => (uint)p.Properties["OwningProcess"].Value);
}
like image 62
falopsy Avatar answered Oct 21 '25 04:10

falopsy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!