當只有單網卡時,獲取本機的IP比較簡單,但是當有兩個網卡,兩個均連內網或一個內網一個外網時,讀取IP就不能用間的getaddress了,可以用下面的方法來實現。
讀取雙網卡或多網卡IP:
public static ArrayList<String> getMACAddress() {
ArrayList<String> addresses = new ArrayList<String>();
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);