/// <summary> /// 获取所有 UDP 连接对象 /// </summary> /// <returns></returns> private static UDPRow[] GetAllUdpConnections() { UDPRow[] tTable; int AF_INET = 2; // IPv4 int buffSize = 0; GetExtendedUdpTable(IntPtr.Zero, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID); // 获取 buffsize 大小 IntPtr buffTable = Marshal.AllocHGlobal(buffSize); try { uint ret = GetExtendedUdpTable(buffTable, ref buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID); if (ret != 0) { return(null); } UDPTable tab = (UDPTable)Marshal.PtrToStructure(buffTable, typeof(UDPTable)); IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries)); tTable = new UDPRow[tab.dwNumEntries]; for (int i = 0; i < tab.dwNumEntries; i++) { UDPRow udpRow = (UDPRow)Marshal.PtrToStructure(rowPtr, typeof(UDPRow)); tTable[i] = udpRow; rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(udpRow)); // next entry } } finally { Marshal.FreeHGlobal(buffTable); } return(tTable); }
/// <summary> /// 获取特定 UDP 连接对象 /// </summary> /// <param name="PID">进程 PID</param> /// <returns></returns> private static List <UDPRow> GetSpecUDPConnection(int PID) { int AF_INET = 2; // IPv4 int BuffSize = 0; // 缓冲区大小 List <UDPRow> Target = new List <UDPRow>(); GetExtendedUdpTable(IntPtr.Zero, ref BuffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID); // 获取 BuffSize 大小 IntPtr Buffer = Marshal.AllocHGlobal(BuffSize); // 分配内存空间 try { if (GetExtendedUdpTable(Buffer, ref BuffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID) != 0) { return(null); } UDPTable udpTable = (UDPTable)Marshal.PtrToStructure(Buffer, typeof(UDPTable)); IntPtr RowPtr = (IntPtr)((long)Buffer + Marshal.SizeOf(udpTable.dwNumEntries)); for (int i = 0; i < udpTable.dwNumEntries; i++) { UDPRow udpRow = (UDPRow)Marshal.PtrToStructure(RowPtr, typeof(UDPRow)); if (udpRow.PID == PID) { Target.Add(udpRow); } RowPtr = (IntPtr)((long)RowPtr + Marshal.SizeOf(udpRow)); // next entry } } finally { Marshal.FreeHGlobal(Buffer); } return(Target); }