internal static Owner?GetOwningModuleTCP(MIB_TCPROW_OWNER_MODULE row) { Owner?ret = null; /*if (ownerCache.TryGetValue(row, out ret)) * { * return ret; * }*/ if (row.OwningPid == 0) { return(Owner.System); } IntPtr buffer = IntPtr.Zero; try { uint buffSize = 0; var retn = NativeMethods.GetOwnerModuleFromTcpEntry(ref row, TCPIP_OWNER_MODULE_INFO_CLASS.TCPIP_OWNER_MODULE_INFO_BASIC, IntPtr.Zero, ref buffSize); if (retn != NO_ERROR && retn != ERROR_INSUFFICIENT_BUFFER) { //Cannot get owning module for this connection LogHelper.Info("Unable to get the connection owner: ownerPid=" + row.OwningPid + " remoteAdr=" + row.RemoteAddress + ":" + row.RemotePort); return(ret); } if (buffSize == 0) { //No buffer? Probably means we can't retrieve any information about this connection; skip it LogHelper.Info("Unable to get the connection owner (no buffer)."); return(ret); } buffer = Marshal.AllocHGlobal((int)buffSize); //GetOwnerModuleFromTcpEntry needs the fields of TCPIP_OWNER_MODULE_INFO_BASIC to be NULL IPHelper.NativeMethods.ZeroMemory(buffer, buffSize); var resp = NativeMethods.GetOwnerModuleFromTcpEntry(ref row, TCPIP_OWNER_MODULE_INFO_CLASS.TCPIP_OWNER_MODULE_INFO_BASIC, buffer, ref buffSize); if (resp == 0) { ret = new Owner(Marshal.PtrToStructure <TCPIP_OWNER_MODULE_BASIC_INFO>(buffer)); } else if (resp != ERROR_NOT_FOUND) // Ignore closed connections { LogHelper.Error("Unable to get the connection owner.", new Win32Exception((int)resp)); } //ownerCache.Add(row, ret); return(ret); } finally { if (buffer != IntPtr.Zero) { Marshal.FreeHGlobal(buffer); } } }
internal static extern uint GetOwnerModuleFromTcpEntry(ref MIB_TCPROW_OWNER_MODULE pTcpEntry, TCPIP_OWNER_MODULE_INFO_CLASS Class, IntPtr Buffer, ref uint pdwSize);