最近在做老系統的CS到BS的改造。碰到一個需要獲取指定IP主機MAC地址的問題。實在沒有想出什么好辦法,只能通過DOS命令折中一下。壞處就是不能跨平臺了,哪位大俠知道怎么做純java的實現?一定指點我一下。
package com.dayang.utils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
/**
* 網絡工具
*
* @author relax
*/
public class NetworkUtil {
/**
* 根據指定IP獲取MAC地址
* @param ip
* @return
*/
public static String getMACAddress(String ip) {
String str;
String macAddress = null;
try {
Process p = Runtime.getRuntime().exec("nbtstat -a " + ip);//執行DOS命令
InputStreamReader ir = new InputStreamReader(p.getInputStream());//獲取返回結果的流
LineNumberReader input = new LineNumberReader(ir);
//查找Mac地址
for (int i = 1; i < 100; i++) {
str = input.readLine();
if (str != null) {
if (str.contains("MAC Address")) {
macAddress = str.substring(str.indexOf("= ")+2, str.length()).replace("-", "");
break;
}
}
}
ir.close();
} catch (IOException e) {
e.printStackTrace();
}
return macAddress;
}
public static void main(String args[]) {
System.err.println(getMACAddress("192.168.0.151"));
}
}