0

How do you get the IP address of the web/application server in .NET? Not the client IP address, but the server IP address.


I just found something about server variables.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Fryer
  • 9,268
  • 14
  • 61
  • 93
  • 2
    Do you want the External IP address? The IP Address on the local network? The IP address of the URL the originating request went to? – McKay Aug 10 '10 at 18:06
  • @McKay I'm looking for the External IP Address of the web server. – Paul Fryer Aug 10 '10 at 18:10
  • So, the problem is that the external IP address of the server isn't something that the server itself knows about. It's something the external hardware knows about. My external IP address is controlled by my ISP. I happen to know what it is, but I can't directly get it. – McKay Aug 10 '10 at 18:12
  • @McKay Interesting... well how about the internal IP address, know how to get that? – Paul Fryer Aug 10 '10 at 18:14
  • I guess the real question is "What do you want this for?" – McKay Aug 10 '10 at 18:15
  • NeilDurant's answer covers "internal" IP address. – McKay Aug 10 '10 at 18:17
  • Would it be possible to host a service outside of the enclave? That way you could call it and the service you called would respond with the IP that it saw the request originate from. – diadem Aug 10 '10 at 18:21

4 Answers4

3

You probably want something like the following code, to get all IP addresses of the current machine. However it won't tell you which network adaptor (and thus IP address) a particular request came in on, if you have more than one.

   String strHostName = Dns.GetHostName();
   Console.WriteLine("Host Name: " + strHostName);

   // Find host by name
   IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

   // Enumerate IP addresses
   foreach(IPAddress ipaddress in iphostentry.AddressList)
   {
       Console.WriteLine(ipaddress.ToString());
   }
NeilDurant
  • 2,082
  • 2
  • 14
  • 14
1

To get my own IP address in C#

IPHostEntry ipEntry = DNS.GetHostByName (Dns.GetHostName());
IPAddress [] addr = ipEntry.AddressList;

To get for other's machine

IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
IPAddress [] addr = ipEntry.AddressList;
Community
  • 1
  • 1
ankitjaininfo
  • 11,961
  • 7
  • 52
  • 75
0

There are services that tell you what your external IP address is, but it might be subject to change.

Sample Services:

McKay
  • 12,334
  • 7
  • 53
  • 76
-2

To get the IP address (and Coutnry/location) of a server programatically I use Utrace.de API. It returns an XML with IP address and location information too.

Example query: http://xml.utrace.de/?query=google.com

ankitjaininfo
  • 11,961
  • 7
  • 52
  • 75