Which PID listens on a given port in c#
from win XP SP2 onwards you can P/Invoke to GetExtendedTcpTable
Using This person's kind work to flesh out the signature (the PInvoke.net spec is incomplete) here is a (rough and poor at error checking) example
using System;
using System.Runtime.InteropServices;
public enum TCP_TABLE_CLASS : int
{
TCP_TABLE_BASIC_LISTENER,
TCP_TABLE_BASIC_CONNECTIONS,
TCP_TABLE_BASIC_ALL,
TCP_TABLE_OWNER_PID_LISTENER,
TCP_TABLE_OWNER_PID_CONNECTIONS,
TCP_TABLE_OWNER_PID_ALL,
TCP_TABLE_OWNER_MODULE_LISTENER,
TCP_TABLE_OWNER_MODULE_CONNECTIONS,
TCP_TABLE_OWNER_MODULE_ALL
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPROW_OWNER_PID
{
public uint state;
public uint localAddr;
public byte localPort1;
public byte localPort2;
public byte localPort3;
public byte localPort4;
public uint remoteAddr;
public byte remotePort1;
public byte remotePort2;
public byte remotePort3;
public byte remotePort4;
public int owningPid;
public ushort LocalPort
{
get
{
return BitConverter.ToUInt16(
new byte[2] { localPort2, localPort1}, 0);
}
}
public ushort RemotePort
{
get
{
return BitConverter.ToUInt16(
new byte[2] { remotePort2, remotePort1}, 0);
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPTABLE_OWNER_PID
{
public uint dwNumEntries;
MIB_TCPROW_OWNER_PID table;
}
[DllImport("iphlpapi.dll", SetLastError=true)]
static extern uint GetExtendedTcpTable(IntPtr pTcpTable,
ref int dwOutBufLen,
bool sort,
int ipVersion,
TCP_TABLE_CLASS tblClass,
int reserved);
public static MIB_TCPROW_OWNER_PID[] GetAllTcpConnections()
{
MIB_TCPROW_OWNER_PID[] tTable;
int AF_INET = 2; // IP_v4
int buffSize = 0;
// how much memory do we need?
uint ret = GetExtendedTcpTable(IntPtr.Zero,
ref buffSize,
true,
AF_INET,
TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL,
0);
if (ret != 0 && ret != 122) // 122 insufficient buffer size
throw new Exception("bad ret on check " + ret);
IntPtr buffTable = Marshal.AllocHGlobal(buffSize);
try
{
ret = GetExtendedTcpTable(buffTable,
ref buffSize,
true,
AF_INET,
TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL,
0);
if (ret != 0)
throw new Exception("bad ret "+ ret);
// get the number of entries in the table
MIB_TCPTABLE_OWNER_PID tab =
(MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(
buffTable,
typeof(MIB_TCPTABLE_OWNER_PID));
IntPtr rowPtr = (IntPtr)((long)buffTable +
Marshal.SizeOf(tab.dwNumEntries));
tTable = new MIB_TCPROW_OWNER_PID[tab.dwNumEntries];
for (int i = 0; i < tab.dwNumEntries; i++)
{
MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal
.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
tTable[i] = tcpRow;
// next entry
rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));
}
}
finally
{
// Free the Memory
Marshal.FreeHGlobal(buffTable);
}
return tTable;
}
Why is WCF service listening as PID 4 (SYSTEM) and not as the PID of the process hosting it?
The Web API uses HTTP not TCP as its transport. By default only an administrator is allowed to start listening on HTTP endpoints. If you want another user to do so you need to use netsh on Windows 7/2008 or httpcfg on Windows XP/2003.
netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user
See Configuring HTTP and HTTPS
C# find process id (pid) of client making an UDP/TCP call
you can try this
netstat -a -n -o | find "1688"
You will get the exact output of the process
UDP 10.4.112.77:55866 *:* 1688
UDP 127.0.0.1:1900 *:* 1688
UDP 127.0.0.1:55868 *:* 1688
Try this for complete process id port and process name.
- Open a command prompt window (as Administrator) From "Start\Search box" Enter "cmd" then right-click on "cmd.exe" and select "Run as Administrator"
- Enter:
netstat -abno
- Find the Port that you are listening on under "Local Address"
- Look at the process name directly under that.
you can collect the information and then the parse the output
this one stack link might be helping you.
Which PID listens on a given port in c#
How to determine tcp port used by Windows process in C#
Except for PID, take a look this:
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();
TcpConnectionInformation[] tcpConnections =
ipProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation info in tcpConnections)
{
Console.WriteLine("Local: {0}:{1}\nRemote: {2}:{3}\nState: {4}\n",
info.LocalEndPoint.Address, info.LocalEndPoint.Port,
info.RemoteEndPoint.Address, info.RemoteEndPoint.Port,
info.State.ToString());
}
Console.ReadLine();
Source: Netstat in C#
A bit more research bring this: Build your own netstat.exe with c#. This uses P/Invoke to call GetExtendedTcpTable
and using same structure as netstat
.
How do I get process name of an open port in C#?
http://www.codeproject.com/KB/IP/iphlpapi.aspx might also help
Determine if a server is listening on a given port
The process is actually very simple.
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
try
{
socket.Connect(host, port);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionRefused)
{
// ...
}
}
}
Related Topics
Hide Form Instead of Closing When Close Button Clicked
How to Center Your Main Window in Wpf
Wpf Equivalent to Textrenderer
Is There a Synchronization Class That Guarantee Fifo Order in C#
Different Forms of the Wcf Service Contract Interface
C# Image.Clone Out of Memory Exception
Async Await VS Getawaiter().Getresult() and Callback
Extract All Strings Between Two Strings
Prevent Textbox Autofill with Previously Entered Values
Difference Between the Keydown Event, Keypress Event and Keyup Event in Visual Studio
Change File Extension Using C#
Gracefully Handling Corrupted State Exceptions
Active Directory Com Exception - an Operations Error Occurred (0X80072020)
Why Does a Bad Password Cause "Padding Is Invalid and Cannot Be Removed"