Many times there’s a query to get the IP Address of the client machine from which the user visited the website. this will help the developers who are working with the web based application.The following code gets the IP address of the machine from which the client visited the website and you can apply your logic to store that details in your databases. Let us see here how to find ip address of a client machine using asp.net
string ipaddress; ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (ipaddress == "" || ipaddress == null) ipaddress = Request.ServerVariables["REMOTE_ADDR"];
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
When users are behind any proxies or routers the REMOTE_ADDR returns the IP Address of the router and not the client user’s machine. Hence first we need to check HTTP_X_FORWARDED_FOR, since when client user is behind a proxy server his machine’s IP Address the Proxy Server’s IP Address is appended to the client machine’s IP Address. If there are multiple proxy servers the IP Addresses of all of them are appended to the client machine IP Address.
Hence we need to first check HTTP_X_FORWARDED_FOR and then REMOTE_ADDR.