c#获取本地IP和MAC地址

查找了几个方法,经过调试修改,下面这个方法能很好的获取到本地的IP和MAC地址。可以用于这方面的功能实现。主要是要添加System.Management的引用。

[csharp]  view plain  copy
 print ?
  1. using System;  
  2. using System.Management;  
  3. using System.Net;  
  4.   
  5.  public class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             try  
  10.             {  
  11.                 string ip = "";  
  12.                 string mac = "";  
  13.                 ManagementClass mc;  
  14.                 string hostInfo = Dns.GetHostName();  
  15.                 //IP地址  
  16.                 //System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;这个过时  
  17.                   System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;  
  18.                 for (int i = 0; i < addressList.Length; i++)  
  19.                 {  
  20.                     ip = addressList[i].ToString();  
  21.                 }  
  22.                 //mac地址  
  23.                 mc = new ManagementClass("Win32_NetworkAdapterConfiguration");  
  24.                 ManagementObjectCollection moc = mc.GetInstances();  
  25.                 foreach (ManagementObject mo in moc)  
  26.                 {  
  27.                     if (mo["IPEnabled"].ToString() == "True")  
  28.                     {  
  29.                         mac = mo["MacAddress"].ToString();  
  30.                     }  
  31.                 }  
  32.                 //输出  
  33.                 string outPutStr = "IP:{0},\n MAC地址:{1}";  
  34.                 outPutStr = string.Format(outPutStr, ip, mac);  
  35.                 Console.WriteLine(outPutStr);  
  36.             }  
  37.             catch (Exception e)  
  38.             { }  
  39.             Console.ReadLine();  
  40.         }  
  41.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值