如何在IP范围内查找Windows PC

时间:2017-03-08 08:35:05

标签: c# network-scan

我想扫描网络并枚举所有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计算机,但其中包含网络打印机。我很容易忽略我的打印机&#39;主机名,但它不是一个好的解决方案。我必须确保只返回带有Windows操作系统的设备。

如果没有第三方库,怎么办?如果有更好的方法,我们不必使用GetHostName方法。

P.S。未按预期找到Linux,MacOS,Android和IOS设备。

3 个答案:

答案 0 :(得分:0)

服务检测不正确,因为可能有linux或其他框模拟 Windows FileSharing

使用Windows机器中的systeminfo /s IPADDRESS shell命令可靠地获取远程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"); }

答案 1 :(得分:0)

您可以尝试在远程计算机中检测操作系统的一种方法是使用ping。 Ping每个IP地址并获取TTL。这应该可以让您了解您正在处理的操作系统。可以在此处找到与TTL匹配的表:http://www.kellyodonnell.com/content/determining-os-type-ping

答案 2 :(得分:0)

根据@Jeroen van Langen的comment,我使用GetHostName更改了GetWindowsHostName方法。

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

可能存在误报,但这对我来说不太可能并且可以接受。