Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if hostname refers to local machine

Can anyone think of an easy way to tell in win32 or .NET if hostname (string) resolves to a local computer? Such as:

"myhostname"
"myhostname.mydomain.local"
"192.168.1.1"
"localhost"

The goal of this exercise is to produce a test which will tell if Windows security layer will treat access to machine as local or network

like image 321
galets Avatar asked Dec 24 '09 17:12

galets


2 Answers

This question has already been answered, but here's what I came up with to resolve both host name and IP address:

public static bool IsLocalHost(string host)
{
    IPHostEntry localHost = Dns.GetHostEntry(Dns.GetHostName());

    IPAddress ipAddress = null;

    if (IPAddress.TryParse(host, out ipAddress))
        return localHost.AddressList.Any(x => x.Equals(ipAddress));

    IPHostEntry hostEntry = Dns.GetHostEntry(host);

    return localHost.AddressList.Any(x => hostEntry.AddressList.Any(y => x.Equals(y)));
}
like image 39
PhilDulac Avatar answered Oct 14 '22 15:10

PhilDulac


In .NET you can:

IPHostEntry iphostentry = Dns.GetHostEntry (Dns.GetHostName ());

Then for any host name, check if it resolves to one of the IPs in iphostEntry.AddressList (this is an IPAddress[]).

Here is a full program that will check the host names/IP addresses passed in the command line:

using System;
using System.Net;

class Test {
    static void Main (string [] args)
    {
        IPHostEntry iphostentry = Dns.GetHostEntry (Dns.GetHostName ());
        foreach (string str in args) {
            IPHostEntry other = null;
            try {
                other = Dns.GetHostEntry (str);
            } catch {
                Console.WriteLine ("Unknown host: {0}", str);
                continue;
            }
            foreach (IPAddress addr in other.AddressList) {
                if (IPAddress.IsLoopback (addr) || Array.IndexOf (iphostentry.AddressList, addr) != -1) {
                    Console.WriteLine ("{0} IsLocal", str);
                    break;
                } 
            }
        }
    }
}
like image 178
Gonzalo Avatar answered Oct 14 '22 14:10

Gonzalo