大家好:
我实现了一个网页,是动态的.对外暴露的是rest接口.当浏览器调用rest接口时,在rest里面实现了动态构造网页.
请问我如何得到访问过这个rest接口的ip地址呢?急!
请高人指点,谢谢.
Request.ServerVariables["remote_addr"]
加载动态网页的区域引入js就行,js中用于统计曝光点击及点击的地址
获取地址的话,java版代码如下:
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();
}
//若经过nginx等转发后就变成多个地址,取最开始的地址
if (ip.indexOf(",") > -1) {
String[] sip = ip.split(",");
for (int i = 0; i < sip.length; i ++ ){
if (sip[i] != null && sip[i].length() > 0 && !"unknown".equalsIgnoreCase(sip[i])) {
ip = sip[i];
break;
}
}
}
不管是什么访问,不外乎是一次http请求,解析请求的header中的ip和代理ip即可。
我来给个C#版的
public string GetIP()
{
string ip = "";
try
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
// 使用了代理,返回真实客户端IP
ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
// 取不到客户端IP,返回代理IP
ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
if (string.IsNullOrEmpty(ip) || ip == "::1" || ip == "127.0.0.1")
{
ip = System.Web.HttpContext.Current.Request.UserHostAddress;
}
if (string.IsNullOrEmpty(ip) || ip == "::1" || ip == "127.0.0.1")
{
ip = "";
}
}
catch (Exception ex)
{
ip = System.Web.HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(ip) || ip == "::1" || ip == "127.0.0.1")
{
ip = "";
}
}
return ip;
}