.NET开发

本类阅读TOP10

·NHibernate快速指南(翻译)
·vs.net 2005中文版下载地址收藏
·【小技巧】一个判断session是否过期的小技巧
·VB/ASP 调用 SQL Server 的存储过程
·?dos下编译.net程序找不到csc.exe文件
·通过Web Services上传和下载文件
·学习笔记(补)《.NET框架程序设计(修订版)》--目录
·VB.NET实现DirectDraw9 (2) 动画
·VB.NET实现DirectDraw9 (1) 托管的DDraw
·建站框架规范书之——文件命名

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
获取指定IP的终端的MAC地址

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

    因为业务需要,需要给公司部分终端进行登记,以保证授权终端能够登录业务系统,最好的方法就是记录下每台终端的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();
  }




相关文章

相关软件