前情提要

  • 每台联网设备的MAC地址是唯一固定的,所以很多时候都会有获取AMC地址的需求
  • MAC地址即使网卡的唯一标识
  • 有时候写后台程序,或者GUI程序时,需要直接获取程序运行的所在电脑的ip地址

MAC获取

获取代码

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * Created by Administrator on 2018/6/26 0026.
 * 系统工具类
 */
public class SystemUtils {
    /**
     * 获取本机MAC地址
     *
     * @return
     */
    public static final String getLocalMac() {
        String localMac = null;
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            /**
             * 获取电脑网卡的AMC地址
             * 返回包含硬件地址的 byte 数组;如果地址不存在或不可访问,则返回 null
             */
            byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
            StringBuffer stringBuffer = new StringBuffer("");
            for (int i = 0; i < mac.length; i++) {
                if (i != 0) {
                    stringBuffer.append("-");
                }
                /**
                 * 转换mac的字节数组
                 */
                int temp = mac[i] & 0xff;
                String str = Integer.toHexString(temp);
                if (str.length() == 1) {
                    stringBuffer.append("0" + str);
                } else {
                    stringBuffer.append(str);
                }
            }
            localMac = stringBuffer.toString().toUpperCase();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return localMac;
    }
}

测试输出

----------输出结果如下--------------
本机MAC地址:1C-B7-2C-EF-BA-3D

Process finished with exit code 0
----------获取的值是没有问题的

获取 MAC 地址 与 本机IP地址

本机IP获取

获取代码

InetAddress inetAddress = InetAddress.getLocalHost();
//获取本机ip
String ip = inetAddress.getHostAddress().toString();
//获取本机计算机名称
String hostName = inetAddress.getHostName().toString();
System.out.println("IP地址:"+ip);
System.out.println("主机名:"+hostName);

结果输出

获取 MAC 地址 与 本机IP地址




相关文章: