一个网络接口上的C#多个IP地址

时间:2017-01-17 09:50:27

标签: c# sockets networking

我们都知道PC可以有一个或多个网络接口。每个网络接口可以有一个或两个(可能更多)的IP地址。问题是如何确定将使用哪个IP地址与远程主机通信。

我知道如何使用下一个代码获取网络接口(感谢来自pinvoke.net的人):

private static NetworkInterface GetNetworkInterfaceByIndex(uint index)
{
    // Search in all network interfaces that support IPv4.
    NetworkInterface ipv4Interface = (from thisInterface in NetworkInterface.GetAllNetworkInterfaces()
                                      where thisInterface.Supports(NetworkInterfaceComponent.IPv4)
                                      let ipv4Properties = thisInterface.GetIPProperties().GetIPv4Properties()
                                      where ipv4Properties != null && ipv4Properties.Index == index
                                      select thisInterface).SingleOrDefault();
    if (ipv4Interface != null)
        return ipv4Interface;

    // Search in all network interfaces that support IPv6.
    NetworkInterface ipv6Interface = (from thisInterface in NetworkInterface.GetAllNetworkInterfaces()
                                      where thisInterface.Supports(NetworkInterfaceComponent.IPv6)
                                      let ipv6Properties = thisInterface.GetIPProperties().GetIPv6Properties()
                                      where ipv6Properties != null && ipv6Properties.Index == index
                                      select thisInterface).SingleOrDefault();

    return ipv6Interface;
}

[DllImport("iphlpapi.dll", SetLastError = true)]
static extern int GetBestInterface(uint DestAddr, out uint BestIfIndex);

static void IpAddressLogTest()
{
    Console.Write("Enter IP address to choose interface: ");
    IPAddress addr;
    IPAddress.TryParse(Console.ReadLine(), out addr);
    uint bestintf;
    var res = GetBestInterface(BitConverter.ToUInt32(addr.GetAddressBytes(), 0), out bestintf);
    NetworkInterface interfaceInfo = GetNetworkInterfaceByIndex(bestintf);
    foreach (var a in interfaceInfo.GetIPProperties().UnicastAddresses)
       if (a.Address.AddressFamily == AddressFamily.InterNetwork)
            Console.WriteLine(a.Address.ToString());
    Console.ReadLine();
}

此代码完美运行,我知道将使用哪个接口与主机通信。但是接口可以在不同的网络中有两个IP地址。

在这种情况下如何选择正确的IP地址?

UPD1。此类设置的示例:

enter image description here

0 个答案:

没有答案
相关问题