Java如何通过IP获得真实地址_C、空白格的博客-CSDN博客_java根据ip获取地址
一、获取访问IP这步很简单,但还是将代码贴出来吧,但是有一点需要注意,如果是nginx那种反向代理的,是获取不到客户端真实IP的,只能获取到nginx的代理IP,需要对nginx进行如下配置:
location / {
proxy_pass http://127.0.0.1:10678;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
/**
* description 获取客户端IP
*
* @param request
* @return java.lang.String
* @version 1.0
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 如果是多级代理,那么取第一个IP为客户端IP
if (ip != null && ip.indexOf(",") != -1) {
ip = ip.substring(0, ip.indexOf(",")).trim();
}
return ip;
}
二、获取到IP以后就需要查找真实地址了,大概分为以下几步:
1、首先引入maven依赖
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.6.0</version>
</dependency>
2、下载ip地址库:
下载地址:https://pan.baidu.com/s/1wwCUY6Ac8LF8984FgAkgvg
提取码:xm24
3、现有两种方法可以获取真实地址,第一种通过地址库查询,第二种通过ali的地域查询,这两种各有优缺点:
①地址库查询:查询比较快适合批量查询,但是有的ip查询不到。
②ali地域查询:大部分的ip都能查询到,但是查询很慢,适合单个查询。
我将两者整合了下,这样大部分的查询应该都是没问题的。
/**
* description 地址库查询
*
* @param ip 地址
* @return java.lang.String
* @version 1.0
*/
public static String getRealAddress(String ip) {
String result = "";
try {
// 加载地址库
ClassPathResource resource = new ClassPathResource("GeoLite2-City.mmdb");
DatabaseReader reader = new DatabaseReader.Builder(resource.getInputStream()).build();
InetAddress inetAddress = InetAddress.getByName(ip);
CityResponse response = reader.city(inetAddress);
// 获取所在国家
String country = response.getCountry().getNames().get("ja");
// 库内获取不到的IP,访问ali的地域查询
if (response.getSubdivisions().size() > 0) {
// 获取所在省份
String province = response.getSubdivisions().get(0).getNames().get("zh-CN");
// 获取所在城市
String city = response.getCity().getNames().get("zh-CN");
city = city == null ? "" : city;
result = country + province + city;
} else {
result = getAlibaba(ip);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* description ali地域查询
*
* @param ip ip地址
* @return java.lang.String
* @version 1.0
*/
public static String getAlibaba(String ip) {
Map map = new HashMap();
map.put("ip", ip);
map.put("accessKey", "alibaba-inc");
String result = HttpClientUtil.post("http://ip.taobao.com/outGetIpInfo", map);
Map valueMap = JSONObject.parseObject(result, Map.class);
// 请求成功,解析响应数据
if ("query success".equals(valueMap.get("msg"))) {
Map<String, String> dataMap = (Map<String, String>) valueMap.get("data");
String country = dataMap.get("country");
String region = dataMap.get("region");
String city = dataMap.get("city");
return country + region + city;
}
return "";
}
结果如下图:
把工具类贴下面了,需要的自己粘下
public static String post(String url, Map<String, String> mapParameter) {
log.debug("开始请求: url = {}, mapParameter = {}, charset = {}", url, mapParameter);
// 创建httpClient的默认实例
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建POST请求
HttpPost httpPost = new HttpPost(url);
// 设置参数
List<NameValuePair> nameValuePairList = new ArrayList<>();
// 迭代参数
if (mapParameter != null && mapParameter.size() > 0) {
mapParameter.forEach((k, v) -> nameValuePairList.add(new BasicNameValuePair(k, v)));
}
// 编码
if (nameValuePairList.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairList);
httpPost.setEntity(entity);
}
// 执行post请求
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
if (response != null) {
log.info("请求成功, 响应状态: {}", response.getStatusLine().getStatusCode());
HttpEntity httpEntity = response.getEntity();
// 如果返回的内容不为空
if (httpEntity != null) {
return EntityUtils.toString(httpEntity);
}
}
} catch (Exception e) {
log.error("请求异常: e = {}", e);
e.printStackTrace();
}
} catch (Exception e) {
log.error("请求异常: e = {}", e);
e.printStackTrace();
}
return null;
}