public static ReadOnlyCollection <IPAddress> SortAddresses(Socket socket, IPAddress listenAddress, ReadOnlyCollection <IPAddress> addresses) { ReadOnlyCollection <IPAddress> sortedAddresses = null; // Skip sort if ipv6 isn't installed or if address array has a single address if (socket == null || addresses.Count <= 1) { sortedAddresses = addresses; } else { CriticalAllocHandleSocketAddressList inputBuffer = null; CriticalAllocHandleSocketAddressList outputBuffer = null; try { inputBuffer = CriticalAllocHandleSocketAddressList.FromAddressList(addresses); outputBuffer = CriticalAllocHandleSocketAddressList.FromAddressCount(0); // Invoke ioctl to sort the addresses int realOutputBufferSize; int error = UnsafeNativeMethods.ERROR_SUCCESS; int errorCode = PeerWinsock.WSAIoctl(socket.Handle, unchecked ((int)IOControlCode.AddressListSort), (IntPtr)inputBuffer, inputBuffer.Size, (IntPtr)outputBuffer, outputBuffer.Size, out realOutputBufferSize, IntPtr.Zero, IntPtr.Zero); if (errorCode == -1) { // Get the Win32 error code before doing anything else error = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SocketException(error)); } // Marshal the sorted SOCKET_ADDRESS_LIST into IPAddresses sortedAddresses = outputBuffer.ToAddresses(); } finally { if (inputBuffer != null) { inputBuffer.Dispose(); } if (outputBuffer != null) { outputBuffer.Dispose(); } } } return(sortedAddresses); }
public static ReadOnlyCollection <IPAddress> SortAddresses(Socket socket, IPAddress listenAddress, ReadOnlyCollection <IPAddress> addresses) { ReadOnlyCollection <IPAddress> onlys = null; if ((socket == null) || (addresses.Count <= 1)) { return(addresses); } CriticalAllocHandleSocketAddressList list = null; CriticalAllocHandleSocketAddressList list2 = null; try { int num; list = CriticalAllocHandleSocketAddressList.FromAddressList(addresses); list2 = CriticalAllocHandleSocketAddressList.FromAddressCount(0); int errorCode = 0; if (PeerWinsock.WSAIoctl(socket.Handle, -939524071, (IntPtr)list, list.Size, (IntPtr)list2, list2.Size, out num, IntPtr.Zero, IntPtr.Zero) == -1) { errorCode = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SocketException(errorCode)); } onlys = list2.ToAddresses(); } finally { if (list != null) { list.Dispose(); } if (list2 != null) { list2.Dispose(); } } return(onlys); }