Dot-Net

如何測試主機名是否指本地機器

  • November 25, 2014

如果主機名(字元串)解析為本地電腦,任何人都可以想出一種簡單的方法來判斷 win32 或 .NET 嗎?如:

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

本練習的目標是生成一個測試,該測試將判斷 Windows 安全層是否將對機器的訪問視為本地或網路

在 .NET 中,您可以:

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

然後對於任何主機名,檢查它是否解析為其中的一個 IP iphostEntry.AddressList(這是一個 IPAddress

$$ $$). 這是一個完整的程序,它將檢查命令行中傳遞的主機名/IP 地址:

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;
               } 
           }
       }
   }
}

引用自:https://stackoverflow.com/questions/1959172