Java获取IP及归属地

最近我们发现各大社交平台都出现了一个新的功能:IP属地。

比如某乎:

这个IP属地是怎么做到的呢?今天我来教教你,保证你看完直呼Easy~

技术栈

1.Java网络编程

2.Servlet

具体实现

1.获取IP地址及其归属地工具类

package com.mmg.controller;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 获取IP地址工具类
 */
public class Iputil {

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

        //使用代理,则获取第一个IP地址
        if (ip == null) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    /**
     * 2.通过调用接口的方式获取IP
     */
    public static String getIp() {
        try {
            URL realUrl = new URL("http://whois.pconline.com.cn/ipJson.jsp");
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setUseCaches(false);
            conn.setReadTimeout(6000);
            conn.setConnectTimeout(6000);
            conn.setInstanceFollowRedirects(false);
            int code = conn.getResponseCode();
            StringBuilder sb = new StringBuilder();
            String ip = "";
            if (code == 200) {
                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                //控制台输出乱码,就指定编码为GBK即可。
                //BufferedReader reader = new BufferedReader(new InputStreamReader(in, "GBK"));
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                ip = sb.substring(sb.indexOf("ip") + 5, sb.indexOf("pro") - 3);
            }
            return ip;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 3.通过调用接口根据ip获取归属地
     */
    public static String getAddress(String ip) {
        try {
            URL realUrl = new URL("http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip + "&json=true");
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setUseCaches(false);
            conn.setReadTimeout(6000);
            conn.setConnectTimeout(6000);
            conn.setInstanceFollowRedirects(false);
            int code = conn.getResponseCode();
            StringBuilder sb = new StringBuilder();
            String ipaddr = "";
            if (code == 200) {
                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                ipaddr = ip + "=" + sb.substring(sb.indexOf("addr") + 7, sb.indexOf("regionNames") - 3);
            }
            return ipaddr;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

2.测试类

package com.mmg.controller;

/**
 * 测试类
 */
public class Test {
    public static void main(String[] args) {
        System.out.println(Iputil.getIpAddr());
        System.out.println(Iputil.getAddress(Iputil.getIp()));
    }
}

通过运行这个方法,可以看到,控制台打印了IP和城市信息,也就是我们想要的IP属地信息啦!

在你的项目里,你可以在登录的时候记录当前登录用户的IP和登录地点,也可以在用户发表文章和评论的时候显示出他的IP属地,非常实用哦~

感谢您的观看,如果对你有帮助的话,麻烦点个收藏把!

  • 10
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

木芒果呀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值