C#获取本机IP地址和Mac地址的代码

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

C#获取本机IP地址和Mac地址的代码
查找了几个方法,经过调试修改,下面这个方法能很好的获取到本地的IP和MAC地址。可以用于这方面的功能实现。主要是要添加System.Management的引用。
using System;
using System.Management;
using System.Net;
 
 public class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string ip = "";
                string mac = "";
                ManagementClass mc;
                string hostInfo = Dns.GetHostName();
                //IP地址
                //System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;这个过时
                  System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
                for (int i = 0; i < addressList.Length; i++)
                {
                    ip = addressList[i].ToString();
                }
                //mac地址
                mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if (mo["IPEnabled"].ToString() == "True")
                    {
                        mac = mo["MacAddress"].ToString();
                    }
                }
                //输出
                string outPutStr = "IP:{0},\n MAC地址:{1}";
                outPutStr = string.Format(outPutStr, ip, mac);
                Console.WriteLine(outPutStr);
            }
            catch (Exception e)
            { }
            Console.ReadLine();
        }
    }