前段时间在我做一项目是遇到这样一个问题,Server要获取客户端IP,直接在Server上获取不到客户端真实IP,要解决这一问题,本人在网上查了一翻,有好多说了好多的方法,但是我试了不知怎么都不成功,所以本人就用了这样一套方法。就是用其他可以获取到IP的Server代替解决,
1、在代替Server上放一个获取IP的文件,如叫getIP.jsp
内容如下:
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<%
String ip="";
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();
}
%>
window.getIp= function (){
return("<%=ip%>");
}
2、在本地Server上只须获得这个js方法的返回值,然后再用ajax传递到需要处理该值的地方即可。
内容如下:
<script language="javascript" src="http://192.168.0.4/getIP.jsp"></script>
<script type="text/javascript">
var strIp;
strIp=window.getIp();
checkUser(strIp);
var xmlHttp;
function createXMLHttpRequest()
{
if(window.ActiveXObject) //IE
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest) //Other Explorers
{
xmlHttp=new XMLHttpRequest();
}
}
function checkUser(strIp)
{
createXMLHttpRequest();
xmlHttp.open("post","save.jsp?getIp="+strIp+",true);
xmlHttp.send();
}
</script>
测试输出
save.jsp:
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<%
String ip="";
ip=getParameter("getIp");
System.out.println("您的IP是:"+ip);
%>
1、在代替Server上放一个获取IP的文件,如叫getIP.jsp
内容如下:
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<%
String ip="";
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();
}
%>
window.getIp= function (){
return("<%=ip%>");
}
2、在本地Server上只须获得这个js方法的返回值,然后再用ajax传递到需要处理该值的地方即可。
内容如下:
<script language="javascript" src="http://192.168.0.4/getIP.jsp"></script>
<script type="text/javascript">
var strIp;
strIp=window.getIp();
checkUser(strIp);
var xmlHttp;
function createXMLHttpRequest()
{
if(window.ActiveXObject) //IE
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest) //Other Explorers
{
xmlHttp=new XMLHttpRequest();
}
}
function checkUser(strIp)
{
createXMLHttpRequest();
xmlHttp.open("post","save.jsp?getIp="+strIp+",true);
xmlHttp.send();
}
</script>
测试输出
save.jsp:
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<%
String ip="";
ip=getParameter("getIp");
System.out.println("您的IP是:"+ip);
%>