如何在Java中使用IP地址查找城市名称

时间:2010-03-18 11:31:31

标签: java location ip

我想使用Java从IP地址获取城市名称

有什么想法吗?

5 个答案:

答案 0 :(得分:7)

来自Andrey链接,以下是如何构建查询,此代码将返回一个HTML文件,其中包含当前IP的所有详细信息,包括城市;

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();

更新,2013年5月23日

之前的答案还可以,但它不是API调用,而是读取我之前提供的HTML页面,因为我没有找到任何免费的API。接下来是一个REST API调用,可以轻松使用并返回所需的所有信息,建议使用这个:

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
}

答案 1 :(得分:2)

答案 2 :(得分:2)

Logan是对的,geobytes不准确。它把我指向了一个不同的城市。

但是,whatismyipaddress确切地认出了我。 geobytes似乎有问题。

答案 3 :(得分:0)

已经提到的一些服务的另一种替代方案是我的API,https://ipinfo.io。它返回地理位置和有关IP地址的其他信息:

$ 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"
}

有关详细信息,请参阅https://ipinfo.io/developers

答案 4 :(得分:0)

如果您的应用程序部署在防火墙后面。因此,我们可以使用下面的GeoLite代替调用API,而不是示例代码。

http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

下载City.dat文件
            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;
相关问题