Java编程读取双网卡的IP地址和MAC地址

当只有单网卡时,获取本机的IP比较简单,但是当有两个网卡,两个均连内网或一个内网一个外网时,读取IP就不能用间的getaddress了,可以用下面的方法来实现。

读取双网卡或多网卡IP:

public static ArrayList getMACAddress() {
ArrayList addresses = new ArrayList();
String address = "";
String os = System.getProperty("os.name");
if (os != null && 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("IP Address") > 0) {
int index = line.indexOf(":");
index += 2;
address = line.substring(index);
addresses.add(address.trim());
}
System.out.println(line);
}
br.close();
return addresses;
} catch (IOException e) {
e.printStackTrace();
}
}
return addresses;
}

读取mac地址的程序如下:

Process process = Runtime.getRuntime().exec("cmd /c ipconfig /all");
  BufferedReader bufferedReader =
  new BufferedReader(new InputStreamReader (process.getInputStream()));
  while ( (line=bufferedReader.readLine()) != null){
  if(line.indexOf("Physical Address. . . . . . . . . :") != -1){
  if(line.indexOf(":") != -1){
  physicalAddress = line.substring(line.indexOf(":")+2);

你可能感兴趣的