查询linux、Windows多mac地址、ip地址

在linux和Windows中,通常都会有多块mac地址,默认只会获取第一块mac地址。
笔者编写了通用工具类查询多平台,多mac地址和ip地址。

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.LinkedHashMap;

/**
 * @Description:
 * @date:2019/10/19 13:39
 * @author:YZD
 */
public class GetLocalMac {
	
    public static void main(String[] args) throws Exception {
        new GetLocalMac().get();
    }
    private LinkedHashMap<String,String> get() throws SocketException {
        LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
        try {
            Enumeration<NetworkInterface> interfaces = null;
            interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                Enumeration<InetAddress> addresss = ni.getInetAddresses();
                while (addresss.hasMoreElements()) {
                    InetAddress nextElement = addresss.nextElement();
                    String hostAddress = nextElement.getHostAddress();
                    if (hostAddress.length() <= 16 && hostAddress.length() >= 8 && ni.getHardwareAddress() != null) {
                        System.out.println("IP:" + hostAddress);
                        StringBuffer sb = new StringBuffer("");
                        for (int i = 0; i < ni.getHardwareAddress().length; i++) {
                            if (i != 0) {
                                sb.append("-");
                            }
                            //字节转换为整数
                            int temp = ni.getHardwareAddress()[i] & 0xff;
                            String str = Integer.toHexString(temp);
                            if (str.length() == 1) {
                                sb.append("0" + str);
                            } else {
                                sb.append(str);
                            }
                        }
                        String mac = sb.toString().toUpperCase();
                        System.out.println("MAC:" + mac);
                        linkedHashMap.put(hostAddress, mac);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
            return linkedHashMap;
    }

}

测试:
linux、Windows编译,运行测试命令:
javac GetLocalMac.java -encoding UTF-8
java GetLocalMac
在这里插入图片描述
在这里插入图片描述

发布了116 篇原创文章 · 获赞 107 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_35385687/article/details/102640570