Java 中获取MAC地址 和IP地址
package pack.java.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class SystemMessageUtil {
/**
* 获取操作系统名称:
* @return
*/
private static String getOSName(){
return System.getProperty("os.name").toLowerCase();
}
/**
* 获取本地IP地址;
* @return
*/
private String getLocalIpAddress(){
String ipAddress = null;
try {
ipAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ipAddress;
}
/**
* 获取本机的MAC地址;
* @return
*/
public String getLocalWindosMacAddress(){
String mac = null;
BufferedReader bufferReader = null;
Process process = null;
try {
//windows 下显示mac网卡地址信息;
process = Runtime.getRuntime().exec("ipconfig /all");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
int index = -1;
try {
while ((line=bufferReader.readLine())!=null) {
System.out.println(line);
index = line.indexOf("Physical Address");
if(index>=0){
index = line.indexOf(":");
if(index>=0){
mac = line.substring(index+1).trim();
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(bufferReader!=null){
bufferReader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return mac;
}
public static void main(String[]args) {
// TODO Auto-generated method stub
SystemMessageUtil messageUtil = new SystemMessageUtil();
System.out.println(messageUtil.getLocalIpAddress());
}
}