Java无网查看请求源信息

Java没网络查看请求原归属地及其它信息。

直接上代码,复制即可

package com.facility.utils;

import cn.hutool.core.io.IoUtil;
import com.facility.constants.ScalesConstants;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.concurrent.CompletableFuture;

@Slf4j
public class IpUtil {

    private static final String LOCAL_IP = "127.0.0.1";


    public static void getRequestMsg(HttpServletRequest request, UserAgent userAgent, String method, String requestURI, String param) {
        String clientType = userAgent.getOperatingSystem().getDeviceType().toString();
//                        log.info("客户端类型 = " + clientType);   //客户端类型  手机、电脑、平板
        String os = userAgent.getOperatingSystem().getName();
//                        log.info("操作系统类型 = " + os);    //操作系统类型
        String browser = userAgent.getBrowser().toString();
//                        log.info("浏览器类型 = " + browser);    //浏览器类型
        String ip = getIpAddr(request);
        String address = getCityInfo(ip);
        String msg = "\n" +
                "客户端类型: " + clientType + "\n" +
                "操作系统类型: " + os + "\n" +
                "浏览器类型: " + browser + "\n" +
                "归属地: " + address + "\n" +
                "ip: " + ip + "\n" +
                "请求方式: " + method + "\n" +
                "路径: " + requestURI + "\n" +
                "参数: " + param;
        if (address.contains("江苏省") || address.contains("内网") || address.contains("中国移动") || "101.226.103.15".equals(ip)) {
            log.info("\n--------------------------------------------------------------------------------------------------------------------------------" +
                    "\n" + msg);
        } else {
            log.error("\n--------------------------------------------------------------------------------------------------------------------------------" +
                    "\n" + msg);
            log.error(String.valueOf(request));
            log.error(ip);
        }
    }

    /**
     * 获取IP地址
     * <p>
     * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String 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("X-Forwarded-For");
        }
        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.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return "0:0:0:0:0:0:0:1".equals(ip) ? LOCAL_IP : ip;
    }


    /**
     * 获取ip属地
     *
     * @param ip
     * @return
     * @throws Exception
     */
    public static String getCityInfo(String ip) {
        if (!Util.isIpAddress(ip)) {
            try {
                ip = ip.split(",")[0];
            } catch (Exception e) {
                log.error("Error: Invalid ip address"+ip);
            }
        }
        //查询算法
//        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
//        int algorithm = DbSearcher.BINARY_ALGORITHM; //Binary
        int algorithm = DbSearcher.MEMORY_ALGORITYM; //Memory
        try {
            if (ScalesConstants.DB_BIN_STR.length == 0) {
                InputStream inputStream = IpUtil.class.getClassLoader().getResourceAsStream("static/ip2region.db");
                ScalesConstants.DB_BIN_STR = IoUtil.readBytes(inputStream);
                inputStream.close();
            }


            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, ScalesConstants.DB_BIN_STR);
            DataBlock dataBlock;

            switch (algorithm) {
                case DbSearcher.BTREE_ALGORITHM:
                    dataBlock = searcher.btreeSearch(ip);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    dataBlock = searcher.binarySearch(ip);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    dataBlock = searcher.memorySearch(ip);
                    break;
                default:
                    log.error("未传入正确的查询算法");
                    return "";
            }

            String ipInfo = dataBlock.getRegion();

            if (!StringUtils.isEmpty(ipInfo)) {
                ipInfo = ipInfo.replace("|0", "");
                ipInfo = ipInfo.replace("0|", "");
                ipInfo = ipInfo.replace("中国|", "");
                ipInfo = ipInfo.replace("内网IP|", "");
            }
            return ipInfo;
        } catch (Exception e) {
            log.error("归属地获取失败:" + ip);
            e.printStackTrace();
            return "归属地获取失败";
        }
    }

    public static String parameterLog(HttpServletRequest request, RequestWrapper requestWrapper) {

        try {

            StringBuilder getPara = new StringBuilder("?");

            Enumeration enu = request.getParameterNames();
            while (enu.hasMoreElements()) {
                String paraName = (String) enu.nextElement();
                String par = paraName + "=" + request.getParameter(paraName);
                if ("?".equals(getPara.toString())) {
                    getPara.append(par);
                } else {
                    getPara.append("&").append(par);
                }
            }

            String requestBody = requestWrapper.getRequestBody();
            StringBuilder logMessage = new StringBuilder();
            if ("?".equals(getPara.toString())) {
                logMessage.append(requestBody);
            } else {
                logMessage.append(getPara);
            }

            return logMessage.toString();

        } catch (IOException e) {
            log.error("记录error出错:" + e.getMessage());
            e.printStackTrace();
        }
        return "";
    }
}

ip2region.db下载地址

提取码: b7qc

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值