extract real ip from operamini .net c#

by nolovelust 19. February 2010 15:27

Function set below extracts real ip from operamini HTTP_X_FORWARDED_FOR headers.

public static string GetOperaMiniIp(HttpRequest hr)
{
string ip = hr.ServerVariables["REMOTE_ADDR"];
string visitorBrowser = hr.ServerVariables["HTTP_USER_AGENT"];
string forwardedip = hr.ServerVariables["HTTP_X_FORWARDED_FOR"];
try
{
if (visitorBrowser.ToLower().Contains("mini"))
{
if (forwardedip != null)
{
string[] forwardedipArray = forwardedip.Split(new char[] { ',' });

//last ip in the array is the real ip
 //http://dev.opera.com/articles/view/opera-mini-request-headers/


string extractedIp = forwardedipArray[forwardedipArray.Length - 1].ToString().Trim();
if (IsValidIP(extractedIp) == true && IsIpLocalIP(extractedIp) == false)
{
ip= extractedIp;
}
}

}
return ip;
}
catch
{
return ip;
}
}
public static bool IsValidIP(string addr)
{
string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$";
System.Text.RegularExpressions.Regex check = new System.Text.RegularExpressions.Regex(pattern);
bool valid = false;
if (addr == "")
{
valid = false;
}
else
{
valid = check.IsMatch(addr, 0);
}
return valid;
}
public static bool IsIpLocalIP(string ip)
{
if (ip.StartsWith("10.") ||
ip.StartsWith("174.") ||
ip.StartsWith("192.168") ||
ip.StartsWith("172.") ||
ip.StartsWith("127.") ||
ip.StartsWith("97.")
)
{
return true;
}
else
{
return false;
}
}

Tags:

ASP.NET | Mobile web | Open Source

Add comment

  Country flag

biuquote
Loading

Adverts

Welcome

Tag cloud

Month List