1.获取计算机地址
public String getAddress() {
try {
InetAddress address = InetAddress.getLocalHost();
return address.getHostAddress();
} catch (UnknownHostException e) {
// 异常或无权访问设置为 127.0.0.1
e.printStackTrace();
return "127.0.0.1";
}
}
2.获取计算机名称
public String getHostName() {
try {
InetAddress address = InetAddress.getLocalHost();
return address.getHostName();
} catch (UnknownHostException e) {
// 异常或无权访问设置为 localhost
e.printStackTrace();
return "localhost";
}
}
3.获取计算机MAC地址
public static String getMac() {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i ++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "\n"));
}
return sb.toString();
} catch (UnknownHostException | SocketException e) {
// 异常或无权访问设置为 localhost
e.printStackTrace();
return "00-00-00-00-00-00";
}
}
还没有评论,来说两句吧...