【C#学习】遍历主机所有的IP地址放入组件ComboBox

遍历主机所有的IP地址放入组件ComboBox

        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            /* combobox 组件 */
            iplist.Items.Add("请选择IP地址");
            List<string> str = new List<string>();

            /* 得到本机名字 */
            string hostname = Dns.GetHostName();
            /* 会返回所有地址,包括IPv4和IPv6 */
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostname);

            /* 遍历本机所有的IP地址放入到槽中 */
            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);
                        iplist.Items.Add(_temp_ip);
                    }
                }
            }

            iplist.SelectedIndex = 0;            
        }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/shileiwu0505/article/details/106845365