[StructLayout(LayoutKind.Sequential)]
public struct MIBOwnerProcessIdTCPTable
{
public uint EntryNumber;
public MIBOwnerProcessIdTCPRow Table;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIBOwnerProcessIdTCPRow
{
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 OwnerProcessId;
}
[DllImport("iphlpapi.dll", SetLastError = true)]
public static extern WinApiSystemErrorCode GetExtendedTcpTable(IntPtr pTcpTable,
ref int dwOutBufLen,
bool sort,
WinApiAddressFamilies addressFamily,
WinApiMIBTCPTableTypes tableType,
int reserved);
/// <summary>
/// [Helper] Get all the TCP connections with process information
/// </summary>
public static MIBOwnerProcessIdTCPRow[] GetAllMIBOwnerProcessIdTCPRows()
{
MIBOwnerProcessIdTCPRow[] rows;
int bufferSize = 0;
// how much memory do we need?
WinApiSystemErrorCode errorCode = GetExtendedTcpTable(IntPtr.Zero,
ref bufferSize,
true,
WinApiAddressFamilies.Internet,
WinApiMIBTCPTableTypes.OwnerProcessIdAll,
0);
if (errorCode != WinApiSystemErrorCode.Success)
{
return null;
}
// get the number of entries in the table
MIBOwnerProcessIdTCPTable table = (MIBOwnerProcessIdTCPTable)Marshal.PtrToStructure(bufferTable, typeof(MIBOwnerProcessIdTCPTable));
IntPtr rowPtr = (IntPtr)((long)bufferTable + Marshal.SizeOf(table.EntryNumber));
rows = new MIBOwnerProcessIdTCPRow[table.EntryNumber];
for (int i = 0; i < rows.Length; i++)
{
rows[i] = (MIBOwnerProcessIdTCPRow)Marshal.PtrToStructure(rowPtr, typeof(MIBOwnerProcessIdTCPRow));
rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(typeof(MIBOwnerProcessIdTCPRow)));
}