我们都知道通过在电脑上敲 cmd 后,输入ipconfig -all 来获取IP地址或者MAC地址,java程序可以在window和linux下获取MAC地址等信息!看下面代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
/**
*
* @author http://zhidao.baidu.com/question/292753600.html
*/
public class TestMac {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println("Operation System=" + getOsName());
System.out.println("Mac Address=" + getMACAddress());
System.out.println("通过ip获取mac地址为:" + getMACAddress("192.168.2.14"));
long end = System.currentTimeMillis();
System.out.println("获取电脑MAC地址时间为:" + (end - start));
}
/**
* 获取操作系统名称
*/
public static String getOsName() {
String os = "";
os = System.getProperty("os.name");
return os;
}
/**
* 获取MAC地址
*/
public static String getMACAddress() {
String address = "";
String os = getOsName();
//根据操作系统类型获取MAC地址
if (os.startsWith("Windows")) {
try {
String command = "cmd.exe /c ipconfig /all";
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("Physical Address") > 0) {
int index = line.indexOf(":");
index += 2;
address = line.substring(index);
break;
}
}
br.close();
return address.trim();
} catch (IOException e) {
}
} else if (os.startsWith("Linux")) {
String command = "/bin/sh -c ifconfig -a";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("HWaddr") > 0) {
int index = line.indexOf("HWaddr") + "HWaddr".length();
address = line.substring(index);
break;
}
}
br.close();
} catch (IOException e) {
}
}
address = address.trim();
return address;
}
/**
* 根据IP地址获取MAC地址
*/
public static String getMACAddress(String ipAddress) {
String str = "", strMAC = "", macAddress = "";
try {
Process pp = Runtime.getRuntime().exec("nbtstat -a " + ipAddress);
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
if (str != null) {
if (str.indexOf("MAC Address") > 1) {
strMAC = str.substring(str.indexOf("MAC Address") + 14, str.length());
break;
}
}
}
} catch (IOException ex) {
return "Can't Get MAC Address!";
}
if (strMAC.length() < 17) {
return "Error!";
}
macAddress = strMAC.substring(0, 2) + ":" + strMAC.substring(3, 5) + ":" + strMAC.substring(6, 8) + ":" + strMAC.substring(9, 11) + ":"
+ strMAC.substring(12, 14) + ":" + strMAC.substring(15, 17);
return macAddress;
}
}
注意:
这段代码需要公网访问的服务器上部署后有效,自己的机器上属于局域网,一般获取的都是本地IP,效果不同