Java获取请求系统的IP地址、本地IP地址、本地MAC地址

话不多少,上操作

1.获取请求系统的IP地址

public static String getIpAddr(HttpServletRequest request) {
    String ip = "";
    try {
        ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                try {
                    InetAddress inet = InetAddress.getLocalHost();
                    ip = inet.getHostAddress();
                } catch (UnknownHostException e) {
                    log.error("获取请求系统ip出错:" + e);
                }
            }
        }
        ip = ip.split(",")[0];
    } catch (Exception e) {
        log.error("获取请求系统ip出错:" + e);
    }
    return ip;
}

这就行了

2.本地IP地址

private static String getLocalHostIp() {
    try {
        InetAddress inet = InetAddress.getLocalHost();
        return inet.getHostAddress();
    } catch (UnknownHostException e) {
        log.error("获取请求系统ip出错:" + e);
    }
}

3.本地MAC地址

public static String getMacAddress() throws Exception
    InetAddress ia = InetAddress.getLocalHost();
    // 获得网络接口对象(即网卡),并得到mac地址,mac地址存在于一个byte数组中。
    byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
    // 下面代码是把mac地址拼装成String
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < mac.length; i++) {
        if (i != 0) {
            sb.append("-");
        }
        // mac[i] & 0xFF 是为了把byte转化为正整数
        String s = Integer.toHexString(mac[i] & 0xFF);
        sb.append(s.length() == 1 ? 0 + s : s);
    }
    // 把字符串所有小写字母改为大写成为正规的mac地址并返回
    return sb.toString().toUpperCase();
}

版权声明:本文为weixin_43468680原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。