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

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

None.gif using  System;
None.gif
using  System.Text ;
None.gif
using  System.Runtime .InteropServices ;
None.gif
None.gif
namespace  SnifferMac
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif 
/**//// <summary>
InBlock.gif 
/// Mac的摘要说明。
ExpandedSubBlockEnd.gif 
/// </summary>

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

InBlock.gif 
public class Mac
ExpandedSubBlockStart.gifContractedSubBlock.gif 
dot.gif{
InBlock.gif  
private static string mac;
InBlock.gif  
private static Int64 macinfo;
InBlock.gif
InBlock.gif  
public Mac()
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   
//
InBlock.gif   
// TODO: 在此处添加构造函数逻辑
InBlock.gif   
//
ExpandedSubBlockEnd.gif
  }

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

InBlock.gif    mac
=sb.ToString() ;
ExpandedSubBlockEnd.gif   }

InBlock.gif   
else
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif    mac
="Wrong mac!";
ExpandedSubBlockEnd.gif   }

InBlock.gif   
return mac;
ExpandedSubBlockEnd.gif  }

ExpandedSubBlockEnd.gif }

ExpandedBlockEnd.gif}

None.gif


 

转载于:https://www.cnblogs.com/liuyes/archive/2007/05/07/738272.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值