【问题标题】:How to get IP address of network adapter如何获取网络适配器的IP地址
【发布时间】:2023-04-08 11:00:01
【问题描述】:

我使用此代码获取可用的 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]);

        }
    }

对于我的机器,目前提供:

192.168.1.11

192.168.240.1

192.168.182.1

10.1.1.121

而 192.168.1.11 是我的网络适配器,接下来的两个来自 VMware Network,而 10.1.1.121 来自当前活动的 OpenVPN 连接。

如何仅可靠地检测 IPv4 地址 192.168.1.11(= 网络适配器)? 我想这只是顺便说一句。

谢谢,罗伯特

【问题讨论】:

    标签: c# windows ip-address


    【解决方案1】:

    这是我使用的代码:

    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;
    }
    

    【讨论】:

      【解决方案2】:

      @Nappy 提到使用 NetworkInterface 是更好的方法。下面的快速示例。

          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();
          }
      

      【讨论】:

        【解决方案3】:

        您得到的答案并不完全正确,因为您示例中的这四个 IPv4 地址都属于一个网络适配器,即使它们可能只是虚拟的。

        要获取有关网络接口的更多信息,您应该查看NetworkInterface Class 或 WMI。例如,您可以按类型过滤以删除环回和隧道接口。

        据我所知,实际使用哪个网络适配器取决于您要发送的数据包的目标地址。网络适​​配器使用地址解析协议来检查它们是否可以到达目标 IP,以及网关的 MAC 地址。

        这么短的答案;没有默认的网络适配器。

        【讨论】:

          【解决方案4】:

          试试这个

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

          【讨论】:

          • 所以它总是第一个条目?
          • 是的。总是。这就是我使用它的原因。
          • 而当一台机器有两个适配器时,它是前两个条目?
          • 不,你不会得到两个。您可以从我使用的代码中看到AddressList[0]。首先将返回。
          • 我的意思是:System.Net.Dns.GetHostByName(Environment.MachineName).AddressList[1].ToString();会给我第二个适配器吗?
          猜你喜欢
          • 2013-05-20
          • 1970-01-01
          • 1970-01-01
          • 2018-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-06
          • 2010-09-18
          相关资源
          最近更新 更多