首页 > 代码库 > C# 获取本机的所有ip地址,并过滤内网ip

C# 获取本机的所有ip地址,并过滤内网ip

技术分享

 

private void Initialization_Load(object sender, EventArgs e)
        {
            cboxip.Items.Add("请选择IP地址");
            List<string> str = new List<string>();
            string hostName = Dns.GetHostName();//本机名   
            //System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期,我运行时且只返回了一个IPv4的地址   
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);//会返回所有地址,包括IPv4和IPv6   
            foreach (IPAddress ip in addressList)  
            {
                string _temp_ip = ip.MapToIPv4().ToString();
                string[] ipstr = _temp_ip.Split(.);
                if (ipstr[0] == "127" || ipstr[0] == "10" || ipstr[0] == "172")
                {
                    continue;
                }
                else {
                    string temp = str.Where(s => s == _temp_ip).FirstOrDefault();
                    if (temp == null)
                    {
                        str.Add(_temp_ip);
                        cboxip.Items.Add(_temp_ip);
                    }
                }               
            }
            cboxip.SelectedIndex = 0;
        }

 

C# 获取本机的所有ip地址,并过滤内网ip