Sunday, January 30, 2011

How to get client's IP Address in Load Balanced Environment


public static string GetIPAddress(NameValueCollection serverVariables)
{
var ip = serverVariables["HTTP_X_FORWARDED_FOR"];

if (!string.IsNullOrEmpty(ip))
{
string[] ipRange = ip.Split(',');

if (null != ipRange && ipRange.Length > 0)
{
int le = ipRange.Length - 1;
string trueIP = ipRange[le];
ip = trueIP;
}
else
{
ip = serverVariables["REMOTE_ADDR"];
}
}
else
{
ip = serverVariables["REMOTE_ADDR"];
}

return ip;

}

Ex: string userIPAddress = GetIPAddress(Request.ServerVariables);

No comments:

Post a Comment