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(); } }
第二种方式
/// <summary> /// 获取Mac地址 /// </summary> /// <param name="DestIP"></param> /// <param name="SrcIP"></param> /// <param name="pMacAddr"></param> /// <param name="PhyAddrLen"></param> /// <returns></returns> [DllImport("Iphlpapi.dll")] public static extern uint SendARP(uint DestIP, uint SrcIP, ref ulong pMacAddr, ref uint PhyAddrLen); public static string GetMac() { string p_Id = GetInternalIP(); IPAddress _Address; if (!IPAddress.TryParse(p_Id, out _Address)) return ""; uint DestIP = System.BitConverter.ToUInt32(_Address.GetAddressBytes(), 0); ulong pMacAddr = 0; uint PhyAddrLen = 6; uint error_code = SendARP(DestIP, 0, ref pMacAddr, ref PhyAddrLen); byte[] _Bytes1 = BitConverter.GetBytes(pMacAddr); return BitConverter.ToString(_Bytes1, 0, 6); } //获取内网IP protected static string GetInternalIP() { IPHostEntry host; string localIP = "?"; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily.ToString() == "InterNetwork") { localIP = ip.ToString(); break; } } return localIP; }