How to get the users IP Address in C#.NET?

When you search this on your favourite search engine, (Google) you will get flooded by load of different way to get the end result. This is great in a sense as you know there are thousands of people with different answers, but then that is where the problem is at. There are so many single responses to how you can get the users IP Address in C#.NET, but not one that shows you everything. Therefore I will present to you below different methods to get the users IP and how I have implemented it in a project.

All the methods I found to be best are using the Request Server Variables. These are predetermined environment variables and request header information. This is why you can get IP address as it is part of the header information.

The standard server variable to use is ‘REMOTE_ADDR’, which is done as the following:

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

However if the user is behind a proxy server, then the above will return that IP Address and not the actual users. The server variable to get the users IP address from behind the proxy server is ‘HTTP_X_FORWARDED_FOR’ done as below:

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

Then you get that issue of not knowing if the user is behind a proxy or not, as the first example will return one or the other and the second example will only return a value if there is a proxy server. Therefore we need to find out if there is a proxy server or not. You can do this with the server variable ‘HTTP_VIA’, if this has a value then they must be using a proxy server and so you can get the correct IP as below:

If (HttpContext.Current.Request.ServerVariables[“HTTP_VIA”] != null) {
return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}

return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

Or another method is to do it in reverse and check if the proxy method is not null first instead like:

string userIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (string.IsNullOrEmpty(userIp)){
return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}

return userIp;

This is the best method I found to get the users IP Address in ASP.NET C#, but if you think there is a better way then please comment below with your solution.

Advertisements

Leave a message please

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s