开发者

How can i find the City name using IP address in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 2 years ago.

Improve this question

I want city name from IP address usi开发者_高级运维ng Java

is there any idea to do this ?


From Andrey link, here is how to construct the inquiry, this code will return an HTML file with all details of current IP, including city;

String IP= "123.123.123.123";
URL link = new URL("http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress="+IP);

BufferedReader in = new BufferedReader(new InputStreamReader(link.openStream()));
String inputLine;

while ((inputLine = in.readLine()) != null){
     System.out.println(inputLine);             
}

in.close();

UPDATE, 23 May 2013

The previous answer is ok, but it's not an API call, it reads an HTML page, that I provided previously because I didn't find any free APIs. Next is a REST API call that can be used easily and will return all the info required, it's recommended to use this one:

String ip = "2.51.255.200"; 
URL url = new URL("http://freegeoip.net/csv/" + ip);
connection = (HttpURLConnection) url.openConnection();
connection.connect();

InputStream is = connection.getInputStream();

int status = connection.getResponseCode();
if (status != 200) {
    return null;
}

reader = new BufferedReader(new InputStreamReader(is));
for (String line; (line = reader.readLine()) != null;) {
    //this API call will return something like:
    "2.51.255.200","AE","United Arab Emirates","03","Dubai","Dubai","","x-coord","y-coord","",""
    // you can extract whatever you want from it
}


If your Application is deployed behind the firewall. So instead of calling a API, we can use GeoLite below is the sample code.

Download City.dat file from http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

            File    datapath = new File("GeoLiteCity.dat");
            LookupService cl = new LookupService(datapath,
                    LookupService.GEOIP_MEMORY_CACHE
                            | LookupService.GEOIP_CHECK_CACHE);
            String cityName = cl.getLocation(ipAddress).city;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜