All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.fosin.cdp.util.ClientUtil Maven / Gradle / Ivy

package com.github.fosin.cdp.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ClientUtil class.
 *
 * @author 28860823
 * @version $Id: $
 */
@Slf4j
public class ClientUtil {

    /** Constant ERROR_IP="127.0.0.1" */
    public final static String ERROR_IP = "127.0.0.1";

    /** Constant PATTERN */
    public final static Pattern PATTERN = Pattern.
            compile("(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})");

    /**
     * 得到客户端真实IP地址
     * 举例说明;
     * request.getRemoteAddr() 192.168.239.196
     * request.getHeader("X-Forwarded-For") 58.63.227.162, 192.168.237.178, 192.168.238.218
     * request.getHeader("X-Real-IP") 192.168.238.218
     * 所以访问的流程应该是这样,客户端58.63.227.162发出请求,经过192.168.237.178, 192.168.238.218两层转发,
     * 到了192.168.239.196这台NGINX上,NGINX就把X-Real-IP头设成了自己看到的remote_addr,也就是直接发给到他的
     * 192.168.238.218,这时候resin收到这个包,对resin来说直接发给他的remote_addr就是NGINX的ip,也就是192.168.239.196,
     * 那么resin里面的request.getRemoteAddr()就是192.168.239.196,那么在resin里拿最原始的ip逻辑
     * (也就是拿能够知道的最外层的ip)应该是这样:
     *
     * 如果XFF不为空,拿XFF的左边第一个
     *
     * 如果XFF为空,拿XRI
     *
     * 如果XRI为空,只能拿request.getRemoteAddr(),也就是只能拿到最直接发给他的机器ip了,
     *
     * @param request HttpServletRequest
     * @return 客户端的一个IP
     */
    public static String getClientOneIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        //优先从XFF中取
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值,第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        //其次从XRP中取
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        //最后从getRemoteAddr取
        return request.getRemoteAddr();
    }

    /**
     * 取外网IP
     *
     * @param request HttpServletRequest
     * @return 客户端远程IP
     */
    public static String getRemoteIp(HttpServletRequest request) {
        String ip = request.getHeader("x-real-ip");
        if (ip == null) {
            ip = request.getRemoteAddr();
        }

        //过滤反向代理的ip
        String[] stemps = ip.split(",");
        if (stemps.length >= 1) {
            //得到第一个IP,即客户端真实IP
            ip = stemps[0];
        }

        ip = ip.trim();
        if (ip.length() > 23) {
            ip = ip.substring(0, 23);
        }

        return ip;
    }

    /**
     * getLastIpSegment
     *
     * @param request a {@link javax.servlet.http.HttpServletRequest} object.
     * @return a {@link java.lang.String} object.
     */
    public static String getLastIpSegment(HttpServletRequest request) {
        String ip = getClientOneIp(request);
        if (ip != null) {
            ip = ip.substring(ip.lastIndexOf('.') + 1);
        } else {
            ip = "0";
        }
        return ip;
    }

    /**
     * isValidIP
     *
     * @param request a {@link javax.servlet.http.HttpServletRequest} object.
     * @return a boolean.
     */
    public static boolean isValidIP(HttpServletRequest request) {
        String ip = getClientOneIp(request);
        return isValidIP(ip);
    }

    /**
     * 判断我们获取的ip是否是一个符合规则ip
     *
     * @param ip ip地址
     * @return boolean
     */
    public static boolean isValidIP(String ip) {
        if (StringUtils.isEmpty(ip)) {
            log.debug("ip is null. valid result is false");
            return false;
        }

        Matcher matcher = PATTERN.matcher(ip);
        boolean isValid = matcher.matches();
        log.debug("valid ip:" + ip + " result is: " + isValid);
        return isValid;
    }

    /**
     * getLastServerIpSegment
     *
     * @return a {@link java.lang.String} object.
     */
    public static String getLastServerIpSegment() {
        String ip = getServerIP();
        if (ip != null) {
            ip = ip.substring(ip.lastIndexOf('.') + 1);
        } else {
            ip = "0";
        }
        return ip;
    }

    /**
     * getServerIP
     *
     * @return a {@link java.lang.String} object.
     */
    public static String getServerIP() {
        InetAddress inet;
        try {
            inet = InetAddress.getLocalHost();
            return inet.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "127.0.0.1";
    }

    /**
     * 获取mac地址
     *
     * @param ip ip地址
     * @return mac地址
     */
    public static String getMacAddress(String ip) {
        String line;
        String macAddress = "";
        final String macAddressPrefix = "MAC";
        final String loopbackAddress = "127.0.0.1 0:0:0:0:0:0:0:1";

        try {
            //如果为127.0.0.1,则获取本地MAC地址。
            if (loopbackAddress.contains(ip)) {
                InetAddress inetAddress = InetAddress.getLocalHost();
                //貌似此方法需要JDK1.6。
                NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress);
                byte[] mac = networkInterface.getHardwareAddress();
                if (mac == null) {
                    return ip;
                }

                //下面代码是把mac地址拼装成String
                StringBuilder sb = new StringBuilder();
                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地址并返回
                macAddress = sb.toString().trim().toUpperCase();
                return macAddress;
            }
            //获取非本地IP的MAC地址
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
            InputStreamReader isr = new InputStreamReader(p.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                int index = line.indexOf(macAddressPrefix);
                if (index != -1) {
                    index = line.indexOf("=");
                    macAddress = line.substring(index + 1).trim().toUpperCase();
                }
            }
            br.close();
        } catch (IOException e) {
            log.info("get mac address error, ip: " + ip);
            return "";
        }
        return macAddress;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy