开发者

can I get Country name from clientIp?

// I get clientIp wi开发者_运维问答th 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜