In this article I will explain with an example, why the Request.ServerVariables HTTP_X_FORWARDED_FOR is NULL when it is used to fetch the IP Address in ASP.Net using C# and VB.Net.
 
 
Why the Request.ServerVariables HTTP_X_FORWARDED_FOR is NULL?
HTTP_X_FORWARDED_FOR Request.ServerVariables will have value only when the Client machine is behind a Proxy Server its IP Address of the Proxy Server is appended to the Client machine’s IP Address. If there are multiple Proxy Servers then the IP Addresses of all the Proxy Servers are appended to the client machine IP Address.
If the IP Address is not found in the HTTP_X_FORWARDED_FOR server variable, it means that it is not using any Proxy Server and hence the IP Address is should be checked in the REMOTE_ADDR server variable.
 
 
How to get IP Address of Visitors Machine in ASP.Net
First the IP Address is determined for the Client machine’s which are behind Routers or Proxy Servers and hence the HTTP_X_FORWARDED_FOR server variable is checked and if it is NULL then the IP Address value is fetchded from the REMOTE_ADDR server variable.
Note: While running this application on your machine locally i.e. in Visual Studio, the IP Address will show as 127.0.0.1 or ::1. This happens because in such case the Client and Server both are the same machine. Thus no need to worry when you deploy it on a Server, you will see the results.
 
C#
string ipaddress;
ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipaddress == "" || ipaddress == null)
    ipaddress = Request.ServerVariables["REMOTE_ADDR"];
 
VB.Net
Dim ipaddress As String
ipaddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If ipaddress = "" Or ipaddress Is Nothing Then
   ipaddress = Request.ServerVariables("REMOTE_ADDR")
End If
 
 
Demo
View Demo
 
 
Downloads