java获取登录ip和地址

//获取HttpServletRequest对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();

/**
* 获取登录用户的IP地址
*
* @param request HttpServletRequest
* @return String
*/
public static String getIpAddr(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.getRemoteAddr();
}
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip = "127.0.0.1";
}
if (ip.split(",").length > 1) {
ip = ip.split(",")[0];
}
return ip;
}

/**
* 通过IP获取地址
*
* @param ip http://freeapi.ipip.net/ip
* @return String
*/
public static String getIpInfo(String ip) {
if ("127.0.0.1".equals(ip)) {
ip = "127.0.0.1";
}
String info = "";
try {
URL url = new URL("http://freeapi.ipip.net/" + ip);
HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
htpcon.setRequestMethod("GET");
htpcon.setDoOutput(true);
htpcon.setDoInput(true);
htpcon.setUseCaches(false);
InputStream in = htpcon.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder temp = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
temp.append(line).append(" ");
line = bufferedReader.readLine();
}
bufferedReader.close();
JSONArray jsonArray = JSONObject.parseArray(temp.toString());
info = info + jsonArray.get(0) + jsonArray.get(1) + jsonArray.get(2) + jsonArray.get(3) + jsonArray.get(4);
} catch (IOException e) {
e.printStackTrace();
}
return info;
}
 

注意:http://freeapi.ipip.net/  该接口有多次后拒绝请求问题,不建议使用,可使用

ip2region      
http://whois.pconline.com.cn
原文地址:https://www.cnblogs.com/coderxiaobai/p/15125233.html