【java】获取本机IP地址和网卡的MAC地址

平凡也就两个字: 懒和惰;
成功也就两个字: 苦和勤;
优秀也就两个字: 你和我。
跟着我从0学习JAVA、spring全家桶和linux运维等知识,带你从懵懂少年走向人生巅峰,迎娶白富美!
关注微信公众号【 IT特靠谱 】,每天都会分享技术心得~

获取本机IP地址和网卡的MAC地址

1 什么是MAC地址?

      MAC地址(英语:Media Access Control Address),直译为媒体存取控制位址,也称为局域网地址(LAN Address),MAC位址,以太网地址(Ethernet Address)或物理地址(Physical Address),它是一个用来确认网络设备位置的位址。在OSI模型中,第三层网络层负责IP地址,第二层数据链路层则负责MAC位址  。MAC地址用于在网络中唯一标示一个网卡,一台设备若有一个或多个网卡,则每个网卡都有一个唯一的MAC地址!

2 获取IP地址和MAC地址

      下面通过java来获取本地ip地址和网卡MAC地址。

2.1 获取IP地址

  /**
   * 获取本机IP地址
   */
  private static String getIpAddress() throws UnknownHostException {
    InetAddress ia = InetAddress.getLocalHost();
    return ia.getHostAddress();
  }

2.2 获取网卡的MAC地址

  /**
   * 获取本机使用网卡的MAC地址
   */
  private static String getMacAddress() throws UnknownHostException, SocketException {
    //获取IP地址,输出示例:WCGZ-DZ-013803/10.88.12.117
    InetAddress ia = InetAddress.getLocalHost();
    //获取网卡的MAC地址
    byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mac.length; i++) {
      if (i != 0) {
        sb.append("-");
      }
      //字节转换为整数
      int temp = mac[i] & 0xff;
      String str = Integer.toHexString(temp);
      if (str.length() == 1) {
        sb.append("0" + str);
      } else {
        sb.append(str);
      }
    }
    return sb.toString().toUpperCase();
  }

3 完整代码

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Main {

  public static void main(String[] args) throws UnknownHostException, SocketException {
    //获取本机IP地址
    String ip = getIpAddress();
    //获取本机网卡的MAC地址
    String mac = getMacAddress();
    log.info("IP地址为:{}, 本机网卡MAC地址为:{}", ip, mac);
  }

  /**
   * 获取本机IP地址
   */
  private static String getIpAddress() throws UnknownHostException {
    InetAddress ia = InetAddress.getLocalHost();
    return ia.getHostAddress();
  }

  /**
   * 获取本机使用网卡的MAC地址
   */
  private static String getMacAddress() throws UnknownHostException, SocketException {
    //获取IP地址,输出示例:WCGZ-DZ-013803/10.88.12.117
    InetAddress ia = InetAddress.getLocalHost();
    //获取网卡的MAC地址
    byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mac.length; i++) {
      if (i != 0) {
        sb.append("-");
      }
      //字节转换为整数
      int temp = mac[i] & 0xff;
      String str = Integer.toHexString(temp);
      if (str.length() == 1) {
        sb.append("0" + str);
      } else {
        sb.append(str);
      }
    }
    return sb.toString().toUpperCase();
  }
}

4 测试结果

      如果对你有帮助或需要技术支持,关注一下本人吧~

猜你喜欢

转载自blog.csdn.net/IT_Most/article/details/109313606