获取客户端IP
时间:2011-03-14 来源:第7笔画
/// <summary> ......
/// <summary>
/// 获取当前请求的IP地址
/// </summary>
/// <returns></returns>
public static string GetIP()
{
HttpRequest request = HttpContext.Current.Request;
string ipAddress=string.Empty;
if(request.ServerVariables["HTTP_X_FORWARDED_FOR"]==null || request.ServerVariables["HTTP_X_FORWARDED_FOR"]=="") //使用了代理服务器
{
ipAddress = request.ServerVariables["REMOTE_ADDR"]; //没使用代理服务器,直接获取
}
else if(request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",")>=0)
{
int index = request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",");
ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(0,index-1);
}
else if(request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";")>=0)
{
int index = request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";");
ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(0,index-1);
}
else
{
ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
return ipAddress;
}