AlexSJC
发布于 2023-10-21 / 3 阅读
0
0

C# 异步 Ping 多个 IP

#C#
public static async Task<List<string>> PingIPs(List<string> ips, int timeout = 1000)
{
    var tasks = ips.Select(ip => new Ping().SendPingAsync(ip, timeout));
    var results = await Task.WhenAll(tasks);
    return results.Where(r => r.Status == IPStatus.Success).Select(r => r.Address.ToString()).ToList();
}
var ips = await PingIPs(Enumerable.Range(1, 255).Select(i => $"192.168.1.{i}").ToList());
ips.ForEach(ip => Console.WriteLine(ip));


评论