获取同网段其它机器的Mac地址

如果需要获取另外一台机器的Mac地址,可以使用SendARP方法将IP地址解析成MAC地址。网上可以找到现成资料,但大部分只确保返回一个Int64类型的数据,但在将Int64转换为MAC字符串时却少有资料。我对网上的程序重新改写了一番,在这里给出一个完整的例子:

None.gif using  System;
None.gif
using  System.Text;
None.gif
using  System.Runtime.InteropServices;
None.gif
None.gif
class  RemoteMac
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif   [DllImport(
"Iphlpapi.dll")]
InBlock.gif   
private static  extern int SendARP(Int32 dest,Int32 host,ref Int64 mac,ref Int32 length);
InBlock.gif   [DllImport(
"Ws2_32.dll")]
InBlock.gif   
private static extern Int32 inet_addr(string ip); 
InBlock.gif
InBlock.gif   [STAThread]
InBlock.gif   
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif      Console.WriteLine(GetRemoteMAC(
"***.***.***.***","***.***.***.***"));
ExpandedSubBlockEnd.gif   }

InBlock.gif
InBlock.gif   
public static string GetRemoteMAC(string localIP, string remoteIP)
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif{
InBlock.gif      Int32 ldest
= inet_addr(remoteIP); //目的地的ip
InBlock.gif
      Int32 lhost= inet_addr(localIP);  //本地服务器的ip
InBlock.gif

InBlock.gif      
string MacStr = "Unknown";
InBlock.gif      Int64 macinfo 
= new Int64(); 
InBlock.gif      Int32 len 
= 6
InBlock.gif      
InBlock.gif      
try
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
InBlock.gif         SendARP(ldest,
0ref macinfo, ref len); 
InBlock.gif         
byte[] b = BitConverter.GetBytes(macinfo); 
InBlock.gif         MacStr 
= ByteArrayToMacString(b); 
ExpandedSubBlockEnd.gif      }

InBlock.gif      
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif{
ExpandedSubBlockEnd.gif      }

InBlock.gif
InBlock.gif      
return MacStr;
ExpandedSubBlockEnd.gif   }

InBlock.gif
InBlock.gif   
static public string ByteArrayToMacString(byte[] buff) 
ExpandedSubBlockStart.gifContractedSubBlock.gif   
dot.gif
InBlock.gif      StringBuilder sb 
= new StringBuilder();
InBlock.gif      
for(int i = 0; i < 6; i++
ExpandedSubBlockStart.gifContractedSubBlock.gif      
dot.gif
InBlock.gif         sb.Append(String.Format(
"{0:X2}",buff[i]));
InBlock.gif         sb.Append(
'-');
ExpandedSubBlockEnd.gif      }

InBlock.gif      sb.Remove(
17,1);
InBlock.gif
InBlock.gif      
return sb.ToString(); 
ExpandedSubBlockEnd.gif   }
 
ExpandedBlockEnd.gif}
 

实际使用时,请将命令

Console.WriteLine(GetRemoteMAC("***.***.***.***","***.***.***.***"));

中的“***.***.***.***”分别替换成自己机器的IP地址以及希望获取其MAC地址的那台机器的IP地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值