Java获取IP归属地

目录

前言

获取IP地址

Nginx 反向代理问题

IP获取归属地

通过归属地API获取

通过地址库获取


 

前言

前几个月微信公众号上线了IP归属地的功能,后续知乎、抖音等平台纷纷添加了该功能。如果是国内的用户精确到省份,国外用户精确到国家。本文就使用Java实现获取IP归属地

主要讲解几个步骤:

  • Java获取请求IP
  • 解决Nginx转发问题
  • 通过IP地址获取归属地

获取IP地址

首先使用基于Spring Boot搭建项目,在controller添加HttpServletRequest请求参数:

@RestController
public class IpController {
    @GetMapping("/ip-address")
    public String ipAddress(HttpServletRequest request)  {
        // 接收request  
    }
}

 通过HttpServletRequest获取IP地址

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();
}
return ip;

在本地环境调用获取IP,要么是0:0:0:0:0:0:0:1,或者是局域网IP

局域网IP是以192.168.x.x开头,或者是127.0.0.1IP

所以需要部署到外网服务器才能获取到公网地址。部署到外网服务器能成功获取IP地址。

Nginx 反向代理问题

直接访问公网服务器地址能成功获取IP地址,但是通过Nginx反向代理获取的都是127.0.0.1。客户端请求Nginx服务器再反向代理转发到服务端,此时拿到的IP反向代理的IP,也就是Nginx服务器的IP,并不是真正的客户端IP

Nginx的配置文件中的location模块添加以下配置,将客户端的IP传入到Nginx服务:

proxy_set_header        X-Real-IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

示例:

server {  
    listen 80;  
    server_name localhost;  
    location / { 
         proxy_set_header        X-Real-IP       $remote_addr;
         proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_pass http://xxxx;
    }

完成以上操作之后,就能成功获取到IP了。然后通过IP获取归属地了。

IP获取归属地

通过IP获取归属地一般都从地址库找到匹配的地址,本文介绍两种方法.

通过归属地API获取

需要发起http请求,这里使用Spring BootRestTemplate发起http请求,首先创建RestTemplatebean实例:

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

再调用RestTemplate发起http请求:

private String URL = "https://api.beijinxuetang.com/api/common/ip";
JSONObject jsonObject = new JSONObject();
jsonObject.put("ip",ip);
JSONObject json = restTemplate.postForObject(URL,jsonObject, JSONObject.class);
if (json.getInteger("code") == 0) {
    json = json.getJSONObject("data");
    // 国家
    String nation = json.getString("nation");
    // 省份
    String province = json.getString("province");
    // 市
    String city = json.getString("city");
}

上面的json是引入fastjson

通过地址库获取

使用API接口,可能会出现服务挂了,或者服务地址不提供服务了等问题。而采用本地地址库就没有这些问题。

本文采用离线IP地址定位库 Ip2region ,Ip2region是一个离线IP地址定位库,微秒的查询时间:

首先找到地址库ip2region.xdb,具体路径为data/ip2region.xdb

ip2region.xdb放在项目的resources目录下:

 

引入maven依赖:

<dependency>
			<groupId>org.lionsoul</groupId>
			<artifactId>ip2region</artifactId>
			<version>2.6.5</version>
		</dependency>

获取归属地:

private Searcher searcher;

@Override
    public String getIpAddress(String ip){
        if ("127.0.0.1".equals(ip) || ip.startsWith("192.168")) {
            return "局域网 ip";
        }
        if (searcher == null) {
            try {
                File file = ResourceUtils.getFile("classpath:ipdb/ip2region.xdb");
                String dbPath = file.getPath();
                searcher = Searcher.newWithFileOnly(dbPath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String region = null;
        String errorMessage = null;
        try {
            region = searcher.search(ip);
        } catch (Exception e) {
            errorMessage = e.getMessage();
            if (errorMessage != null && errorMessage.length() > 256) {
                errorMessage = errorMessage.substring(0,256);
            }
            e.printStackTrace();
        }
        // 输出 region
    }

 获取region就能获取到IP归属地了。例如中国|0|四川省|德阳市|电信

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java 中,我们可以使用第三方库来获取 IP归属地信息。其中一个常用的库是 GeoIP2,它基于 MaxMind 的 GeoIP2 数据库。 首先,需要将 GeoIP2 库添加到项目中。可以在 Maven 或 Gradle 构建脚本中添加相应的依赖项。 然后,我们可以使用 GeoIP2 提供的 API查询 IP归属地。以下是一个示例代码: ```java import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.record.Country; import java.io.File; import java.io.IOException; import java.net.InetAddress; public class IPUtils { public static String getIPCountry(String ip) { try { File database = new File("GeoIP2-City.mmdb"); DatabaseReader reader = new DatabaseReader.Builder(database).build(); InetAddress ipAddress = InetAddress.getByName(ip); CityResponse response = reader.city(ipAddress); Country country = response.getCountry(); return country.getName(); } catch (IOException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { String ip = "123.456.789.0"; String country = getIPCountry(ip); System.out.println("IP " + ip + " 的归属地是:" + country); } } ``` 在上述示例中,我们通过 `getIPCountry` 方法传入一个 IP 地址,并在 `main` 方法中调用该方法来获取IP归属地信息。具体的归属地信息包括国家、地区、城市等,可以根据需要进行扩展和处理。 需要注意的是,在运行代码之前,我们需要下载并导入 GeoIP2 数据库文件 `GeoIP2-City.mmdb`,该文件包含了 IP 地址和归属地信息的映射关系。可以从 MaxMind 的官网或其他数据源获取该文件。 这样,我们就可以通过 Java获取 IP归属地信息了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雾里有果橙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值