C# Tips & Tricks #36 – How to Get User’s IP Address

This blog post will explain various ways by which the .NET developers can get user’s IP address using ASP.NET and C#.

How to get User’s IP Address using ASP.NET and C# ?

There are 3 different ways which you can use to fetch the IP address using C#.

  1. Request.UserHostAddress
  2. Request.ServerVariables & REMORE_ADDR
  3. Request.ServerVariables & HTTP_X_FORWARDED_FOR

The IP Address can be retreived in the following ways.

String str = HttpContext.Current.Request.UserHostAddress;

or

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

The REMOTE_ADDR usually provides the IP Address of the Internet Service Provider in some cases.As a result it may be required to test with HTTP_X_FORWARDED_FOR to get the real IP Address.This might also contain an array of IP addresses when connected through proxies.

Eg :

Request.ServerVariables("HTTP_X_FORWARDED_FOR");

and check to see if it returns an Empty and then retreive the corresponding IP Address using REMOTE_ADDR.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...