获取单个IP或IP段的MAC地址
代码:GetMac2.java。
执行class命令示例:java -classpath bin GetMac2 192.168.1.3
或
java -classpath bin GetMac2 192.168.1.3 6
代码:
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class GetMac2 {
public static String getMac(String ip) {
List<String> command = new ArrayList<>();
command.add("nbtstat");
command.add("-A");
command.add(ip);
try {
ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process process = builder.start();
LineNumberReader ir = new LineNumberReader(
new InputStreamReader(process.getInputStream(), Charset.forName("gbk"))); //UTF8
String line;
while ((line = ir.readLine()) != null) {
if("".equals(line.trim()))continue;
// System.out.println(line);
if(line.contains("MAC 地址")) {
String arr[] = line.split("=");
return arr[arr.length-1].trim();
}
}
if (process.isAlive()) {
process.waitFor();
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
return "";
}
//命令1: GetMac2 192.168.1.3
//命令2: GetMac2 192.168.1.3 5
public static void main(String[] args) {
String ip = args[0];
if(args.length>1) {
String endIp = args[1]; //结束ip(最末段)
int end = Integer.parseInt(endIp);
int index=ip.lastIndexOf(".");
int start = Integer.parseInt(ip.substring(index+1)); //起始ip(最末段)
String preStr = ip.substring(0, index+1); //ip段前缀
for(int i=start;i<=end;i++) {
String tmpIp = preStr + i;
String mac = getMac(tmpIp);
System.out.println(tmpIp + " " + mac);
}
return;
}
String mac = getMac(ip);
System.out.println(ip + " " + mac);
}
}