我正在编写一个应用程序来检索给定网络上所有计算机的名称和 IP 地址。这是为了在远程连接到计算机时使用技术支持。我仍在开发并且仅在我自己的网络上进行测试,但是当我运行它时,我没有得到任何结果,这会显示在输出中。
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
我的代码如下:
public List<NetworkComputer> getComputers( string domain )
{
List<NetworkComputer> computers = new List<NetworkComputer>();
DirectoryEntry entry = new DirectoryEntry( domain );
DirectorySearcher searcher = new DirectorySearcher( entry );
searcher.Filter = ("(objectClass=computer)");
searcher.SizeLimit = int.MaxValue;
searcher.PageSize = int.MaxValue;
foreach( SearchResult result in searcher.FindAll() )
{
if( result.GetDirectoryEntry().Name.StartsWith( "CN=" ) )
{
IPAddress ipAddress = null;
ipAddress = Dns.GetHostAddresses( result.GetDirectoryEntry().Name.Remove( 0, "CN=".Length ) )[0];
computers.Add( new NetworkComputer( result.GetDirectoryEntry().Name.Remove( 0, "CN=".Length ), ipAddress ) );
}
}
return computers;
}
}
}
如果我在不尝试获取 IP 地址的情况下运行它,我会得到一个没有问题的所有计算机的列表。这是导致我出现问题的IP地址。