5

I am working on an application that redirects the user to closest server automatically (there are multiple servers). For that I need to detect client's IP address and server's IP address the client is visiting. I think to get the client's IP address I can use:

HttpContext.Current.Request.UserHostAddress

How do I get the server's IP address that the client is visiting? Is it possible to detect it without using DNS querying ?

skos
  • 4,102
  • 8
  • 36
  • 59
  • this sort of redirection is better of being done at the router level as once the client connects to be redirected you might as well serve the page anyway. – Lloyd Mar 21 '12 at 08:42

2 Answers2

1

Looks like it's here:

Getting the IP address of server in ASP.NET?

//this gets the ip address of the server pc 

public string GetIPAddress() 
{ 
 string strHostName = System.Net.Dns.GetHostName(); 
 IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
 IPAddress ipAddress = ipHostInfo.AddressList[0]; 

 return ipAddress.ToString(); 
} 

Kudos to TStamper!

Community
  • 1
  • 1
RemarkLima
  • 11,639
  • 7
  • 37
  • 56
  • 1
    That answer should just be a a comment as duplicate. – Silvermind Mar 21 '12 at 08:17
  • It gives me this error `The type or namespace name 'IPHostEntry' could not be found (are you missing a using directive or an assembly reference?)`. Am I missing out on something ? – skos Mar 21 '12 at 08:19
  • Better use the other answer in your linked article, the one [without DNS querying](http://stackoverflow.com/a/2239564/107625). – Uwe Keim Mar 21 '12 at 08:19
  • @UweKeim I couldn't find 'without DNS querying'. Where's it? – skos Mar 21 '12 at 08:24
  • 1
    Just click on @Uwe-Keim's comment "Without DNS querying" - It'll take you to the answer that doesn't use a DNS lookup. – RemarkLima Mar 21 '12 at 08:41
0

Better, cleaner and shorter method:

using System.Net;

public IPAddress[] GetIPAddress() 
{ 
    return Dns.GetHostAddresses(Dns.GetHostName());
} 

TIP: This method returns an array of addresses, some of them are private NICs and at least one is public (facing the Internet). This is an helpful method that tells you whether a given IP address is private. Iterate your IPAddress[] array and query against this method:

public bool IsPrivateNetworkIPAddress(string ip)
{
    Regex rx = new Regex(@"(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)"); // see http://stackoverflow.com/a/2814102/290343
    return rx.IsMatch(ip);
}
Ofer Zelig
  • 17,068
  • 9
  • 59
  • 93