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
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)));
}
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;
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With