Drupal - How to get ip address?
In a situation where you use the IP address for security you should be aware of your infrastructure.
If you are using a proxy between your web server and your clients that sets the header, you should be able to trust the last address. Then you use the code like Muhammed suggested with an update to always get the last IP address from the forward header (See code below)
If you do not use a proxy, beware that the X-Forwarded-For header is very easy to spoof. I suggest you ignore it then unless you have a clear reason why not to.
I updated Muhammed Akhtar's code as follows to allow you to choose:
public string GetIP(bool CheckForward = false)
{
string ip = null;
if (CheckForward) {
ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
if (string.IsNullOrEmpty(ip)) {
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
} else { // Using X-Forwarded-For last address
ip = ip.Split(',')
.Last()
.Trim();
}
return ip;
}
This Wikipedia article explains the risks more thoroughly.
HTTP_X_FORWARDED_FOR should be used BUT it can return multiple IP addresses separated by a comma. See this page.
So you should always check it. I personally use the Split function.
public static String GetIPAddress()
{
String ip =
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
else
ip = ip.Split(',')[0];
return ip;
}
You can use this method to get the IP address of the client machine.
public static String GetIP()
{
String ip =
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
{
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
return ip;
}