views:

107

answers:

3

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

+2  A: 

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;
       } 
      }
     }
    }
}
Gonzalo
Tis worked, although it seems this doesn't test for addresses like "127.0.0.1". This one works (feel free to update your post if you feel like): var local_ip = (from ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList select ip).ToList(); local_ip.Add(IPAddress.Loopback); local_ip.Add(IPAddress.IPv6Loopback); var target_ip = Dns.GetHostEntry(target).AddressList; var intersect = from ip1 in target_ip join ip2 in local_ip on ip1 equals ip2 select ip1; return intersect.Any();
galets
+1  A: 

You can get the IP address that the hostname resolves to by writing Dns.Resolve(hostName).AddressList[0].ToString().

You can then compare that to 127.0.0.1 or to the computer's local IP address.

You can get the computer's local IP addresses by looping through System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList.

SLaks
A: 

In .net you should be able to use Request.ServerVariables(“REMOTE_ADDR”); to get the host ip address and then compare it with the resolved ip address of the hostname. Isn't that what you wanted?

hmm
This will only work for ASP.NET applications.
Gonzalo
This is only true during an ASP.Net request. Also, you should use `Request.UserHostAddress`.
SLaks