我想扫描一个网络并枚举所有windows机器的主机名。有一个接口方法,它以ip范围作为输入并返回主机名。我必须实施它。下面是我的代码:
public ICollection<string> EnumerateWindowsComputers(ICollection<string> ipList)
{
ICollection<string> hostNames = new List<string>();
foreach (var ip in ipList)
{
var hostName = GetHostName(ip);
if (string.IsNullOrEmpty(hostName) == false)
{
hostNames.Add(hostName)
}
}
return hostNames;
}
private static string GetHostName(string ipAddress)
{
try
{
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
if (entry != null)
{
return entry.HostName;
}
}
catch (SocketException ex)
{
System.Console.WriteLine(ex.Message + " - " + ipAddress);
}
return null;
}
此方法成功枚举所有windows计算机,但其中有网络打印机。我可以很容易地忽略打印机的主机名,但这不是一个好的解决方案。我必须确保只有Windows操作系统的设备返回。
如果没有第三方图书馆,你知道怎么做吗?如果有更好的方法,我们不需要使用GetHostName
方法。
Ps.linux、MacOS、Android和IOS设备并不像预期的那样被发现。
发布于 2017-03-08 01:44:09
根据@Jeroen的comment,我用GetWindowsHostName
改变了我的GetHostName
方法。
private string GetWindowsHostName(string ipAddress)
{
try
{
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
if (entry != null)
{
try
{
using (TcpClient tcpClient = new TcpClient())
{
// 445 is default TCP SMB port
tcpClient.Connect(ipAddress, 445);
}
using (TcpClient tcpClient = new TcpClient())
{
// 139 is default TCP NetBIOS port.
tcpClient.Connect(ipAddress, 139);
}
return entry.HostName;
}
catch (Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
}
catch (SocketException ex)
{
System.Console.WriteLine(ex.Message + " - " + ipAddress);
}
return null;
}
可能有假阳性,但这是不可能的,也是可以接受的。
发布于 2017-03-08 00:56:38
服务检测将不正确,因为可能有linux或其他盒在模拟Windows FileSharing。
使用Windows命令从Windows可靠地获取远程Windows详细信息。您的代码如下所示:
string IPADDRESS = "192.168.1.1";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.startInfo.FileName = "cmd.exe";
p.startInfo.Arguments = "/C systeminfo /s IPADDRESS";
p.Start();
p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
p.WaitForExit();
if(output.Contains("Microsoft Windows")) { Console.WriteLine("Windows OS"); }
发布于 2017-03-08 00:59:16
您可以尝试在远程计算机中检测OS的一种方法是使用ping。平每个IP地址并得到TTL。这应该会让你对你正在处理的操作系统有一个了解。在这里可以找到一个与操作系统匹配的TTL表:http://www.kellyodonnell.com/content/determining-os-type-ping
https://stackoverflow.com/questions/42666505
复制