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