前情提要
- 每台联网设备的MAC地址是唯一固定的,所以很多时候都会有获取AMC地址的需求
- MAC地址即使网卡的唯一标识
MAC获取代码
import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; /** * Created by Administrator on 2018/5/30 0030. */ public class NetUtils { /** * @param args * @throws UnknownHostException * @throws SocketException */ public static void main(String[] args) throws UnknownHostException, SocketException { //得到IP,输出SC-201707281232/192.168.1.20 InetAddress ia = InetAddress.getLocalHost(); System.out.println(ia); getLocalMac(ia); } private static void getLocalMac(InetAddress ia) throws SocketException { // TODO Auto-generated method stub //获取网卡,获取地址 byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress(); System.out.println("mac数组长度:"+mac.length); 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); System.out.println("每8位:"+str); if(str.length()==1) { sb.append("0"+str); }else { sb.append(str); } } System.out.println("本机MAC地址:"+sb.toString().toUpperCase()); } }
测试输出
----------输出结果如下--------------
SC-201707281232/192.168.1.20
mac数组长度:6
每8位:1c
每8位:b7
每8位:2c
每8位:ef
每8位:ba
每8位:3d
本机MAC地址:1C-B7-2C-EF-BA-3D
Process finished with exit code 0
mac数组长度:6
每8位:1c
每8位:b7
每8位:2c
每8位:ef
每8位:ba
每8位:3d
本机MAC地址:1C-B7-2C-EF-BA-3D
Process finished with exit code 0
----------获取的值是没有问题的