Alex Rivera | Logout

How to check if localhost

Asked 2012-08-06T18:50:52.390
45

Is there a way in c# to check if the app is running on localhost (as opposed to a production server)?

I am writing a mass mailing program that needs to use a certain mail queue is it's running on localhost.

if (Localhost)
{
Queue = QueueLocal;
}
else
{
Queue = QueueProduction;
}
Edit
Report

1 Answer

21

See if this works:

public static bool IsLocalIpAddress(string host)
{
  try
  { // get host IP addresses
    IPAddress[] hostIPs = Dns.GetHostAddresses(host);
    // get local IP addresses
    IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

    // test if any host IP equals to any local IP or to localhost
    foreach (IPAddress hostIP in hostIPs)
    {
      // is localhost
      if (IPAddress.IsLoopback(hostIP)) return true;
      // is local address
      foreach (IPAddress localIP in localIPs)
      {
        if (hostIP.Equals(localIP)) return true;
      }
    }
  }
  catch { }
  return false;
}

Reference: http://www.csharp-examples.net/local-ip/

answered 2012-08-06T18:54:06.163

Your Answer