获取网络计算机的名称

时间:2014-01-13 14:49:10

标签: c# .net wcf networking

有几台计算机连接到一台无线路由器。我可以在一台计算机上创建一个WCF服务,并使用服务托管计算机上Environment.MachineName中表示的计算机名称从另一台计算机上使用它。但是,我似乎无法从其他计算机中发现该名称。

我尝试过的一些事情:(这些只是相关部分。)

此:

Dns.GetHostName(); ... //(Just gives me this computer's name.)

而且:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain) ... // "The server could not be contacted."

还有这个:

DirectorySearcher searcher = new DirectorySearcher("(objectCategory=computer)", new[] { "Name" }); 
SearchResultCollection SRC = searcher.FindAll(); ... // "The specified domain either does not exist or could not be contacted."

DirectoryEntry root = new DirectoryEntry("WinNT:");
foreach (DirectoryEntry dom in root.Children)
    foreach (DirectoryEntry entry in dom.Children)
        if (entry.Name != "Schema")
            result += entry.Name + "\r\n"; // https://stackoverflow.com/a/5581339/939213 returns nothing.

那么,怎么做我得到了计算机的名字?

我对任何第三方图书馆都不感兴趣。我知道http://www.codeproject.com/Articles/16113/Retreiving-a-list-of-network-computer-names-using,但该代码来自2006年。我希望现在有一些管理方式可以做到这一点。并且根据Getting computer names from my network places - “除非您确定域环境,否则不要使用DirectoryServices”。

1 个答案:

答案 0 :(得分:3)

您可以使用此代码段获取本地网络中存在的所有计算机的IP列表(由ARP命令回复):

static List<string> GetARP()
{
    List<string> _ret = new List<string>();

    Process netUtility = new Process();
    netUtility.StartInfo.FileName = "arp.exe";
    netUtility.StartInfo.CreateNoWindow = true;
    netUtility.StartInfo.Arguments = "-a";
    netUtility.StartInfo.RedirectStandardOutput = true;
    netUtility.StartInfo.UseShellExecute = false;
    netUtility.StartInfo.RedirectStandardError = true;
    netUtility.Start();

    StreamReader streamReader = new StreamReader(netUtility.StandardOutput.BaseStream, netUtility.StandardOutput.CurrentEncoding);

    string line = "";
    while ((line = streamReader.ReadLine()) != null)
    {

        if (line.StartsWith("  "))
        {
            var Itms = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            if (Itms.Length == 3)
                _ret.Add(Itms[0]);
        }
    }

    streamReader.Close();

    return _ret;

}

您可以尝试通过调用Dns.GetHostByAddress(targetIP)来单独解析每台计算机的名称。