简体   繁体   English

如何获取网络适配器的IP地址

[英]How to get IP address of network adapter

I use this code to get the available IPv4 addresses: 我使用以下代码来获取可用的IPv4地址:

static void Main(string[] args)
    {
        string host = System.Net.Dns.GetHostName();
        System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(host);
        System.Net.IPAddress[] ipAddr = ipEntry.AddressList;
        for (int i = 0; i < ipAddr.Length; i++)
        {
            if (ipAddr[i].AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                Console.WriteLine( ipAddr[i]);

        }
    }

For my machine this currently gives: 对于我的机器,当前提供了:

192.168.1.11 192.168.1.11

192.168.240.1 192.168.240.1

192.168.182.1 192.168.182.1

10.1.1.121 10.1.1.121

whereas 192.168.1.11 is my network adapter, the next two are from VMware Network, and 10.1.1.121 is from a currently active OpenVPN connection. 192.168.1.11是我的网络适配器,接下来的两个来自VMware Network,而10.1.1.121是来自当前活动的OpenVPN连接。

How can I reliably detect the IPv4 address 192.168.1.11 (= network adapter) only? 如何才能仅可靠地检测IPv4地址192.168.1.11(=网络适配器)? I guess that it's just incidentally on the first place. 我想这只是偶然。

Thanks, Robert 谢谢罗伯特

The answer you got is not entirely true, because those four IPv4 adresses in your example all belong to a network adapter, even if they might be virtual only. 您得到的答案并不完全正确,因为示例中的这四个IPv4地址都属于网络适配器,即使它们可能只是虚拟的也是如此。

To get more information about your network interfaces, you should check the NetworkInterface Class or WMI. 要获取有关您的网络接口的更多信息,您应该检查NetworkInterface类或WMI。 You can filter out by type to remove loopback and tunnel interfaces for example. 例如,您可以按类型过滤以删除回送和隧道接口。

Which network adapter is actually used is as far as I know dependent on the destination address of the packet you want to send. 据我所知,实际使用哪个网络适配器取决于要发送的数据包的目标地址。 The network adapters use the Adress Resolution Protocol to check if they can reach the desination IP, and the MAC address of the gateway. 网络适​​配器使用地址解析协议来检查它们是否可以到达目标IP和网关的MAC地址。

So short answer; 答案很短; there is no default network adapter. 没有默认的网络适配器。

This is the code I used: 这是我使用的代码:

private string getLocalIP()
{
    string Localip = "?";
    foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
    {

        var defaultGateway =  from nics in NetworkInterface.GetAllNetworkInterfaces()


from props in nics.GetIPProperties().GatewayAddresses
   where nics.OperationalStatus == OperationalStatus.Up
   select props.Address.ToString(); // this sets the default gateway in a variable

        GatewayIPAddressInformationCollection prop = netInterface.GetIPProperties().GatewayAddresses;

        if(defaultGateway.First() != null){

        IPInterfaceProperties ipProps = netInterface.GetIPProperties();

        foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
        {

            if (addr.Address.ToString().Contains(defaultGateway.First().Remove(defaultGateway.First().LastIndexOf(".")))) // The IP address of the computer is always a bit equal to the default gateway except for the last group of numbers. This splits it and checks if the ip without the last group matches the default gateway
            {

                if (Localip == "?") // check if the string has been changed before
                {
                    Localip = addr.Address.ToString(); // put the ip address in a string that you can use.
                }
            }

        }

        }

    }
   return Localip;
}

As @Nappy Mentions using NetworkInterface is nicer approach. 由于使用NetworkInterface的@Nappy Mentions是更好的方法。 Quick sample below. 以下是快速示例。

    private IEnumerable<IPAddress> GetIpsForNetworkAdapters()
    {

        var nics = from i in NetworkInterface.GetAllNetworkInterfaces()
                    where i.OperationalStatus == OperationalStatus.Up
                    select new { name = i.Name, ip = GetIpFromUnicastAddresses(i) };

        return nics.Select(x => x.ip);
    }

    private IPAddress GetIpFromUnicastAddresses(NetworkInterface i)
    {
        return (from ip in i.GetIPProperties().UnicastAddresses
                where ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
                select ip.Address).SingleOrDefault();
    }

尝试这个

System.Net.Dns.GetHostByName(Environment.MachineName).AddressList[0].ToString();

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

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