通过客户端发送请求到服务端,在服务端获取客户端IP,转入 request 头信息:
服务端获取:
package com.chinadatapay.util;
/**
* 获取客户端IP
* @author Cloud
*
*/
public class RemoteHostUtil {
public static String getRemoteHost(javax.servlet.http.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();
}
return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;//最后用三元表达式判断是否是本地IP;
}
}
通过JS获取:
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script type="text/javascript">
document.write(returnCitySN["cip"]+','+returnCitySN["cname"]);
</script>
更多使用Js脚本方式获取IP请查阅:
http://www.jb51.net/article/52484.htm