Java 获取计算机地址、计算机名称、计算机MAC地址

妖狐艹你老母 2023-09-29 17:12 72阅读 0赞

1.获取计算机地址

  1. public String getAddress() {
  2. try {
  3. InetAddress address = InetAddress.getLocalHost();
  4. return address.getHostAddress();
  5. } catch (UnknownHostException e) {
  6. // 异常或无权访问设置为 127.0.0.1
  7. e.printStackTrace();
  8. return "127.0.0.1";
  9. }
  10. }

2.获取计算机名称

  1. public String getHostName() {
  2. try {
  3. InetAddress address = InetAddress.getLocalHost();
  4. return address.getHostName();
  5. } catch (UnknownHostException e) {
  6. // 异常或无权访问设置为 localhost
  7. e.printStackTrace();
  8. return "localhost";
  9. }
  10. }

3.获取计算机MAC地址

  1. public static String getMac() {
  2. try {
  3. InetAddress inetAddress = InetAddress.getLocalHost();
  4. byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
  5. StringBuilder sb = new StringBuilder();
  6. for (int i = 0; i < mac.length; i ++) {
  7. sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "\n"));
  8. }
  9. return sb.toString();
  10. } catch (UnknownHostException | SocketException e) {
  11. // 异常或无权访问设置为 localhost
  12. e.printStackTrace();
  13. return "00-00-00-00-00-00";
  14. }
  15. }

发表评论

表情:
评论列表 (有 0 条评论,72人围观)

还没有评论,来说两句吧...

相关阅读