简体   繁体   English

C#本地IP与多个以太网不正确

[英]C# Local IP is not correct with multiple Ethernet

I need to get the Local IP address of PC but if pc is connected to multiple network the ip is not correct. 我需要获取PC的本地IP地址,但是如果PC连接到多个网络,则IP不正确。

I'm using: 我正在使用:

public static string GetIPAddress()
        {
            IPHostEntry host;
            string localIP = "?";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                }
            }
            return localIP;
        }

Like: 喜欢:

在此处输入图片说明

I need get the local ip of adapter with internet or all local ip address. 我需要使用互联网或所有本地IP地址获取适配器的本地IP。

I can see 2 options: 我可以看到2个选项:

option 1 选项1

loop trough all interfaces using System.Net.NetworkInformation : 使用System.Net.NetworkInformation通过所有接口循环:

static List<IPAddress> GetIpAddress()
{
    List<IPAddress> AllIps = new List<IPAddress>();

    foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces())
    {

        IPInterfaceProperties properties = netif.GetIPProperties();

        foreach (IPAddressInformation unicast in properties.UnicastAddresses)
        {
            AllIps.Add(unicast.Address);
            Console.WriteLine(unicast.Address);
        }
    }

    return AllIps;
}

option 2 选项2

find the default gateway to the internet, then match the default gateway address to the interface addresses you found: 查找到Internet的默认网关,然后将默认网关地址与找到的接口地址匹配:

 public static IPAddress GetDefaultGateway()
 {
     IPAddress result = null;
     var cards = NetworkInterface.GetAllNetworkInterfaces().ToList();
     if (cards.Any())
     {
         foreach (var card in cards)
         {
             var props = card.GetIPProperties();
             if (props == null)
                 continue;

             var gateways = props.GatewayAddresses;
             if (!gateways.Any())
                 continue;

             var gateway =
                 gateways.FirstOrDefault(g => g.Address.AddressFamily.ToString() == "InterNetwork");
             if (gateway == null)
                 continue;

             result = gateway.Address;
             break;
         };
     }

     return result;
 }

now you can combine the 2 options in order to find the interface that is connected to the internet. 现在,您可以组合两个选项以找到连接到互联网的接口。 here is my suggestion to match the default gateway to the correct adapter address. 这是我的建议,将默认网关与正确的适配器地址匹配。
you can also determine the IP address classes using the IpClass Enumeration that is written in the code i have added: 您还可以使用在我添加的代码中编写的IpClass枚举确定IP地址类别

static void Main(string[] args)
{
    // find all interfaces ip adressess
    var allAdaptersIp = GetIpAddress();
    // find the default gateway
    var dg = GetDefaultGateway();
    // match the default gateway to the host address => the interface that is connected to the internet => that print host address
    Console.WriteLine("ip address that will route you to the world: " + GetInterNetworkHostIp(ref allAdaptersIp, dg, IpClass.ClassC));
    Console.ReadLine();
}

enum IpClass
{
    ClassA,
    ClassB,
    ClassC
}

static string GetInterNetworkHostIp(ref List<IPAddress> adapters, IPAddress dg, IpClass ipclassenum)
{
    string networkAddress = "";
    var result = "" ;

    switch (ipclassenum)
    {
        case IpClass.ClassA:
            networkAddress  = dg.ToString().Substring(0, dg.ToString().Length - dg.ToString().LastIndexOf(".") ); 
            break;
        case IpClass.ClassB:
            networkAddress = dg.ToString().Substring(0, dg.ToString().Length - dg.ToString().IndexOf(".",3));
            break;
        case IpClass.ClassC:
            networkAddress = dg.ToString().Substring(0, dg.ToString().Length- dg.ToString().IndexOf(".") );
            break;
        default:

            break;
    }

    foreach (IPAddress ip in adapters)
    {
        if (ip.ToString().Contains(networkAddress))
        {
            result = ip.ToString();
            break;
        }
    }

    if (result == "")
        result = "no ip was found";

    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM