一. 公网ip获取
1. 引入文件:<script type="text/javascript" src="https://pv.sohu.com/cityjson?ie=utf-8"></script>
2. https://pv.sohu.com/cityjson?ie=utf-8 的运行结果是:
var returnCitySN = {"cip": "xx.xx.xx.xx", "cid": "xxxxxx", "cname": "xxxxxx"};
采用js获取:returnCitySN.cip
二. 本机或服务器ip获取
代码如下:
public static String getIpAddr(HttpServletRequest request) {
String ip = "";
if(null != request){
try{
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();
}
}catch(Exception e){
logger.error("Fail to get ip.", e);
}
}
return ip;
}