public static IPAddress getBestRouteTo(IPAddress destIPAddress) { sockaddr_inet dest = new sockaddr_inet(); dest.sin_family = (ushort)destIPAddress.AddressFamily; dest.s_addr = (uint)byteswap(destIPAddress.Address); dest.sin_zero = 0; mib_ipforward_row2 bestRoute = new mib_ipforward_row2(); sockaddr_inet bestSrc = new sockaddr_inet(); int res = GetBestRoute2(IntPtr.Zero, 0, IntPtr.Zero, ref dest, 0, ref bestRoute, ref bestSrc); if (res != 0) { throw new Win32Exception(res); } return(new IPAddress(bestSrc.s_addr)); }
private static extern int GetBestRoute2(IntPtr InterfaceLUID, int InterfaceIndex, IntPtr SourceAddress, ref sockaddr_inet destAddress, UInt32 AddresssortOptions, ref mib_ipforward_row2 bestRoute, ref sockaddr_inet bestSourceAddress);