Есть следующий код:
private struct MIB_UDPROW_OWNER_PID
{
public uint dwLocalAddr;
public uint dwLocalPort;
public uint dwOwningPid;
}
enum UDP_TABLE_CLASS
{
UDP_TABLE_BASIC,
UDP_TABLE_OWNER_MODULE,
UDP_TABLE_OWNER_PID
}
const uint ERROR_INSUFFICIENT_BUFFER = 122;
const uint NO_ERROR = 0;
private const uint AF_INET = 2;
private const uint AF_INET6 = 23;
[DllImport("Iphlpapi.dll", SetLastError = true, ExactSpelling = true)]
static extern uint GetExtendedUdpTable(IntPtr pTcpTable,
ref int pdwSize,
bool bOrder,
uint ulAf,
UDP_TABLE_CLASS TableClass,
uint Reserved
)
;
static void Main(string[] args)
{
while (true)
{
Thread.Sleep(100);
MIB_UDPROW_OWNER_PID[] ms = GetUdpTableForEachProcess();
foreach (MIB_UDPROW_OWNER_PID m in ms )
{
Console.WriteLine(m.dwLocalPort);
}
}
}
static MIB_UDPROW_OWNER_PID[] GetUdpTableForEachProcess()
{
IntPtr ptr = IntPtr.Zero;
int buffSize = 0;
uint dwError;
dwError = GetExtendedUdpTable(ptr, ref buffSize, false, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
if (dwError != ERROR_INSUFFICIENT_BUFFER)
{
return null;
}
ptr = Marshal.AllocHGlobal(buffSize);
dwError = GetExtendedUdpTable(ptr, ref buffSize, false, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
if (dwError != NO_ERROR)
{
Marshal.FreeHGlobal(ptr);
return null;
}
int count = Marshal.ReadInt32(ptr);
IntPtr ptrRead = ptr + sizeof(int);
int sz = Marshal.SizeOf(typeof(MIB_UDPROW_OWNER_PID));
MIB_UDPROW_OWNER_PID[] mtop = new MIB_UDPROW_OWNER_PID[count];
for (int i = 0; i <= count - 1; i++)
{
mtop[i] = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(ptrRead, typeof(MIB_UDPROW_OWNER_PID));
ptrRead += sz;
}
Marshal.FreeHGlobal(ptr);
return mtop;
}
И вместо того, чтобы вернуть мне порт, оно возвращает значения вида 0 0 0 куча цифр 0 0 0. Тоже самое и с PID. Причем с GetExtendedTcpTable все работает отлично. Все структуры и перечисления точно правильные, так как взяты с MSDN. Null нигде и никто не возвращает. Есть идеи, товарищи?