It’s pretty common the need for a web application to be able to detect the I.P. address of a client. The I.P. address could be used either for statistic or authentication purposes.
Knowing the IP address you could easily get information about the location of the client. Using Max Mind’s GeoIP Country and GeoIP City you can extract this information. Max Mind offers also a non-paying solution (which is less accurate though).
You can also use the IP address to block multiple logins with the same credentials. This could be useful for sites that offer content to users that have paid a subscription.
The code to do so is really easy, all you need to do is check a bunch of server variables. The good thing is that those variables are not platform specific, so an equivalent code could also work with PHP.
public static string GetCurrentIpAddress(HttpRequest request) { string ipAddress = ""; if (string.IsNullOrEmpty(ipAddress)) { ipAddress = request.ServerVariables["HTTP_CLIENT_IP"]; } if (string.IsNullOrEmpty(ipAddress)) { ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } if (string.IsNullOrEmpty(ipAddress)) { ipAddress = request.ServerVariables["HTTP_X_FORWARDED"]; } if (string.IsNullOrEmpty(ipAddress)) { ipAddress = request.ServerVariables["HTTP_X_REAL_IP"]; } if (string.IsNullOrEmpty(ipAddress)) { ipAddress = request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"]; } if (string.IsNullOrEmpty(ipAddress)) { ipAddress = request.ServerVariables["HTTP_FORWARDED_FOR"]; } if (string.IsNullOrEmpty(ipAddress)) { ipAddress = request.ServerVariables["HTTP_FORWARDED"]; } if (string.IsNullOrEmpty(ipAddress)) { ipAddress = request.ServerVariables["REMOTE_ADDR"]; } return ipAddress; }
Sometimes though we do not have the actual IP address but we have the host name of the ISP provider of the client. The host name can be easily resolved into an IP address easily. Using the System.Net.Dns.GetHostEntry function we get a list of all the IP addresses this hostname resolves to.
public static string GetIp(string HostName) { try { System.Net.IPHostEntry ips; ips = System.Net.Dns.GetHostEntry(HostName); return ips.AddressList[1].ToString(); } catch (Exception ex) { // Handle the error } }
Finally, although this approach works much better than just looking at REMOTE_ADDR, still itβs far from a full proof solution, simply because it relies on the HTTP header information which can be easily manipulated.
Leave a Reply