从SendPingAsync结果中检索ping主机名

时间:2014-08-27 18:02:01

标签: c# dns ping

我从字符串列表(地址)ping主机。一切都很完美但是当主机无法访问时,ping返回Result.Address:" 0.0.0.0"而不是我传递给SendPingAsync函数的现有地址或主机名。 这是我的代码:

            var pingTasks = addresses.Select(address =>
            {
                return new Ping().SendPingAsync(address);
            });

            await Task.WhenAll(pingTasks);

            StringBuilder pingResultBuilder = new StringBuilder();

            foreach (var pingReply in pingTasks)
            {
                pingResultBuilder.Append(pingReply.Result.Address);
                pingResultBuilder.Append("    ");

                pingResultBuilder.Append(pingReply.Result.Status);
                pingResultBuilder.Append("    ");

                pingResultBuilder.Append(pingReply.Result.RoundtripTime.ToString());
                pingResultBuilder.AppendLine();
            }

            Console.WriteLine(pingResultBuilder.ToString());

我找到了解决方案here,但我需要在SendPingAsync函数中执行相同的操作,而不是SendAsync。 如何从host name / ip address检索传递的pingReply.Result

1 个答案:

答案 0 :(得分:5)

您可以使用SendAsync编写扩展方法。

public static class MyExtensions
{
    public static Task<PingResult> SendTaskAsync(this Ping ping, string address)
    {
        var tcs = new TaskCompletionSource<PingResult>();
        PingCompletedEventHandler response = null;
        response = (s, e) =>
        {
            ping.PingCompleted -= response;
            tcs.SetResult(new PingResult() { Address = address, Reply = e.Reply });
        };
        ping.PingCompleted += response;
        ping.SendAsync(address, address);
        return tcs.Task;
    }

    public class PingResult
    {
        public string Address { set; get; }
        public PingReply Reply { set; get; }
    }
}

您现在可以像以下一样使用它:

var pingTasks = addresses.Select(address =>
{
    return new Ping().SendTaskAsync(address);
});

var replies = await Task.WhenAll(pingTasks);

StringBuilder pingResultBuilder = new StringBuilder();

foreach (var pingReply in replies)
{
    pingResultBuilder.Append(pingReply.Address);
    pingResultBuilder.Append("    ");

    pingResultBuilder.Append(pingReply.Reply.Status);
    pingResultBuilder.Append("    ");

    pingResultBuilder.Append(pingReply.Reply.RoundtripTime.ToString());
    pingResultBuilder.AppendLine();
}

Console.WriteLine(pingResultBuilder.ToString());