*获取mac地址的方法

public class NetUtil:System.Web.UI.Page
 {
  [DllImport("Iphlpapi.dll")]
  private static extern int SendARP(Int32 dest,Int32 host,ref Int64 mac,ref Int32 length);
  [DllImport("Ws2_32.dll")]
  private static extern Int32 inet_addr(string ip);
  public static string GetMAC(string ip)
  {
   if("127.0.0.1" == ip)
   {
    return GetLocalHostMac();
   }
   else
   {
    return GetRemoteHostMac(ip);
   }
  }
  private static string GetLocalHostMac()
  {
   string mac = "";
   ManagementObjectSearcher query =new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration") ;
   ManagementObjectCollection queryCollection = query.Get();
   foreach( ManagementObject mo in queryCollection )
   {
    if(mo["IPEnabled"].ToString() == "True")
     mac = mo["MacAddress"].ToString();
   }
   mac = mac.Replace(":","-");
   return mac;
  }
  private static string GetRemoteHostMac(string ip)
  {
   Int64 macinfo = new Int64();
   Int32 len = 6;
   Int32 ldest = inet_addr(ip); //目的地的ip
   int res = SendARP(ldest,0, ref macinfo, ref len);
   string mac_src=macinfo.ToString("X");

   while(mac_src.Length<12)
   {
    mac_src = mac_src.Insert(0,"0");
   }
   string mac_dest="";

   for(int i=0;i<11;i++)
   {
    if (0 == (i % 2))
    {
     if ( i == 10 )
     {
      mac_dest = mac_dest.Insert(0,mac_src.Substring(i,2));
     }
     else
     {
      mac_dest ="-" + mac_dest.Insert(0,mac_src.Substring(i,2));
     }
    }
   }
   return mac_dest;
  }
 }

原文地址:https://www.cnblogs.com/dwjaissk/p/875836.html