Alvi

📅 2026-03-24T17:14:42.566Z
👁️ 26 katselukertaa
🔓 Julkinen


using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading.Tasks;

public class ADScanner
{
    public class OnlinePC
    {
        public string Hostname { get; set; }
        public string IPAddress { get; set; }
    }

    public static List<OnlinePC> GetOnlineDomainComputers()
    {
        var onlinePCs = new ConcurrentBag<OnlinePC>();
        var computerNames = new List<string>();

        // STEP 1: Get all computers from Active Directory
        using (DirectoryEntry entry = new DirectoryEntry("LDAP://RootDSE"))
        {
            string domainDN = entry.Properties["defaultNamingContext"].Value.ToString();

            using (DirectoryEntry searchRoot = new DirectoryEntry($"LDAP://{domainDN}"))
            using (DirectorySearcher searcher = new DirectorySearcher(searchRoot))
            {
                searcher.Filter = "(objectClass=computer)";
                searcher.PropertiesToLoad.Add("name");

                foreach (SearchResult result in searcher.FindAll())
                {
                    if (result.Properties.Contains("name"))
                    {
                        computerNames.Add(result.Properties["name"][0].ToString());
                    }
                }
            }
        }

        // STEP 2: Ping in parallel (FAST)
        Parallel.ForEach(computerNames, new ParallelOptions { MaxDegreeOfParallelism = 50 }, computer =>
        {
            try
            {
                using (Ping ping = new Ping())
                {
                    PingReply reply = ping.Send(computer, 1000);

                    if (reply.Status == IPStatus.Success)
                    {
                        onlinePCs.Add(new OnlinePC
                        {
                            Hostname = computer,
                            IPAddress = reply.Address.ToString()
                        });
                    }
                }
            }
            catch
            {
                // Ignore failures (offline/unreachable)
            }
        });

        return new List<OnlinePC>(onlinePCs);
    }
}