在.net中查找网络别名

时间:2020-03-05 18:52:27  来源:igfitidea点击:

.net 2.0中是否可以找到运行我的代码的计算机的网络别名?具体来说,如果我的工作组将我的计算机视为// jekkedev01,我如何以编程方式检索该名称?

解决方案

回答

使用System.Environment类。它具有用于检索计算机名称的属性,该属性是从NetBios中检索的。除非我误解了你的问题。

回答

或者My.Computer.Name

回答

如果需要计算机说明,它将存储在注册表中:

  • 密钥:" HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Services \ lanmanserver \ parameters"
  • 值名称:srvcomment
  • 数据类型:REG_SZ(字符串)

AFAIK与任何域服务器或者PC连接到的网络无关。

对于与网络相关的任何事情,我正在使用以下工具:

  • NETBIOS名称:System.Environment.MachineName
  • 主机名:System.Net.Dns.GetHostName()
  • DNS名称:System.Net.Dns.GetHostEntry(" LocalHost")。HostName

如果PC具有多个NETBIOS名称,我不知道任何其他方法,只能根据它们解析到的IP地址对名称进行分组,如果PC具有多个网络接口,即使这样也不可靠。

回答

我不是.NET程序员,但是System.Net.DNS.GetHostEntry方法看起来像我们所需要的。它返回包含Aliases属性的IPHostEntry类的实例。

回答

由于我们可以有多个网络接口,每个网络接口可以有多个IP,并且任何一个IP都可以具有可以解析为该IP的多个名称,因此可能会有多个。

如果我们想知道DNS服务器知道计算机的所有名称,则可以像这样遍历它们:

public ArrayList GetAllDnsNames() {
  ArrayList names = new ArrayList();
  IPHostEntry host;
  //check each Network Interface
  foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {
    //check each IP address claimed by this Network Interface
    foreach (UnicastIPAddressInformation i in nic.GetIPProperties().UnicastAddresses) {
      //get the DNS host entry for this IP address
      host = System.Net.Dns.GetHostEntry(i.Address.ToString());
      if (!names.Contains(host.HostName)) {
        names.Add(host.HostName);
      }
      //check each alias, adding each to the list
      foreach (string s in host.Aliases) {
        if (!names.Contains(s)) {
          names.Add(s);
        }
      }
    }
  }
  //add "simple" host name - above loop returns fully qualified domain names (FQDNs)
  //but this method returns just the machine name without domain information
  names.Add(System.Net.Dns.GetHostName());

  return names;
}