獲取指定IP的終端的MAC地址
2024-07-21 02:16:03
供稿:網(wǎng)友
因?yàn)闃I(yè)務(wù)需要,需要給公司部分終端進(jìn)行登記,以保證授權(quán)終端能夠登錄業(yè)務(wù)系統(tǒng),最好的方法就是記錄下每臺(tái)終端的mac地址來進(jìn)行驗(yàn)證是否有授權(quán)。
下面是采用調(diào)用api的方式獲取指定ip的終端的mac地址:
[dllimport("iphlpapi.dll")]
public static extern int sendarp(int32 dest, int32 host, ref int64 mac, ref int32 length);
//dest為目標(biāo)機(jī)器的ip;host為本機(jī)器的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);
}
}
在上面的方式使用一段時(shí)間之后發(fā)現(xiàn)只能獲取到同一網(wǎng)段或沒有經(jīng)過任何路由的終端的mac地址,而對那些不同網(wǎng)段或經(jīng)過了路由的終端的mac地址則無法正常獲取到mac地址。下面的操作系統(tǒng)命令方式可以解決此問題:
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();
}