Friday, October 3, 2008

How to get user’s IP address using asp.net

Many times we need to get the current user’s / visitor’s IP address.

Sometimes this is essential for security reasons.
We must leg the user’s IP address in the following situations:

1) where you accept data from user, like guestbook newsletter, search page etc. This gives a plus point to the security of website, as you can get the user’s identity by his IP if he do something wrong with your website.

2) User login pages. Alwayskeep record the logins of website users. Record the datetime and IP of user.

If you want to blok some particular users to use your website then on page load just ckeck the current Ip against database of ip’s you have created for blacklisting.

Now coming to the point,
How to get user’s IP address using asp.net

HttpContext.Current.Request.UserHostAddress;
or
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

The above code may return the IP with proxy.

Use the below code to get the IP address of the machine and not the proxy use the following code
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"

No comments: