zoukankan      html  css  js  c++  java
  • 读取本地IP地址和子网页码

      #region 读取本地IP地址和子网页码
                //读取本地IP地址和子网页码
                NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface adapter in nics)
                {
                    if (adapter.NetworkInterfaceType.ToString().Equals("Ethernet"))
                    {
                        //adapter.Name;     //网卡适配名称:“本地连接”
                        //adapter.Description;   //适配器描述信息
                        IPInterfaceProperties ip = adapter.GetIPProperties();     //IP配置信息
    
                        if (ip.UnicastAddresses.Count > 0)
                        {
                            string localip = ip.UnicastAddresses[1].Address.ToString();   //IP地址
                            txtIP.Text = localip;
                            string localcode = ip.UnicastAddresses[1].IPv4Mask.ToString();  //子网掩码
                            txtZWym.Text = localcode;
    
                        }
                        if (ip.GatewayAddresses.Count > 0)
                        {
                            string net = ip.GatewayAddresses[0].Address.ToString();   //默认网关
                            txtWg.Text = net;
                        }
    
                        if (ip.DnsAddresses.Count > 0)
                        {
                            ip.DnsAddresses[0].ToString();       //首选DNS服务器地址
                            if (ip.DnsAddresses.Count > 1)
                                ip.DnsAddresses[1].ToString();  //备用DNS服务器地址
                            //MessageBox.Show(" ip.DnsAddresses[0].ToString();:" + ip.DnsAddresses[0].ToString());
                        }
                    }
                }
                #endregion

     方法二:上面的方法有时候读不出来子网掩码,需要如下方法:

      ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection nics = mc.GetInstances();
                foreach (ManagementObject nic in nics)
                {
                    if (Convert.ToBoolean(nic["ipEnabled"]) == true)
                    {
                        string mac = nic["MacAddress"].ToString();//Mac地址
    
                        string ip = (nic["IPAddress"] as String[])[0];//IP地址
                        txtIP.Text = ip;
                        string ipsubnet = (nic["IPSubnet"] as String[])[0];//子网掩码
                        txtZWym.Text = ipsubnet;
                        string ipgateway = (nic["DefaultIPGateway"] as String[])[0];//默认网关
                        txtWg.Text = ipgateway;
                    }
                }
  • 相关阅读:
    hdu 5352 匈牙利(多重匹配)
    hdu 2112 最短路+stl
    hdu 1811 拓扑排序+并查集+细心
    hdu5407 CRB and Candies
    hdu1018 Big Number
    hdu5410 CRB and His Birthday
    hdu1023 Train Problem II
    hdu4812 D Tree
    hdu1085 Holding Bin-Laden Captive!
    hdu4810 Wall Painting
  • 原文地址:https://www.cnblogs.com/aijiao/p/10030972.html
Copyright © 2011-2022 走看看