[C# basic knowledge] Get the ip address and MAC of the network card

【Get IP】

One: Applicable to a single network card situation

            string hostInfo = Dns.GetHostName();

            //IP地址
            //System.Net.IPAddress[] addressList = Dns.GetHostByName(hostInfo).AddressList;这个过时
            System.Net.IPAddress[] addressList = Dns.GetHostEntry(hostInfo).AddressList;
            ip = addressList[0].ToString();


2: Applicable to multiple network cards

           foreach (NetworkInterface netInt in NetworkInterface.GetAllNetworkInterfaces())
           {
                IPInterfaceProperties property = netInt.GetIPProperties();
                foreach (UnicastIPAddressInformation ip in property.UnicastAddresses)
                {
                    if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ipaddr = ip.Address.ToString();
                    }
                }
            }  

3.

                      ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                      ManagementObjectCollection moc = mc.GetInstances();
                      if ((bool)mo["IPEnabled"] == true)
                      {
                          if (mo["IPAddress"] != null)
                              strIP = ((string[])mo["IPAddress"])[0];
                      }   
                      else
                      {
                          strIP = "0.0.0.0";
                      }

【Get MAC】

1. 

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    mac = mo["MacAddress"].ToString();
                    break;
                }
            }

2. NetworkInformation 

 foreach (NetworkInterface netInt in NetworkInterface.GetAllNetworkInterfaces())
            {
                netmac = netInt.GetPhysicalAddress().ToString();
            }






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324133167&siteId=291194637