中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档 | 网通镜像
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 编程语言 > .NET > 临时文章
获取指定IP的终端的MAC地址
作者:未知 时间:2005-04-11 12:12 出处:Blog 责编:chinaitpower
              摘要:暂无

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

关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有