Beispiel #1
0
        private static void AddException(PingException exception, MonitorWorkItem workItem)
        {
            string message = $@"{exception.Message}

{exception.InnerException.AggregateMessages()}";

            workItem.Add(Time.UtcNow, "Ping Urls", message);
        }
Beispiel #2
0
        public async Task SendAsync_ThrowsPlatformNotSupported_Unix()
        {
            // TODO: Remove this test once Ping implemented on Unix

            IPAddress localIpAddress = IPAddress.Loopback;
            Ping      p = new Ping();

            PingException e = await Assert.ThrowsAsync <PingException>(() => p.SendPingAsync(localIpAddress));

            Assert.IsType <PlatformNotSupportedException>(e.InnerException);
        }
Beispiel #3
0
        Task <bool> ITransportDelegator.PingAsync(ITransportRequestState requestState)
        {
            var pingTimeout = this.Settings.PingTimeout.GetValueOrDefault(DefaultPingTimeout);

            pingTimeout = requestState.RequestConfiguration != null
                                ? requestState.RequestConfiguration.ConnectTimeout.GetValueOrDefault(pingTimeout)
                                : pingTimeout;

            var requestOverrides = new RequestConfiguration
            {
                ConnectTimeout = pingTimeout,
                RequestTimeout = pingTimeout
            };
            var rq = requestState.InitiateRequest(RequestType.Ping);

            try
            {
                return(this.Connection.Head(requestState.CreatePathOnCurrentNode(""), requestOverrides)
                       .ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        rq.Finish(false, null);
                        rq.Dispose();
                        throw new PingException(requestState.CurrentNode, t.Exception);
                    }
                    rq.Finish(t.Result.Success, t.Result.HttpStatusCode);
                    rq.Dispose();
                    var response = t.Result;
                    if (!response.HttpStatusCode.HasValue || response.HttpStatusCode.Value == -1)
                    {
                        throw new PingException(requestState.CurrentNode, t.Exception);
                    }
                    if (response.HttpStatusCode == (int)HttpStatusCode.Unauthorized)
                    {
                        throw new ElasticsearchAuthenticationException(response);
                    }
                    using (response.Response)
                        return response.Success;
                }));
            }
            catch (ElasticsearchAuthenticationException)
            {
                throw;
            }
            catch (Exception e)
            {
                var tcs           = new TaskCompletionSource <bool>();
                var pingException = new PingException(requestState.CurrentNode, e);
                tcs.SetException(pingException);
                return(tcs.Task);
            }
        }
Beispiel #4
0
        public byte[] sendPacket(IPAddress end, byte[] body)
        {
            Ping      pingSender = new Ping();
            PingReply reply      = pingSender.Send(end);

            if (reply.Status == IPStatus.Success)
            {
                return(reply.Buffer);
            }
            else
            {
                Exception x = new PingException(reply.Status.ToString());
                return(null);
            }
        }
        private void ProcessPingStatus(ManagementBaseObject pingStatus)
        {
            string str = (string)LanguagePrimitives.ConvertTo(pingStatus.GetPropertyValue("Address"), typeof(string), CultureInfo.InvariantCulture);
            int    num = (int)LanguagePrimitives.ConvertTo(pingStatus.GetPropertyValue("PrimaryAddressResolutionStatus"), typeof(int), CultureInfo.InvariantCulture);

            if (num == 0)
            {
                int num1 = (int)LanguagePrimitives.ConvertTo(pingStatus.GetPropertyValue("StatusCode"), typeof(int), CultureInfo.InvariantCulture);
                if (num1 == 0)
                {
                    this.quietResults[str] = true;
                    if (!this.quiet)
                    {
                        base.WriteObject(pingStatus);
                    }
                }
                else
                {
                    if (!this.quiet)
                    {
                        Win32Exception win32Exception = new Win32Exception(num1);
                        string         str1           = StringUtil.Format(ComputerResources.NoPingResult, str, win32Exception.Message);
                        Exception      pingException  = new PingException(str1, win32Exception);
                        ErrorRecord    errorRecord    = new ErrorRecord(pingException, "TestConnectionException", ErrorCategory.ResourceUnavailable, str);
                        base.WriteError(errorRecord);
                        return;
                    }
                }
            }
            else
            {
                if (!this.quiet)
                {
                    Win32Exception win32Exception1 = new Win32Exception(num);
                    string         str2            = StringUtil.Format(ComputerResources.NoPingResult, str, win32Exception1.Message);
                    Exception      exception       = new PingException(str2, win32Exception1);
                    ErrorRecord    errorRecord1    = new ErrorRecord(exception, "TestConnectionException", ErrorCategory.ResourceUnavailable, str);
                    base.WriteError(errorRecord1);
                    return;
                }
            }
        }
Beispiel #6
0
        public async Task Should_throw_exception_for_generic_send_when_exception_occurs()
        {
            var container = new Container(cfg =>
            {
                cfg.Scan(scanner =>
                {
                    scanner.AssemblyContainingType(typeof(NullPinged));
                    scanner.IncludeNamespaceContainingType <Ping>();
                    scanner.WithDefaultConventions();
                    scanner.AddAllTypesOf(typeof(IRequestHandler <,>));
                });
                cfg.For <ServiceFactory>().Use <ServiceFactory>(ctx => t => ctx.GetInstance(t));
                cfg.For <IMediator>().Use <Mediator>();
            });
            var mediator = container.GetInstance <IMediator>();

            PingException pingException = new PingException();

            await Should.ThrowAsync <NotImplementedException>(async() => await mediator.Send(pingException));
        }
Beispiel #7
0
        private bool TryResolveNameOrAddress(
            string targetNameOrAddress,
            out string resolvedTargetName,
            [NotNullWhen(true)]
            out IPAddress?targetAddress)
        {
            resolvedTargetName = targetNameOrAddress;

            IPHostEntry hostEntry;

            if (IPAddress.TryParse(targetNameOrAddress, out targetAddress))
            {
                if ((IPv4 && targetAddress.AddressFamily != AddressFamily.InterNetwork) ||
                    (IPv6 && targetAddress.AddressFamily != AddressFamily.InterNetworkV6))
                {
                    string message = StringUtil.Format(
                        TestConnectionResources.NoPingResult,
                        resolvedTargetName,
                        TestConnectionResources.TargetAddressAbsent);
                    Exception   pingException = new PingException(message, null);
                    ErrorRecord errorRecord   = new ErrorRecord(
                        pingException,
                        TestConnectionExceptionId,
                        ErrorCategory.ResourceUnavailable,
                        resolvedTargetName);
                    WriteError(errorRecord);
                    return(false);
                }

                if (ResolveDestination)
                {
                    hostEntry          = GetCancellableHostEntry(targetNameOrAddress);
                    resolvedTargetName = hostEntry.HostName;
                }
                else
                {
                    resolvedTargetName = targetAddress.ToString();
                }
            }
            else
            {
                try
                {
                    hostEntry = GetCancellableHostEntry(targetNameOrAddress);

                    if (ResolveDestination)
                    {
                        resolvedTargetName = hostEntry.HostName;
                        hostEntry          = GetCancellableHostEntry(hostEntry.HostName);
                    }
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    if (!Quiet.IsPresent)
                    {
                        string message = StringUtil.Format(
                            TestConnectionResources.NoPingResult,
                            resolvedTargetName,
                            TestConnectionResources.CannotResolveTargetName);
                        Exception   pingException = new PingException(message, ex);
                        ErrorRecord errorRecord   = new ErrorRecord(
                            pingException,
                            TestConnectionExceptionId,
                            ErrorCategory.ResourceUnavailable,
                            resolvedTargetName);
                        WriteError(errorRecord);
                    }

                    return(false);
                }

                if (IPv6 || IPv4)
                {
                    targetAddress = GetHostAddress(hostEntry);

                    if (targetAddress == null)
                    {
                        string message = StringUtil.Format(
                            TestConnectionResources.NoPingResult,
                            resolvedTargetName,
                            TestConnectionResources.TargetAddressAbsent);
                        Exception   pingException = new PingException(message, null);
                        ErrorRecord errorRecord   = new ErrorRecord(
                            pingException,
                            TestConnectionExceptionId,
                            ErrorCategory.ResourceUnavailable,
                            resolvedTargetName);
                        WriteError(errorRecord);
                        return(false);
                    }
                }
                else
                {
                    targetAddress = hostEntry.AddressList[0];
                }
            }

            return(true);
        }
Beispiel #8
0
        private void ProcessPing(string targetNameOrAddress)
        {
            if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress))
            {
                if (Quiet.IsPresent)
                {
                    WriteObject(false);
                }

                return;
            }

            bool quietResult = true;

            byte[] buffer = GetSendBuffer(BufferSize);

            PingReply   reply;
            PingOptions pingOptions = new PingOptions(MaxHops, DontFragment.IsPresent);
            int         timeout     = TimeoutSeconds * 1000;
            int         delay       = Delay * 1000;

            for (int i = 1; i <= Count; i++)
            {
                try
                {
                    reply = SendCancellablePing(targetAddress, timeout, buffer, pingOptions);
                }
                catch (PingException ex)
                {
                    string      message       = StringUtil.Format(TestConnectionResources.NoPingResult, resolvedTargetName, ex.Message);
                    Exception   pingException = new PingException(message, ex.InnerException);
                    ErrorRecord errorRecord   = new ErrorRecord(
                        pingException,
                        TestConnectionExceptionId,
                        ErrorCategory.ResourceUnavailable,
                        resolvedTargetName);
                    WriteError(errorRecord);

                    quietResult = false;
                    continue;
                }

                if (Quiet.IsPresent)
                {
                    // Return 'true' only if all pings have completed successfully.
                    quietResult &= reply.Status == IPStatus.Success;
                }
                else
                {
                    WriteObject(new PingStatus(
                                    Source,
                                    resolvedTargetName,
                                    reply,
                                    reply.RoundtripTime,
                                    buffer.Length,
                                    pingNum: (uint)i));
                }

                // Delay between pings, but not after last ping.
                if (i < Count && Delay > 0)
                {
                    Thread.Sleep(delay);
                }
            }

            if (Quiet.IsPresent)
            {
                WriteObject(quietResult);
            }
        }
Beispiel #9
0
        private void ProcessMTUSize(string targetNameOrAddress)
        {
            PingReply?reply, replyResult = null;

            if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress))
            {
                if (Quiet.IsPresent)
                {
                    WriteObject(-1);
                }

                return;
            }

            // Caution! Algorithm is sensitive to changing boundary values.
            int HighMTUSize    = 10000;
            int CurrentMTUSize = 1473;
            int LowMTUSize     = targetAddress.AddressFamily == AddressFamily.InterNetworkV6 ? 1280 : 68;
            int timeout        = TimeoutSeconds * 1000;

            try
            {
                PingOptions pingOptions = new PingOptions(MaxHops, true);
                int         retry       = 1;

                while (LowMTUSize < (HighMTUSize - 1))
                {
                    byte[] buffer = GetSendBuffer(CurrentMTUSize);

                    WriteDebug(StringUtil.Format(
                                   "LowMTUSize: {0}, CurrentMTUSize: {1}, HighMTUSize: {2}",
                                   LowMTUSize,
                                   CurrentMTUSize,
                                   HighMTUSize));

                    reply = SendCancellablePing(targetAddress, timeout, buffer, pingOptions);

                    if (reply.Status == IPStatus.PacketTooBig || reply.Status == IPStatus.TimedOut)
                    {
                        HighMTUSize = CurrentMTUSize;
                        retry       = 1;
                    }
                    else if (reply.Status == IPStatus.Success)
                    {
                        LowMTUSize  = CurrentMTUSize;
                        replyResult = reply;
                        retry       = 1;
                    }
                    else
                    {
                        // If the host didn't reply, try again up to the 'Count' value.
                        if (retry >= Count)
                        {
                            string message = StringUtil.Format(
                                TestConnectionResources.NoPingResult,
                                targetAddress,
                                reply.Status.ToString());
                            Exception   pingException = new PingException(message);
                            ErrorRecord errorRecord   = new ErrorRecord(
                                pingException,
                                TestConnectionExceptionId,
                                ErrorCategory.ResourceUnavailable,
                                targetAddress);
                            WriteError(errorRecord);
                            return;
                        }
                        else
                        {
                            retry++;
                            continue;
                        }
                    }

                    CurrentMTUSize = (LowMTUSize + HighMTUSize) / 2;

                    // Prevent DoS attack.
                    Thread.Sleep(100);
                }
            }
            catch (PingException ex)
            {
                string      message       = StringUtil.Format(TestConnectionResources.NoPingResult, targetAddress, ex.Message);
                Exception   pingException = new PingException(message, ex.InnerException);
                ErrorRecord errorRecord   = new ErrorRecord(
                    pingException,
                    TestConnectionExceptionId,
                    ErrorCategory.ResourceUnavailable,
                    targetAddress);
                WriteError(errorRecord);
                return;
            }

            if (Quiet.IsPresent)
            {
                WriteObject(CurrentMTUSize);
            }
            else
            {
                WriteObject(new PingMtuStatus(
                                Source,
                                resolvedTargetName,
                                replyResult ?? throw new ArgumentNullException(nameof(replyResult)),
                                CurrentMTUSize));
            }
        }
Beispiel #10
0
        private void ProcessTraceroute(string targetNameOrAddress)
        {
            byte[] buffer = GetSendBuffer(BufferSize);

            if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress))
            {
                if (!Quiet.IsPresent)
                {
                    WriteObject(false);
                }

                return;
            }

            int         currentHop  = 1;
            PingOptions pingOptions = new PingOptions(currentHop, DontFragment.IsPresent);
            PingReply   reply;
            PingReply   discoveryReply;
            int         timeout = TimeoutSeconds * 1000;
            Stopwatch   timer   = new Stopwatch();

            IPAddress hopAddress;

            do
            {
                pingOptions.Ttl = currentHop;

#if !UNIX
                // Get intermediate hop target. This needs to be done first, so that we can target it properly
                // and get useful responses.
                var  discoveryAttempts = 0;
                bool addressIsValid    = false;
                do
                {
                    discoveryReply = SendCancellablePing(targetAddress, timeout, buffer, pingOptions);
                    discoveryAttempts++;
                    addressIsValid = !(discoveryReply.Address.Equals(IPAddress.Any) ||
                                       discoveryReply.Address.Equals(IPAddress.IPv6Any));
                }while (discoveryAttempts <= DefaultTraceRoutePingCount && addressIsValid);

                // If we aren't able to get a valid address, just re-target the final destination of the trace.
                hopAddress = addressIsValid ? discoveryReply.Address : targetAddress;
#else
                // Unix Ping API returns nonsense "TimedOut" for ALL intermediate hops. No way around this
                // issue for traceroutes as we rely on information (intermediate addresses, etc.) that is
                // simply not returned to us by the API.
                // The only supported states on Unix seem to be Success and TimedOut. Workaround is to
                // keep targeting the final address; at the very least we will be able to tell the user
                // the required number of hops to reach the destination.
                hopAddress     = targetAddress;
                discoveryReply = SendCancellablePing(targetAddress, timeout, buffer, pingOptions);
#endif
                var hopAddressString = discoveryReply.Address.ToString();

                string routerName = hopAddressString;
                try
                {
                    if (!TryResolveNameOrAddress(hopAddressString, out routerName, out _))
                    {
                        routerName = hopAddressString;
                    }
                }
                catch
                {
                    // Swallow hostname resolve exceptions and continue with traceroute
                }

                // In traceroutes we don't use 'Count' parameter.
                // If we change 'DefaultTraceRoutePingCount' we should change 'ConsoleTraceRouteReply' resource string.
                for (uint i = 1; i <= DefaultTraceRoutePingCount; i++)
                {
                    try
                    {
                        reply = SendCancellablePing(hopAddress, timeout, buffer, pingOptions, timer);

                        if (!Quiet.IsPresent)
                        {
                            var status = new PingStatus(
                                Source,
                                routerName,
                                reply,
                                reply.Status == IPStatus.Success
                                    ? reply.RoundtripTime
                                    : timer.ElapsedMilliseconds,
                                buffer.Length,
                                pingNum: i);
                            WriteObject(new TraceStatus(
                                            currentHop,
                                            status,
                                            Source,
                                            resolvedTargetName,
                                            targetAddress));
                        }
                    }
                    catch (PingException ex)
                    {
                        string message = StringUtil.Format(
                            TestConnectionResources.NoPingResult,
                            resolvedTargetName,
                            ex.Message);
                        Exception   pingException = new PingException(message, ex.InnerException);
                        ErrorRecord errorRecord   = new ErrorRecord(
                            pingException,
                            TestConnectionExceptionId,
                            ErrorCategory.ResourceUnavailable,
                            resolvedTargetName);
                        WriteError(errorRecord);

                        continue;
                    }

                    // We use short delay because it is impossible DoS with trace route.
                    Thread.Sleep(50);
                    timer.Reset();
                }

                currentHop++;
            } while (currentHop <= MaxHops &&
                     (discoveryReply.Status == IPStatus.TtlExpired ||
                      discoveryReply.Status == IPStatus.TimedOut));

            if (Quiet.IsPresent)
            {
                WriteObject(currentHop <= MaxHops);
            }
            else if (currentHop > MaxHops)
            {
                var message = StringUtil.Format(
                    TestConnectionResources.MaxHopsExceeded,
                    resolvedTargetName,
                    MaxHops);
                var pingException = new PingException(message);
                WriteError(new ErrorRecord(
                               pingException,
                               TestConnectionExceptionId,
                               ErrorCategory.ConnectionError,
                               targetAddress));
            }
        }
Beispiel #11
0
 protected virtual void OnPingException(PingExceptionArgs e)
 {
     PingException?.Invoke(this, e);
 }
        private bool InitProcessPing(string targetNameOrAddress, out string resolvedTargetName, out IPAddress targetAddress)
        {
            resolvedTargetName = targetNameOrAddress;

            IPHostEntry hostEntry;

            if (IPAddress.TryParse(targetNameOrAddress, out targetAddress))
            {
                if (ResolveDestination)
                {
                    hostEntry          = Dns.GetHostEntry(targetNameOrAddress);
                    resolvedTargetName = hostEntry.HostName;
                }
            }
            else
            {
                try
                {
                    hostEntry = Dns.GetHostEntry(targetNameOrAddress);

                    if (ResolveDestination)
                    {
                        resolvedTargetName = hostEntry.HostName;
                        hostEntry          = Dns.GetHostEntry(hostEntry.HostName);
                    }
                }
                catch (Exception ex)
                {
                    string message = StringUtil.Format(
                        TestConnectionResources.NoPingResult,
                        resolvedTargetName,
                        TestConnectionResources.CannotResolveTargetName);
                    Exception   pingException = new PingException(message, ex);
                    ErrorRecord errorRecord   = new ErrorRecord(
                        pingException,
                        TestConnectionExceptionId,
                        ErrorCategory.ResourceUnavailable,
                        resolvedTargetName);
                    WriteError(errorRecord);
                    return(false);
                }

                if (IPv6 || IPv4)
                {
                    AddressFamily addressFamily = IPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;

                    foreach (var address in hostEntry.AddressList)
                    {
                        if (address.AddressFamily == addressFamily)
                        {
                            targetAddress = address;
                            break;
                        }
                    }

                    if (targetAddress == null)
                    {
                        string message = StringUtil.Format(
                            TestConnectionResources.NoPingResult,
                            resolvedTargetName,
                            TestConnectionResources.TargetAddressAbsent);
                        Exception   pingException = new PingException(message, null);
                        ErrorRecord errorRecord   = new ErrorRecord(
                            pingException,
                            TestConnectionExceptionId,
                            ErrorCategory.ResourceUnavailable,
                            resolvedTargetName);
                        WriteError(errorRecord);
                        return(false);
                    }
                }
                else
                {
                    targetAddress = hostEntry.AddressList[0];
                }
            }

            return(true);
        }
        private void ProcessPing(string targetNameOrAddress)
        {
            string    resolvedTargetName;
            IPAddress targetAddress;

            if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress))
            {
                return;
            }

            if (!Continues.IsPresent)
            {
                WritePingHeader(resolvedTargetName, targetAddress.ToString());
            }

            bool quietResult = true;

            byte[] buffer = GetSendBuffer(BufferSize);

            Ping        sender = new Ping();
            PingReply   reply;
            PingOptions pingOptions = new PingOptions(MaxHops, DontFragment.IsPresent);
            PingReport  pingReport  = new PingReport(Source, resolvedTargetName);
            int         timeout     = TimeoutSeconds * 1000;
            int         delay       = Delay * 1000;

            for (int i = 1; i <= Count; i++)
            {
                try
                {
                    reply = sender.Send(targetAddress, timeout, buffer, pingOptions);
                }
                catch (PingException ex)
                {
                    string      message       = StringUtil.Format(TestConnectionResources.NoPingResult, resolvedTargetName, ex.Message);
                    Exception   pingException = new PingException(message, ex.InnerException);
                    ErrorRecord errorRecord   = new ErrorRecord(
                        pingException,
                        TestConnectionExceptionId,
                        ErrorCategory.ResourceUnavailable,
                        resolvedTargetName);
                    WriteError(errorRecord);

                    quietResult = false;
                    continue;
                }

                if (Continues.IsPresent)
                {
                    WriteObject(reply);
                }
                else
                {
                    if (Quiet.IsPresent)
                    {
                        // Return 'true' only if all pings have completed successfully.
                        quietResult &= reply.Status == IPStatus.Success;
                    }
                    else
                    {
                        pingReport.Replies.Add(reply);
                    }

                    WritePingProgress(reply);
                }

                // Delay between ping but not after last ping.
                if (i < Count && Delay > 0)
                {
                    Thread.Sleep(delay);
                }
            }

            if (!Continues.IsPresent)
            {
                WritePingFooter();
            }

            if (Quiet.IsPresent)
            {
                WriteObject(quietResult);
            }
            else
            {
                WriteObject(pingReport);
            }
        }
        private void ProcessMTUSize(string targetNameOrAddress)
        {
            PingReply reply, replyResult = null;
            string    resolvedTargetName;
            IPAddress targetAddress;

            if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress))
            {
                return;
            }

            WriteMTUSizeHeader(resolvedTargetName, targetAddress.ToString());

            // Cautious! Algorithm is sensitive to changing boundary values.
            int HighMTUSize    = 10000;
            int CurrentMTUSize = 1473;
            int LowMTUSize     = targetAddress.AddressFamily == AddressFamily.InterNetworkV6 ? 1280 : 68;
            int timeout        = TimeoutSeconds * 1000;

            try
            {
                Ping        sender      = new Ping();
                PingOptions pingOptions = new PingOptions(MaxHops, true);
                int         retry       = 1;

                while (LowMTUSize < (HighMTUSize - 1))
                {
                    byte[] buffer = GetSendBuffer(CurrentMTUSize);

                    WriteMTUSizeProgress(CurrentMTUSize, retry);

                    WriteDebug(StringUtil.Format(
                                   "LowMTUSize: {0}, CurrentMTUSize: {1}, HighMTUSize: {2}",
                                   LowMTUSize,
                                   CurrentMTUSize,
                                   HighMTUSize));

                    reply = sender.Send(targetAddress, timeout, buffer, pingOptions);

                    // Cautious! Algorithm is sensitive to changing boundary values.
                    if (reply.Status == IPStatus.PacketTooBig)
                    {
                        HighMTUSize = CurrentMTUSize;
                        retry       = 1;
                    }
                    else if (reply.Status == IPStatus.Success)
                    {
                        LowMTUSize  = CurrentMTUSize;
                        replyResult = reply;
                        retry       = 1;
                    }
                    else
                    {
                        // Target host don't reply - try again up to 'Count'.
                        if (retry >= Count)
                        {
                            string message = StringUtil.Format(
                                TestConnectionResources.NoPingResult,
                                targetAddress,
                                reply.Status.ToString());
                            Exception   pingException = new PingException(message);
                            ErrorRecord errorRecord   = new ErrorRecord(
                                pingException,
                                TestConnectionExceptionId,
                                ErrorCategory.ResourceUnavailable,
                                targetAddress);
                            WriteError(errorRecord);
                            return;
                        }
                        else
                        {
                            retry++;
                            continue;
                        }
                    }

                    CurrentMTUSize = (LowMTUSize + HighMTUSize) / 2;

                    // Prevent DoS attack.
                    Thread.Sleep(100);
                }
            }
            catch (PingException ex)
            {
                string      message       = StringUtil.Format(TestConnectionResources.NoPingResult, targetAddress, ex.Message);
                Exception   pingException = new PingException(message, ex.InnerException);
                ErrorRecord errorRecord   = new ErrorRecord(
                    pingException,
                    TestConnectionExceptionId,
                    ErrorCategory.ResourceUnavailable,
                    targetAddress);
                WriteError(errorRecord);
                return;
            }

            WriteMTUSizeFooter();

            if (Quiet.IsPresent)
            {
                WriteObject(CurrentMTUSize);
            }
            else
            {
                var res = PSObject.AsPSObject(replyResult);

                PSMemberInfo sourceProperty = new PSNoteProperty("Source", Source);
                res.Members.Add(sourceProperty);
                PSMemberInfo destinationProperty = new PSNoteProperty("Destination", targetNameOrAddress);
                res.Members.Add(destinationProperty);
                PSMemberInfo mtuSizeProperty = new PSNoteProperty("MTUSize", CurrentMTUSize);
                res.Members.Add(mtuSizeProperty);
                res.TypeNames.Insert(0, "PingReply#MTUSize");

                WriteObject(res);
            }
        }
        private void ProcessTraceroute(string targetNameOrAddress)
        {
            byte[] buffer = GetSendBuffer(BufferSize);

            string    resolvedTargetName;
            IPAddress targetAddress;

            if (!InitProcessPing(targetNameOrAddress, out resolvedTargetName, out targetAddress))
            {
                return;
            }

            WriteConsoleTraceRouteHeader(resolvedTargetName, targetAddress.ToString());

            TraceRouteResult traceRouteResult = new TraceRouteResult(Source, targetAddress, resolvedTargetName);

            int         currentHop  = 1;
            Ping        sender      = new Ping();
            PingOptions pingOptions = new PingOptions(currentHop, DontFragment.IsPresent);
            PingReply   reply       = null;
            int         timeout     = TimeoutSeconds * 1000;

            do
            {
                TraceRouteReply traceRouteReply = new TraceRouteReply();

                pingOptions.Ttl = traceRouteReply.Hop = currentHop;
                currentHop++;

                // In the specific case we don't use 'Count' property.
                // If we change 'DefaultTraceRoutePingCount' we should change 'ConsoleTraceRouteReply' resource string.
                for (int i = 1; i <= DefaultTraceRoutePingCount; i++)
                {
                    try
                    {
                        reply = sender.Send(targetAddress, timeout, buffer, pingOptions);

                        traceRouteReply.PingReplies.Add(reply);
                    }
                    catch (PingException ex)
                    {
                        string message = StringUtil.Format(
                            TestConnectionResources.NoPingResult,
                            resolvedTargetName,
                            ex.Message);
                        Exception   pingException = new PingException(message, ex.InnerException);
                        ErrorRecord errorRecord   = new ErrorRecord(
                            pingException,
                            TestConnectionExceptionId,
                            ErrorCategory.ResourceUnavailable,
                            resolvedTargetName);
                        WriteError(errorRecord);

                        continue;
                    }
                    catch
                    {
                        // Ignore host resolve exceptions.
                    }

                    // We use short delay because it is impossible DoS with trace route.
                    Thread.Sleep(200);
                }

                if (ResolveDestination && reply.Status == IPStatus.Success)
                {
                    traceRouteReply.ReplyRouterName = Dns.GetHostEntry(reply.Address).HostName;
                }

                traceRouteReply.ReplyRouterAddress = reply.Address;

                WriteTraceRouteProgress(traceRouteReply);

                traceRouteResult.Replies.Add(traceRouteReply);
            } while (reply != null &&
                     currentHop <= sMaxHops &&
                     (reply.Status == IPStatus.TtlExpired || reply.Status == IPStatus.TimedOut));

            WriteTraceRouteFooter();

            if (Quiet.IsPresent)
            {
                WriteObject(currentHop <= sMaxHops);
            }
            else
            {
                WriteObject(traceRouteResult);
            }
        }