获取指定IP的终端的MAC地址

王朝other·作者佚名  2006-01-09
宽屏版  字体: |||超大  

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

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有