Client and server IP address discovery

I am working on an application that automatically redirects the user to the nearest server (there are several servers). To do this, I need to determine the IP address of the client and the IP address of the server that the client is visiting. I think to get the IP address of a client that I can use:

HttpContext.Current.Request.UserHostAddress

How to get the IP address of the server that the client is visiting? Is it possible to detect it without using DNS queries?

+5
source share
2 answers

Looks like this:

Getting server IP address 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!

+1
source

Better, cleaner and shorter method:

using System.Net;

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

: , , ( ). , , IP- . IPAddress[] :

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);
}
0

All Articles