java程序获取本地IP地址和mac地址
搜了网上有很多种方法,比较下来下面的方式应该是最正宗的。
/**
* 获取本机所有IP
*/
private static String[] getAllLocalHostIP(){
List<String> res=new ArrayList<String>();
Enumeration netInterfaces;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
Enumeration nii=ni.getInetAddresses();
while(nii.hasMoreElements()){
ip = (InetAddress) nii.nextElement();
if (ip.getHostAddress().indexOf(":") == -1) {
res.add(ip.getHostAddress());
// System.out.println("本机的ip=" + ip.getHostAddress());
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return (String[])res.toArray(new String[0]);
}
/**
* 获取本机所有物理地址
* @return
*/
private static String[] getAllLocalMac(){
List<String> res=new ArrayList<String>();
Enumeration netInterfaces;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
byte[] mac=ni.getHardwareAddress();
StringBuilder sb = new StringBuilder();
if (mac!=null) {
for (byte b : mac) {
sb.append(toHexByte(b));
sb.append("-");
}
sb.deleteCharAt(sb.length() - 1);
res.add(sb.toString());
// System.out.println("mac:"+sb.toString());
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return (String[])res.toArray(new String[0]);
}