Java根据IP地址获取MAC地址
- 先使用ping -n 2 10.0.0.1 命令,如果返回的结果中含有TTL字符,证明ping 10.0.0.1是能ping通的,即可达的。如果在Linux机器上请使用 ping -c 2 10.0.0.1命令
- 再使用arp -a 10.0.0.1命令,在windows的cmd中使用该命令的返回结果如下图
- 得到 10.0.0.1的Mac地址为34-96-72-a0-ee-b5
- 既然通过这两个命令能实现从IP地址到MAC地址的转换,那么在Java后台无非就是执行这两条命令,对结果进行分析,对字符串进行处理得到MAC地址
-
-
package com.security.common.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IP2MacUtils { public static String commond(String cmd) throws IOException{ Process process = Runtime.getRuntime().exec(cmd); InputStream inputStream = process.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String line = null; while((line = bufferedReader.readLine()) != null ){ //String encode = System.getProperty("sun.jun.encoding"); stringBuilder.append(line); } return stringBuilder.toString(); } public static String getMacByIP(String IPAddress) throws IOException{ String result = commond("ping -n 3 " + IPAddress); if ( result.contains("TTL")) { result = commond("arp -a " + IPAddress); } System.out.println(result); String regExp = "([0-9A-Fa-f]{2})([-:][0-9A-Fa-f]{2}){5}"; Pattern pattern = Pattern.compile(regExp); Matcher matcher = pattern.matcher(result); StringBuilder stringBuilder = new StringBuilder(); while( matcher.find() ){ String temp = matcher.group(); System.out.println(temp); stringBuilder.append(temp); } return stringBuilder.toString(); } public static void main(String[] args) throws IOException{ System.out.println("MAC : " + getMacByIP("10.0.0.1")); } }
- 最终程序的运行结果为
-
得到的结果一如命令行得到的结果,从而实现了Java中由IP地址得到MAC地址。
-
Java.lang.Process , Pattern , Matcher ,正则表达式的简单使用