private unsafe static void GetAddressesForAdapter(int index, ref MulticastIPAddressInformationCollection addressList) { int length = 0; int ret = (NativeMethods.GetAdaptersAddresses(AddressFamily.Unspecified, MULTICAST_FLAGS, IntPtr.Zero, null, ref length)); byte[] data = new byte[length]; fixed(byte *pData = data) { byte *p = pData; ret = (NativeMethods.GetAdaptersAddresses(AddressFamily.Unspecified, MULTICAST_FLAGS, IntPtr.Zero, p, ref length)); if ((length == 0) || (ret != 0)) { // FAILED } // find this adapter by index int INDEX_OFFSET = 4; int currentIndex = 0; uint pNext = 0; do { p += INDEX_OFFSET; // past length currentIndex = (int)*((int *)p); if (index == currentIndex) { p -= 4; GetAddressesForAdapter(p, ref addressList); return; } p += 4; // past index pNext = (uint)*((uint *)p); p = (byte *)pNext; } while (pNext != 0); // failed to find index throw new ArgumentException("Index not found"); } }
private unsafe static void GetAddressesForAdapter(byte *pData, ref MulticastIPAddressInformationCollection addressList) { addressList.InternalClear(); /* * typedef struct _IP_ADAPTER_ADDRESSES { * union { * ULONGLONG Alignment; * struct { * ULONG Length; * DWORD IfIndex; * }; * }; * struct _IP_ADAPTER_ADDRESSES* Next; * PCHAR AdapterName; * PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress; * PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress; * PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress; * PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress; * PWCHAR DnsSuffix; * PWCHAR Description; * PWCHAR FriendlyName; * BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH]; * DWORD PhysicalAddressLength; * DWORD Flags; * * * typedef struct _SOCKET_ADDRESS { * LPSOCKADDR lpSockaddr ; * INT iSockaddrLength ; * } SOCKET_ADDRESS, *PSOCKET_ADDRESS, FAR * LPSOCKET_ADDRESS ; * * */ int addressListOffset = 0; byte *p = pData; uint *pNext = null; addressListOffset = 28; p += addressListOffset; /* * typedef struct _IP_ADAPTER_MULTICAST_ADDRESS { * union { * ULONGLONG Alignment; * struct { * ULONG Length; * DWORD Flags; * } * }; * struct _IP_ADAPTER_MULTICAST_ADDRESS* Next; * SOCKET_ADDRESS Address; * } IP_ADAPTER_MULTICAST_ADDRESS, *PIP_ADAPTER_MULTICAST_ADDRESS; */ uint pAddress = (uint)*((uint *)p); p = (byte *)pAddress; if (p == null) { return; } MulticastIPAddressInformation info; do { info = new MulticastIPAddressInformation(); // past length p += 4; // flags info.AdapterFlags = (PerAdapterFlags)((int)*((int *)p)); p += 4; // next pNext = (uint *)*((uint *)p); p += 4; // socket address pointer info.Address = GetAddressFromSocketAddressPointer(p); p += 4; p = (byte *)pNext; addressList.InternalAdd(info); }while (pNext != null); }