Given a list of IP addresses:
List<string> ipList = new List<string>(); //example: 192.168.0.1, 192.168.0.2, 192.168.0.3 etc.
I am attempting to loop over each IP in the list, in a parallel fashion and then print a meaningful message to screen:
foreach (PingReply pingReply in ipList.AsParallel().WithDegreeOfParallelism(64).Select(ip => new Ping().Send(ip)))
{
Console.WriteLine($"Ping status: {pingReply.Status} for the target IP address: {ip}");
}
I am unable to access ip
in that context. I would really like to understand how I could go about accessing each relative ip
as I am sending them out?
I have explored the PingReply
object but PingReply.Address
as an example contains the host (sender) IP, so it cannot help with this requirement. I really wish the PingReply
object contained the Ip that was pinged!
UPDATE
As per example provided by @haim770 and @MindSwipe I ended up using:
foreach (var pingResponseData in ipList.AsParallel().WithDegreeOfParallelism(64).Select(ip => new { ip, pingReply = new Ping().Send(ip) }))
{
Console.WriteLine($"Ping status: {pingResponseData.pingReply.Status} for the target IP address: {pingResponseData.ip}");
}
UPDATE 2
As per comment from @pinkfloydx33 regarding use of ValueTuple
I have done as per the following example:
foreach (var (ip, reply) in ipList.AsParallel().WithDegreeOfParallelism(ipList.Count).Select(ip => (ip, new Ping().Send(ip, 150))))
{
Console.WriteLine($"Ping status: {reply.Status} for the target IP address: {ip}");
}