网络请求错误排查

pexels-song-kaiyue-5835215.jpg

介绍:

在某些场景下,会莫名其妙的碰到一些陌生的请求访问我们的服务,对我们造成一定的困扰,我们需要想办法去定位这些请求的原始信息。

解决方案:

  • 利用IpUtil工具类获取源IP地址:
public static String getIpAddr(HttpServletRequest request) {
    String ipAddress = null;
    try {
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
            // = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
    } catch (Exception e) {
        ipAddress = "";
    }
    // ipAddress = this.getRequest().getRemoteAddr();

    return ipAddress;
}

先看看这些IP是不是自己公司运维在做一些监控、心跳等操作导致的。

  • 如果是外来攻击或者其他,可以利用tcpdump命令+Wireshark:
    例子:tcpdump -tttt -s0 -X -vv tcp port 8080 -w captcha.cap
-tttt 输出最大程度可读的时间戳
-s0 指定每一个包捕获的长度,单位是byte,使用-s0可以捕获整个包的内容
-X 以hex和ASCII两种形式显示包的内容
-vv 显示更加多的包信息
tcp 指我们只捕获tcp流量
port 8080 指我们只捕获端口8080的流量
-w captcha.cap 指定捕获的流量结果输出到captcha.cap文件,便于分析使用

在这个过程中,所有访问 8080 端口的 TCP 流量都会被捕获。当请求结束之后,我们可以使用 Ctrl+C 中断该命令的执行,这时候在当前目录下就可以看到生成了一个名为 captcha.cap 的文件。

接下来我们从服务器上下载这个captcha.cap文件到自己电脑上,使用 Wireshark 打开。
scp account@ip:/path/to/captcha.cap
过滤条件:http and ip.src == 192.168.0.65
右键 Follow - HTTP Stream

参考:
https://segmentfault.com/a/1190000015648433</u>
https://github.com/mylxsw/growing-up/blob/master/doc/tcpdump%E7%AE%80%E6%98%8E%E6%95%99%E7%A8%8B.md</u>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容