项目问题小记:mac地址校验

该文介绍了如何获取不同操作系统(银河麒麟、Linux、Windows、USO)的MAC地址,并通过控制器提供接口。此外,文章提到了使用拦截器进行MAC地址校验,以及YML配置文件中的MAC地址设置。在拦截器中,对特定路径进行MAC地址验证,若不匹配则阻止请求。
摘要由CSDN通过智能技术生成

        获取服务器mac地址,通过拦截器拦截请求,校验mac地址,完成!

        代码:

        一、获取mac地址工具类:    

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

@Slf4j
public class MacAddressUtil {

    /**
     *  获取银河麒麟mac地址
     * @return
     * @throws SocketException
     */
    public static String getMACAddressByKylin() throws SocketException {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

        while(networkInterfaces.hasMoreElements()) {
            NetworkInterface network = networkInterfaces.nextElement();
            //log.info("银河麒麟 network:{}", network);
            byte[] mac = network.getHardwareAddress();

            if(mac == null) {
                log.warn("mac is null");
            } else {

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < mac.length; i++) {
                    sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                }
                log.info("银河麒麟 MAC address : {} ", sb);

                if (!"".equals(sb.toString())) {
                    return sb.toString();
                }
                break;
            }
        }
        return "";
    }

    /**
     *  获取linux系统mac地址
     * @return
     */
    public static String getMacAddressByLinux(){
        List<String> macs = new ArrayList<>();
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("ifconfig -a");
            bufferedReader = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            String line = null;
            int index = -1;
            while ((line = bufferedReader.readLine()) != null) {
                index = line.toLowerCase().indexOf("硬件地址");
                String mac = "";
                if (index != -1) {
                    mac = line.substring(index + 4).trim();
                    macs.add(mac.toLowerCase());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            bufferedReader = null;
            process = null;
        }
        log.info("Linux:"+macs);
        return macs.toString();
    }

    /**
     *  获取windows系统mac地址
     * @return
     * @throws Exception
     */
    public static List<String> getMACAddressByWindows() throws Exception {
        ArrayList<String> rs = new ArrayList<>();
        String result = "";
        Process process = Runtime.getRuntime().exec("ipconfig /all");
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
        int index = -1;
        String line;
        while ((line = br.readLine()) != null) {
            index = line.indexOf("物理地址");
            if (index >= 0) {
                index = line.indexOf(":");
                if (index >= 0) {
                    result = line.substring(index + 1).trim();
                }
                rs.add(result.toUpperCase());
            }
        }
        br.close();
        log.info("windows Mac address : {}",rs);
        return rs;
    }

    /**
     *  获取uso系统mac地址
     * @return
     */
    public static List<String> getMacAddressByUSO() {

        ArrayList<String> macs = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            byte[] mac = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint() || !netInterface.isUp()) {
                    continue;
                } else {
                    mac = netInterface.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
                        }
                        if (sb.length() > 0) {
                            macs.add(sb.toString().toLowerCase());
                        }
                    }
                }
            }
            log.info("UOS 获取的mac地址为:{}", macs);
            return macs;
        } catch (Exception e) {
            log.error("UOS MAC地址获取失败", e);
        }
        return Collections.emptyList();
    }

}

        二、通过控制器获取mac地址,在部署前修改项目的yml配置文件,或者添加到数据库,这个看个人习惯

        控制器:

@RestController
@RequestMapping("/mac")
public class SysMacController {

    @Autowired
    private ISysMacService sysMacService;

    /**
     *  查询银河麒麟系统mac地址
     * @return
     */
    @GetMapping("/ql")
    public String getMAC(){
        String mac = null;
        try {
            mac = MacAddressUtil.getMACAddressByKylin();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return mac;
    }

    /**
     *  查询linux系统mac地址
     * @return
     */
    @GetMapping("/linux")
    public String getLinuxMac(){
        String linuxMac = MacAddressUtil.getMacAddressByLinux();
        return linuxMac;
    }

    /**
     *  查询windows系统mac地址
     * @return
     */
    @GetMapping("/win")
    public List<String> getMACAddressByWindows() throws Exception {
        return MacAddressUtil.getMACAddressByWindows();
    }

    /**
     *  查询USO系统mac地址
     * @return
     */
    @GetMapping("/uso")
    public List<String> getMacAddress() {
        return MacAddressUtil.getMacAddressByUSO();
    }

    @PostMapping("/add")
    public Integer addMac(String macAddress){
        SysMac sysMac = new SysMac();
        sysMac.setMacAddress(macAddress);
        return sysMacService.insertSysMac(sysMac);
    }

    @GetMapping("/get")
    public List<SysMac> getMac(SysMac mac){
        List<SysMac> sysMacs = sysMacService.selectSysMacList(mac);
        return sysMacs;
    }




}

        yml

#Mac地址
mac:
  address: 88-53-95-2B-76-37

        三、拦截器,每次请求都拦截(也可以放行)

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Bean
    public MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor())
                //放行
                .excludePathPatterns("/mac/ql")
                //拦截
                .addPathPatterns("/mac/**");
    }
}
@Slf4j
@Component
public class MacAddressInterceptor implements HandlerInterceptor {

    @Value("${mac.address}")
    private String macAddress;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String macAddressByKylin = MacAddressUtil.getMACAddressByKylin();
        if (macAddress.equals(macAddressByKylin)) {
            log.info("mac地址验证通过!");
            return true;
        }
        log.info("mac地址验证未通过!拦截!!!");
        return false;

    }
}

        ps:此处有个小坑,@Value获取不到yml配置文件的值,可以参考大佬的文档!!!

        很简单的一个小功能。       

        完成!

       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值