日期:2014-01-30  浏览次数:20464 次




    因为业务需要,需要给公司部分终端进行登记,以保证授权终端能够登录业务系统,最好的方法就是记录下每台终端的MAC地址来进行验证是否有授权。

    下面是采用调用API的方式获取指定IP的终端的MAC地址:

  [DllImport("Iphlpapi.dll")]
  public static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
  //dest为目标机器的IP;Host为本机器的IP

  [DllImport("Ws2_32.dll")]
  public static extern Int32 inet_addr(string ip);

  public static string GetNetCardAddress(string strIp)
  {
   try
   {
    IPHostEntry host = Dns.GetHostByName(System.Environment.MachineName);
    Int32 local = inet_addr(host.AddressList[0].ToString());
    Int32 remote = inet_addr(strIp);

    Int64 macinfo = new Int64();
    Int32 length = 6;
    SendARP(remote, local, ref macinfo, ref length);

    string temp = System.Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();

    StringBuilder strReturn = new StringBuilder();
    int x = 12;
    for(int i=0;i<6;i++)
    {
     strReturn.Append(temp.Substring(x-2, 2));
     x -= 2;
    }

    return strReturn.ToString();
   }
   catch(Exception error)
   {
    throw new Exception(error.Message);
   }
  }

    在上面的方式使用一段时间之后发现只能获取到同一网段或没有经过任何路由的终端的MAC地址,而对那些不同网段或经过了路由的终端的MAC地址则无法正常获取到MAC地址。下面的操作系统命令方式可以解决此问题:

  public static string GetNetCardAddress2(string strIp)
  {
   string mac = "";

   System.Diagnostics.Process process = new System.Diagnostics.Process();
   process.StartInfo.FileName = "nbtstat";
   process.StartInfo.Arguments = "-a "+strIp;
   process.StartInfo.UseShellExecute = false;
   process.StartInfo.CreateNoWindow = true;
   process.StartInfo.RedirectStandardOutput = true;
 
   process.Start();
 
   string output = process.StandardOutput.ReadToEnd();
   int length = output.IndexOf("MAC Address = ");

   if(length>0)
   {
    mac = output.Substring(length+14, 17);
   }
 
   process.WaitForExit();
 
   return mac.Replace("-", "").Trim();
  }