tags:

views:

6037

answers:

6

I am running a server, and I want to display my own IP address.
what is the syntax for getting the computer's own (if possible, external) IP address? The guy before wrote this code

IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
    if (ip.AddressFamily.ToString() == "InterNetwork")
    {
        localIP = ip.ToString();
    }
}
return localIP;

however, I generally distrust him, and I don't understand this code. Is there a better way to do so?

+8  A: 

Nope, that is pretty much the best way to do it. As a machine could have several IP addresses you need to iterate the collection of them to find the proper one.

Edit: The only thing I would change would be to change this:

if (ip.AddressFamily.ToString() == "InterNetwork")

to this:

if (ip.AddressFamily == AddressFamily.InterNetwork)

There is no need to ToString an enumeration for comparison.

Andrew Hare
I want the external IP address, if possible. I suppose it's not going to be that possible if I am behind NAT.
Nefzen
No, your machine will only know its NAT address.
Andrew Hare
I am pretty much sure that you will need to reach an external server for the external address.
Thiago Arrais
then, which is the best IP number I need to choose? The code in the question looked for "InterNetwork", is that the "best"?
Nefzen
"InterNetwork" is the machine's IPv4 address.
Andrew Hare
+1  A: 
namespace NKUtilities 
{
    using System;
    using System.Net;

    public class DNSUtility
    {
        public static int Main (string [] args)
        {

          String strHostName = new String ("");
          if (args.Length == 0)
          {
              // Getting Ip address of local machine...
              // First get the host name of local machine.
              strHostName = Dns.GetHostName ();
              Console.WriteLine ("Local Machine's Host Name: " +  strHostName);
          }
          else
          {
              strHostName = args[0];
          }

          // Then using host name, get the IP address list..
          IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
          IPAddress [] addr = ipEntry.AddressList;

          for (int i = 0; i < addr.Length; i++)
          {
              Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
          }
          return 0;
        }    
     }
}

Look here for details.

You have to remember your computer can have more than one IP (actually it always does) - so which one are you after.

mfloryan
A: 
using System.Net;

string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());

Just tested this on my machine and it works.

opedog
A: 

In essence that seems about the right way to do it, two comments however:

  • I would do the ip.AddressFamily comparison based on the enum itself without a ToString()... it avoids any risk of typos or mangling in the string value
  • Keep in mind that a single machine may very well have multiple external addresses... this is most common in a machine with multiple network interfaces (multiple ethernet, or ethernet and wireless), but by no means impossible on just a single ethernet connection
jerryjvl
A: 

Maybe by external IP you can consider (if you are in a Web server context) using this

Request.ServerVariables["LOCAL_ADDR"];

I was asking the same question as you and I found it in this stackoverflow article.

It worked for me.

Juan Calero
+1  A: 

The only way to know your public IP is to ask someone else to tell you; this code may help you:

public string getPublicIP()
{
    string direction;
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
    WebResponse response = request.GetResponse();
    StreamReader stream = new StreamReader(response.GetResponseStream());
    direction = stream.ReadToEnd();
    stream.Close();
    response.Close();

    //Search for the ip in the html
    int first = direction.IndexOf("Address: ") + 9;
    int last = direction.LastIndexOf("</body>");
    direction = direction.Substring(first, last - first);

    return direction;
}
ezgar
-1: should have response, streamreader, and stream in using blocks.
John Saunders