简体   繁体   中英

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

I want city name from IP address using 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
}

Logan is right, geobytes is not accurate. It pointed me to a different city.

But, whatismyipaddress identified me accuratly. There seems to be a problem with geobytes.

Another alternative to some of the services already mentioned is my API, https://ipinfo.io . It returns geolocation and other information about an IP address:

$ curl ipinfo.io
{
  "ip": "24.6.61.239",
  "hostname": "c-24-6-61-239.hsd1.ca.comcast.net",
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "loc": "37.3845,-122.0881",
  "org": "AS7922 Comcast Cable Communications, LLC",
  "postal": "94040"
}

See https://ipinfo.io/developers for more details.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM