/** * @author xichao.dong * @email 406592176@qq.com * @date 2014-8-15 上午8:50:38 * @company (开发公司) 珠海市冰川软件有限公司 * @copyright (版权) 本文件归属珠海市冰川软件有限公司所有 * @version V1.0 * @modify (修改) : 2014-8-15 上午8:50:38 xichao.dong * @Review (审核人) :xichao.dong */ package com.glacier.basic.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import javax.servlet.http.HttpServletRequest; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; /** * @ClassName: IpUtil * @Description: TODO(IP获取器) * @author xichao.dong * @email 406592176@qq.com * @date 2014-8-15 上午11:15:40 */ public class IpUtil { /** * 获取登录用户的IP地址 * * @param request * @return */ 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 (ip.split(",").length > 1) { ip = ip.split(",")[0]; } return ip; } /** * 通过IP获取地址(需要联网,调用淘宝的IP库) * * @param ip * @return */ public static String getIpInfo(String ip) { String info = "["; if (ip.equals("0:0:0:0:0:0:0:1") || ip.equals("127.0.0.1")) { return "[本地]"; } try { URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + 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)); StringBuffer temp = new StringBuffer(); String line = bufferedReader.readLine(); while (line != null) { temp.append(line).append("\r\n"); line = bufferedReader.readLine(); } bufferedReader.close(); JSONObject obj = (JSONObject) JSON.parse(temp.toString()); if (obj.getIntValue("code") == 0) { JSONObject data = obj.getJSONObject("data"); info += data.getString("country") + " "; info += data.getString("region") + " "; info += data.getString("city") + " "; info += data.getString("isp"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return info += "]"; } }