public static bool GetProcessUDPConns(ref MIB_UDPTABLE_OWNER_PID UdpConns) { UInt32* ptable = (UInt32*)IntPtr.Zero; UInt32 dwSize = 0; GetExtendedUdpTable((IntPtr)ptable, ref dwSize, true, AFType.AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0); char* tmp = stackalloc char[(int)dwSize]; ptable = (UInt32*)tmp; if (GetExtendedUdpTable((IntPtr)ptable, ref dwSize, true, AFType.AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0) != NO_ERROR) return false; UdpConns.dwNumEntries = ptable[0]; UdpConns.table = new MIB_UDPROW_OWNER_PID[UdpConns.dwNumEntries]; MIB_UDPROW_OWNER_PID * row = (MIB_UDPROW_OWNER_PID*)&ptable[1]; UInt32 j = 0; for (int i = 0; i < UdpConns.dwNumEntries; i++) { if(!IP.specialIP(row[i].dwLocalAddr)) UdpConns.table[j++] = row[i]; } UdpConns.dwNumEntries = j; return true; }
public static HashSet<UInt32> netActiveProcesses() { HashSet<UInt32> processes = new HashSet<UInt32>(); MIB_UDPTABLE_OWNER_PID utable = new MIB_UDPTABLE_OWNER_PID(); bool res = GetProcessUDPConns(ref utable); if(res) { for(int i = 0; i < utable.dwNumEntries; i++) { MIB_UDPROW_OWNER_PID urow = utable.table[i]; if (!processes.Contains(urow.dwOwningPid)) processes.Add(urow.dwOwningPid); } } MIB_TCPTABLE_OWNER_PID ttable = new MIB_TCPTABLE_OWNER_PID(); res = GetProcessTCPConns(ref ttable); if(res) { for(int i = 0; i < ttable.dwNumEntries; i++) { MIB_TCPROW_OWNER_PID trow = ttable.table[i]; if (!processes.Contains(trow.dwOwningPid) && tcpActive(trow)) processes.Add(trow.dwOwningPid); } } return processes; }