Connecting Tech Pros Worldwide Help | Site Map

How to get a client's ip address with ASP.NET

 
LinkBack Thread Tools Search this Thread
  #1  
Old December 27th, 2005, 07:04 AM
Newbie
 
Join Date: Dec 2005
Posts: 3
Default How to get a client's ip address with ASP.NET

I want to fetch client's ip address as soon as he accesses my web-site built in asp.net.Then i want to store it in my database.
Is there any method to achieve this target in asp.net application.
If you could help me i will be very thankful to you.
Reply
  #2  
Old December 27th, 2005, 07:12 AM
KUB365's Avatar
Administrator
 
Join Date: Jul 2005
Location: Portland, OR
Age: 28
Posts: 861
Default

ASP .Net web page:
Expand|Select|Wrap|Line Numbers
  1. Dim strClientIP As String
  2. strClientIP = Request.UserHostAddress()
  3. Response.Write(strClientIP)
  4.  
ASP .NET web services:
Expand|Select|Wrap|Line Numbers
  1. Context.Request.ServerVariables ["REMOTE_ADDR"]
  2.  
Reply
  #3  
Old June 10th, 2007, 05:44 AM
Newbie
 
Join Date: Jun 2007
Posts: 1
Default

or you can try:

string ip;

ip=Request.ServerVariables("HTTP_X_FORWARDED_FOR") ;
if(ip==string.Empty)
{
ip=Request.ServerVariables("REMOTE_ADDR");
}
REMOTE_ADDR does not always provide the users IP but rather the ISPs' IP address so first test HTTP_X_FORWARDED_FOR as this one is the real user IP.
Reply
  #4  
Old February 16th, 2009, 02:19 AM
Newbie
 
Join Date: Feb 2009
Posts: 1
Default Thanks guys

This is very helpful for me. Many thanks
Reply
  #5  
Old June 24th, 2009, 12:40 PM
Newbie
 
Join Date: Jun 2009
Posts: 1
Default

Another important note to this

the HTTP_X_FORWARDED_FOR may contain an array of IP, this can happen if you connect through a proxy.
What also happens when this happens is that the REMOTE_ADDR may contain the proxy IP.

to avoid this problem you can parse the HTTP_X_FORWARDED_FOR for the last entery IP.

this can easily be done using...
Expand|Select|Wrap|Line Numbers
  1. ip=Request.ServerVariables("HTTP_X_FORWARDED_FOR") ;
  2. if (!string.IsNullOrEmpty(ip))
  3. {
  4.    string[] ipRange = ip.Split(',');
  5.    int le = ipRange.Length - 1;
  6.    string trueIP = ipRange[le];
  7. }
  8. else
  9. {
  10.    ip=Request.ServerVariables("REMOTE_ADDR");
  11. }
This code example is C#.NET but the method is the same

What this does is check if we have anything in the HTTP_X_FORWARDED_FOR, and if we do we take out the last entry (works if only one entry is found aswell)
if we don't have an HTTP_X_FORWARDED_FOR we set the IP from the REMOTE_ADDR instead
Reply
Reply

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search


Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 220,662 network members.