我可以从 clientIp 获取国家/地区名称吗?

发布于 2024-11-27 10:30:25 字数 312 浏览 0 评论 0 原文

// I get clientIp with below statement.
request.setAttribute("clientIp", clientIp);

// I use below statement to see clientIp on JSP page.
<%=response.encodeURL((String)request.getAttribute("clientIp")) %>

我想知道我还可以显示 clientIP 中的国家/地区名称吗?

例如:10.2.3.4 美国 10.4.5.3 英格兰

// I get clientIp with below statement.
request.setAttribute("clientIp", clientIp);

// I use below statement to see clientIp on JSP page.
<%=response.encodeURL((String)request.getAttribute("clientIp")) %>

I wonder can I also show Country name from clientIP?

Like: 10.2.3.4 U.S.A 10.4.5.3 England

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我很坚强 2024-12-04 10:30:25

如果您想通过 Java 完成这一切,您需要下载 IP 数据库,这是一个将 IP 映射到国家/地区代码的平面文件。

谷歌一下,你会发现有一些免费的,但它们可能不是完全最新的。

它可能看起来像这样:

"16777216","33554431","AU","AUS","AUSTRALIA"
"50331648","69956103","US","USA","UNITED STATES"
"69956104","69956111","BM","BMU","BERMUDA"
"69956112","72349055","US","USA","UNITED STATES"

下载后,您需要将其加载到数据库中,例如 SQLLite,以便您可以对其执行查找:

public String getCountryCode(String host) throws Exception {
    InetAddress addr = InetAddress.getByName(host);
    Long ipNum = ipToInt(addr.getHostAddress());

    Statement smt = conn.createStatement();
    ResultSet rs = smt.executeQuery("SELECT COUNTRY_CODE3 FROM ip_range WHERE IP_FROM <= "+ipNum+" and IP_TO >= "+ipNum);
    if (rs.next())
        return rs.getString(1);

    return null;
}

或者,还有各种 网络服务是免费的,仅限日常使用,可以为您完成繁重的工作,而且可能会更新。

If you want to do it all from Java you'll need to download an IP database, a flat file that maps IP to CountryCode.

Google around and you'll see that there are a few free ones, but they may not be totally up to date.

It will probably look something like this:

"16777216","33554431","AU","AUS","AUSTRALIA"
"50331648","69956103","US","USA","UNITED STATES"
"69956104","69956111","BM","BMU","BERMUDA"
"69956112","72349055","US","USA","UNITED STATES"

Once downloaded you'll want to load it into a database, e.g SQLLite so you can perform lookups on it:

public String getCountryCode(String host) throws Exception {
    InetAddress addr = InetAddress.getByName(host);
    Long ipNum = ipToInt(addr.getHostAddress());

    Statement smt = conn.createStatement();
    ResultSet rs = smt.executeQuery("SELECT COUNTRY_CODE3 FROM ip_range WHERE IP_FROM <= "+ipNum+" and IP_TO >= "+ipNum);
    if (rs.next())
        return rs.getString(1);

    return null;
}

Alternatively there are various web services that are free for limited daily usage that will do the hard-work for you and probably be more up to date.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文