Java服务端获取IP及归属地查询

2022-12-03 12:51:18 浏览数 (1)

获取请求的IP

代码语言:javascript复制
public String getIp(HttpServletRequest request){
  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("WL-Proxy-Client-IP");
  }
  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("HTTP_CLIENT_IP");
  }
  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("HTTP_X_FORWARDED_FOR");
  }
  if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getRemoteAddr();
  }
  if(ip == null){
    return "";
  }
  String[] ipArr = ip.split(",");
  if(ipArr.length>0){
    return ipArr[0];
  }else{
    return "";
  }
}

如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?

答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。

如:

X-Forwarded-For:192.168.1.110,192.168.1.120, 192.168.1.130,192.168.1.100 用户真实IP为:192.168.1.110

获取IP的归属地

添加依赖

代码语言:javascript复制
<dependencies>
  <dependency>
    <groupId>org.lionsoul</groupId>
    <artifactId>ip2region</artifactId>
    <version>2.6.6</version>
  </dependency>
</dependencies>

示例代码

代码语言:javascript复制
import org.lionsoul.ip2region.xdb.Searcher;
import java.io.*;
import java.util.concurrent.TimeUnit;

public class SearcherTest {
    public static void main(String[] args) {
        // 1、创建 searcher 对象
        String dbPath = "D:\Project\java\data\ip2region.xdb";
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(dbPath);
        } catch (IOException e) {
            System.out.printf("failed to create searcher with `%s`: %sn", dbPath, e);
            return;
        }

        // 2、查询
        String ip = "223.5.5.5";
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
            System.out.printf("{region: %s, ioCount: %d, took: %d μs}n", region, searcher.getIOCount(), cost);
        } catch (Exception e) {
            System.out.printf("failed to search(%s): %sn", ip, e);
        }

        // 3、关闭资源
        try {
            searcher.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 备注:并发使用,每个线程需要创建一个独立的 searcher 对象单独使用。
    }
}

其中ip2region.xdb下载地址

链接:https://pan.baidu.com/s/1Uc_2kB0lFpH9rlCOQOvh0w 提取码:psvm

0 人点赞