###一:通过命令ipconfig /all获取本机MAC地址(Windows平台)
在Windows中执行ipconfig /all命令后,会得到下图所示内容:
可以看出其中就包含着本机的MAC地址,若是我们能用Java执行“ipconfig /all”命令,并获取到上图中的内容,进而便可获取到本机MAC地址。
那么java可以执行Windows命令吗?答案是肯定的。
你可以这样做(将ipconfig /all替换为你想要执行的Windows命令即可):
Runtime.getRuntime().exec("cmd.exe /c ipconfig /all");
下面贴出完整的获取本机MAC地址的代码,以供大家参考
public static void main(String[] args){
try {
Process process = Runtime.getRuntime().exec("cmd.exe /c ipconfig /all");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("Physical Address") > 0) {
int index = line.indexOf(":");
index += 2;
String address = line.substring(index);
System.out.println(address);
break;
}
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
###二:使用NetworkInterface,通过本机IP或者本机名获取本机MAC地址
通过本机IP地址获取MAC地址
byte[] addr = {(byte) 192,(byte) 168,1,103};
NetworkInterface ne=NetworkInterface.getByInetAddress(InetAddress.InetAddress.getByAddress(addr));
byte[] mac = ne.getHardwareAddress();
根据本机名获取MAC地址
NetworkInterface ne=NetworkInterface.getByInetAddress(InetAddress.getByName("XB-20150408SKNM"));
byte[] mac = ne.getHardwareAddress();
###三、通过IP获取局域网中的其他设备的MAC地址
思路:
先前已经说明:使用java可以执行Windows命令。
1、ping ip
若ping不通则说明此IP不在本局域网内,操作就此终止;
若ping的通,证明此IP在局域网内,然后使用命令arp -a IP获取如下图所示信息:
2、获取上图中的内容,进而获取到MAC地址。
解释一个问题:为什么要先ping ip呢?
因为arp命令用于显示和修改 “ 地址解析协议 (ARP)” 缓存中的项目。 也就是说局域网中的设备若是没有跟本机(执行arp命令的设备)通信过,那么执行arp命令后是得不到其信息的。
所以我们先ping ip,然后就能之用arp命令查看到对应的信息了。
示例代码:
/**
* 执行单条指令
* @param cmd 命令
* @return 执行结果
* @throws Exception
*/
public static String command(String cmd) throws Exception{
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
InputStream in = process.getInputStream();
StringBuilder result = new StringBuilder();
byte[] data = new byte[256];
while(in.read(data) != -1){
String encoding = System.getProperty("sun.jnu.encoding");
result.append(new String(data,encoding));
}
return result.toString();
}
/**
* 获取mac地址
* @param ip
* @return
* @throws Exception
*/
public static String getMacAddress(String ip) throws Exception{
String result = command("ping "+ip+" -n 2");
if(result.contains("TTL")){
result = command("arp -a "+ip);
}
String regExp = "([0-9A-Fa-f]{2})([-:][0-9A-Fa-f]{2}){5}";
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(result);
StringBuilder mac = new StringBuilder();
while (matcher.find()) {
String temp = matcher.group();
mac.append(temp);
}
return mac.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
System.out.println(getMacAddress("192.168.1.108"));
System.out.println(System.currentTimeMillis());
}
参考资料:
1、最靠谱的JAVA局域网内通过IP地址获取MAC地址(本人亲测)
2、java怎么样获取局域网内活动Ip和主机名
3、怎么样获取局域网的所有IP地址(在不知道主机名的情况下)