unsafe static MIB_TCPROW2[] GetTcpRows() { uint sizePointer = 0; const bool order = false; NativeMethods.GetTcpTable2(null, ref sizePointer, order); var rawTableBytes = new byte[sizePointer]; fixed(byte *ptbl = rawTableBytes) { uint error = NativeMethods.GetTcpTable2((MIB_TCPTABLE2 *)ptbl, ref sizePointer, order); Debug.Assert(error == 0); if (error != 0) { return(Array.Empty <MIB_TCPROW2>()); } int elems = (int)((MIB_TCPTABLE2 *)ptbl)->dwNumEntries; var res = new MIB_TCPROW2[elems]; var pelem = (MIB_TCPROW2 *)(ptbl + 4); var p = ptbl + 4; for (int i = 0; i < res.Length; i++, p += MIB_TCPROW2.SIZE) { res[i] = *(MIB_TCPROW2 *)p; } return(res); } }
public static List <int> GetPortByProcessId(int pid) { List <int> ports = new List <int>(); int nBufSize = 0; int err = GetTcpTable2(IntPtr.Zero, ref nBufSize, false); if (err == 0x7a) // ERROR_INSUFFICIENT_BUFFER { IntPtr pBuf = Marshal.AllocHGlobal(nBufSize); try { err = GetTcpTable2(pBuf, ref nBufSize, false); if (err == 0) { int entrySize = Marshal.SizeOf(typeof(MIB_TCPROW2)); int nEntries = Marshal.ReadInt32(pBuf); int tableStartAddr = (int)pBuf + sizeof(int); for (int i = 0; i < nEntries; i++) { IntPtr pEntry = (IntPtr)(tableStartAddr + i * entrySize); MIB_TCPROW2 tcpData = (MIB_TCPROW2)Marshal.PtrToStructure(pEntry, typeof(MIB_TCPROW2)); if (tcpData.dwOwningPid == pid) { ports.Add(ntohs((ushort)tcpData.dwLocalPort)); } } } else { throw new Win32Exception(err); } } finally { if (pBuf != IntPtr.Zero) { Marshal.FreeHGlobal(pBuf); } } } else { throw new Win32Exception(err); } return(ports.Distinct().ToList()); }