public static NetStatInfo[] GetExtendedTcpTable(bool sorted = false) { IntPtr table = IntPtr.Zero; int tableLength = 0; NetStatInfo[] rows = null; int AfInet = 2; if (NativeMethods.GetExtendedTcpTable(table, ref tableLength, sorted, AfInet, TCP_TABLE_CLASS.OwnerPidAll, 0) != 0) { try { table = Marshal.AllocHGlobal(tableLength); if (NativeMethods.GetExtendedTcpTable(table, ref tableLength, true, AfInet, TCP_TABLE_CLASS.OwnerPidAll, 0) == 0) { var mibTable = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(table, typeof(MIB_TCPTABLE_OWNER_PID)); rows = new NetStatInfo[mibTable.NumEntries]; IntPtr rowPtr = (IntPtr)((long)table + Marshal.SizeOf(mibTable.NumEntries)); for (int i = 0; i < mibTable.NumEntries; ++i) { var mibRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID)); var row = new NetStatInfo(); row.Proto = ProtocolType.Tcp; row.State = mibRow.state; row.ProcessId = mibRow.owningPid; row.LocalAddress = new IPAddress(mibRow.localAddr); row.LocalPort = BitConverter.ToUInt16(new byte[2] { mibRow.localPort[1], mibRow.localPort[0] }, 0); row.RemoteAddress = new IPAddress(mibRow.remoteAddr); row.RemotePort = BitConverter.ToUInt16(new byte[2] { mibRow.remotePort[1], mibRow.remotePort[0] }, 0); if (row.ProcessId > 0) { row.ProcessName = GetProcessName(row.ProcessId); } rows[i] = row; rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(typeof(MIB_TCPROW_OWNER_PID))); } } } finally { if (table != IntPtr.Zero) { Marshal.FreeHGlobal(table); } } } return(rows); }
public static string GetExtendedTable(bool sorted = false) { var tcpList = GetExtendedTcpTable(true); var udpList = GetExtendedUdpTable(true); var list = new List <NetStatInfo>(); list.AddRange(tcpList); list.AddRange(udpList); var items = list.Select(x => x.ToLineString()); var result = string.Join("\r\n", items); return(NetStatInfo.ToHeaderLine() + result); }