Alvi
- 📅 2026-03-24T17:15:13.206Z
- 👁️ 23 katselukertaa
- 🔓 Julkinen
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
public class NetworkScanner
{
public class OnlinePC
{
public string Hostname { get; set; }
public string IPAddress { get; set; }
}
public static async Task<List<OnlinePC>> GetOnlineDomainComputersAsync(int timeout = 1000, int maxParallel = 100)
{
var computers = GetAllDomainComputers();
var onlinePCs = new ConcurrentBag<OnlinePC>();
using (SemaphoreSlim semaphore = new SemaphoreSlim(maxParallel))
{
var tasks = computers.Select(async hostname =>
{
await semaphore.WaitAsync();
try
{
using (Ping ping = new Ping())
{
var reply = await ping.SendPingAsync(hostname, timeout);
if (reply.Status == IPStatus.Success)
{
string ip = reply.Address.ToString();
onlinePCs.Add(new OnlinePC
{
Hostname = hostname,
IPAddress = ip
});
}
}
}
catch
{
// Ignore unreachable hosts
}
finally
{
semaphore.Release();
}
});
await Task.WhenAll(tasks);
}
return onlinePCs.ToList();
}
private static List<string> GetAllDomainComputers()
{
var list = new List<string>();
using (DirectoryEntry entry = new DirectoryEntry())
using (DirectorySearcher searcher = new DirectorySearcher(entry))
{
searcher.Filter = "(objectCategory=computer)";
searcher.PropertiesToLoad.Add("name");
foreach (SearchResult result in searcher.FindAll())
{
if (result.Properties.Contains("name"))
{
list.Add(result.Properties["name"][0].ToString());
}
}
}
return list;
}
}