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.
Function ClientIpAddress(ByVal myRequest As HttpRequest) Dim myIP As String = "" If (myIP = "") Then myIP = myRequest.ServerVariables("HTTP_CLIENT_IP") If (myIP = "") Then myIP = myRequest.ServerVariables("HTTP_X_FORWARDED_FOR") If (myIP = "") Then myIP = myRequest.ServerVariables("HTTP_X_FORWARDED") If (myIP = "") Then myIP = myRequest.ServerVariables("HTTP_X_CLUSTER_CLIENT_IP") If (myIP = "") Then myIP = myRequest.ServerVariables("HTTP_FORWARDED_FOR") If (myIP = "") Then myIP = myRequest.ServerVariables("HTTP_FORWARDED") If (myIP = "") Then myIP = myRequest.ServerVariables("REMOTE_ADDR") Return myIP End Function
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.
Function Host2Ip(ByVal HostName As String) As String Try Dim myIPs As System.Net.IPHostEntry myIPs = System.Net.Dns.GetHostEntry(HostName) Host2Ip = myIPs.AddressList(0).ToString() Catch ex As Exception 'Handle the error End Try End Function
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.