IP获取归属地区(免费)

IP获取归属地区

使用 http://whois.pconline.com.cn/ipJson.jsp 这个 URL 来获取 IP 地址的归属城市信息

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IpAddressUtils {
    private static final Logger log = LoggerFactory.getLogger(IpAddressUtils.class);

    /**
     * 获取当前网络ip
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String 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") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("Error occurred when getIpAddr method was invoked.ex:", e);
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


    /**
     * IP获取归属地区
     * @param ipAddress
     * @return
     */
    public static String getAddress(String ipAddress) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String address = null;
        try {
            // 创建 HttpClient 实例
            httpClient = HttpClients.createDefault();

            // 构建 API 请求 URL
            String apiUrl = "http://whois.pconline.com.cn/ipJson.jsp?ip=" + ipAddress;

            // 创建 HttpGet 请求
            HttpGet httpGet = new HttpGet(apiUrl);

            // 发送请求并获取响应
            response = httpClient.execute(httpGet);

            // 解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String jsonResponse = EntityUtils.toString(response.getEntity(), "GBK");
                address = jsonResponse.substring(jsonResponse.indexOf("addr") + 7, jsonResponse.indexOf("regionNames") - 3);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(httpClient, response);
            return address;
        }
    }


    public static void close(CloseableHttpClient httpClient, CloseableHttpResponse response) {
        try {
            if (Objects.nonNull(response)) {
                response.close();
            }
            if(Objects.nonNull(httpClient)){
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 7
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
在 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归属地信息了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

工程师小A

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

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

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

打赏作者

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

抵扣说明:

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

余额充值