采飞扬的小屋

导航

利用IP,用C#来获得远程主机的MAC地址

以前在一个网站看到一篇这样的文章,感觉还不错。这几天因为我和朋友写的一个程序可能需要这样的功能,就用了那篇文章的方法,可是却发现有很多不如意的地方,也就是说他的思路对了,可是程序的编写却很有问题。我就自己写了一个DLL文件给朋友了。实际实现起来很简单,就是采用P/Invoke的方式就可以了,用的函数主要就是一个SendARP()而已,主要是得到的结果的处理方式需要考虑一下。当然看到这你也许已经知道这个DLL文件的局限了——它只能获得局域网里面主机的MAC地址。出了局域网怎么办我还想不到好办法,不知哪位高手可以指点一下,谢谢。我的邮箱是janent521@163.com.
下面就把代码贴出来了,不足之处还请指正!

using System;
using System.Text ;
using System.Runtime .InteropServices ;

namespace SnifferMac
{
 
/// <summary>
 
/// Mac的摘要说明。
 
/// </summary>

 public class LibWrap
 
{
  [DllImport(
"Ws2_32.dll")]
   
public static extern Int32 inet_addr(string  ip);
  [DllImport(
"Iphlpapi.dll")]
   
public static extern uint SendARP([In]Int32 dest ,[In]Int32 soc,ref Int64 mac,[In,Out]ref Int32 len);
 }

 
public class Mac
 
{
  
private static string mac;
  
private static Int64 macinfo;

  
public Mac()
  
{
   
//
   
// TODO: 在此处添加构造函数逻辑
   
//
  }

  
public static string GetMac(string deIP)
  
{
   Int32 des
=LibWrap.inet_addr(deIP);
   macinfo
=new Int64();
   Int32 len
=6;
   LibWrap.SendARP(des,
0,ref macinfo,ref len);
   mac
=macinfo.ToString("x4");
   StringBuilder sb
=new StringBuilder() ; 
   
string s;
   
int i=0;
   
if(mac!="0000"&&mac.Length ==12)
   
{
    
while(i<12)
    
{
     s
=mac.Substring(10-i,2);
     sb.Append(s.ToUpper() );
     
if(i!=10
      sb.Append(
"-") ;
     i
+=2;
    }

    mac
=sb.ToString() ;
   }

   
else
   
{
    mac
="Wrong mac!";
   }

   
return mac;
  }

 }

}


 

posted on 2007-05-07 21:03  采飞扬  阅读(1303)  评论(2编辑  收藏  举报