JAVA获取本地,远程macAddress(二)

2014-11-24 02:22:20 · 作者: · 浏览: 4
nit ID 6字节(48位
private String GetMacAddr(byte[] b) throws Exception
{
// 获取计算机名
//System.out.println(new String(b, 57, 18));
//System.out.println(new String(b, 75, 18));
//System.out.println(new String(b, 93, 18));
int i = b[56] * 18 + 56;
String sAddr = "";
StringBuffer sb = new StringBuffer(17);
// 先从第56字节位置,读出Number Of Names(NetBIOS名字的个数,其中每个NetBIOS Names
// Info部分占18个字节)
// 然后可计算出“Unit ID”字段的位置=56+Number Of
// Names×18,最后从该位置起连续读取6个字节,就是目的主机的MAC地址。
for (int j = 1; j < 7; j++)
{
sAddr = Integer.toHexString(0xFF & b[i + j]);
if (sAddr.length() < 2)
{
sb.append(0);
}
sb.append(sAddr.toUpperCase());
if (j < 6)
sb.append('-');
}
return sb.toString();
}

private void close()
{
try
{
ds.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

public String GetRemoteMacAddr() throws Exception
{
byte[] bqcmd = GetQueryCmd();
this.send(bqcmd);
DatagramPacket dp = this.receive();
String smac = GetMacAddr(dp.getData());
this.close();
return smac;
}

public static void main(String[] args) throws Exception
{
RemoteMacAddr addr = new RemoteMacAddr("192.168.1.119");
System.out.println(addr.GetRemoteMacAddr());
}
}