コード例 #1
0
        public async Task SendPingAsyncWithIPAddressAndTimeoutAndBufferAndPingOptions_Unix(AddressFamily addressFamily)
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync(addressFamily);

            if (localIpAddress == null)
            {
                // No local address for given address family.
                return;
            }

            byte[] buffer = TestSettings.PayloadAsBytes;
            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, new PingOptions()),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);

                // Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
                if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
                {
                    Assert.Equal(buffer, pingReply.Buffer);
                }
                else
                {
                    Assert.Equal(Array.Empty <byte>(), pingReply.Buffer);
                }
            });
        }
コード例 #2
0
        public async Task SendPingAsync_InvalidArgs()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            Ping p = new Ping();

            // Null address
            AssertExtensions.Throws <ArgumentNullException>("address", () => { p.SendPingAsync((IPAddress)null); });
            AssertExtensions.Throws <ArgumentNullException>("hostNameOrAddress", () => { p.SendPingAsync((string)null); });
            AssertExtensions.Throws <ArgumentNullException>("address", () => { p.SendAsync((IPAddress)null, null); });
            AssertExtensions.Throws <ArgumentNullException>("hostNameOrAddress", () => { p.SendAsync((string)null, null); });
            AssertExtensions.Throws <ArgumentNullException>("address", () => { p.Send((IPAddress)null); });
            AssertExtensions.Throws <ArgumentNullException>("hostNameOrAddress", () => { p.Send((string)null); });

            // Invalid address
            AssertExtensions.Throws <ArgumentException>("address", () => { p.SendPingAsync(IPAddress.Any); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.SendPingAsync(IPAddress.IPv6Any); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.SendAsync(IPAddress.Any, null); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.SendAsync(IPAddress.IPv6Any, null); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.Send(IPAddress.Any); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.Send(IPAddress.IPv6Any); });

            // Negative timeout
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(localIpAddress, -1); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(TestSettings.LocalHost, -1); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.SendAsync(localIpAddress, -1, null); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.SendAsync(TestSettings.LocalHost, -1, null); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.Send(localIpAddress, -1); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.Send(TestSettings.LocalHost, -1); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.Send(localIpAddress, TimeSpan.FromMilliseconds(-1), default, default); });
コード例 #3
0
        public async Task SendPingAsyncWithIPAddressAndTimeout()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);
            });
        }
コード例 #4
0
        public async Task SendPingAsyncWithIPAddress_AddressAsString()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(localIpAddress.ToString()),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);
            });
        }
コード例 #5
0
        public async Task SendPingAsyncWithHostAndTimeoutAndBuffer()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            byte[] buffer = TestSettings.PayloadAsBytes;
            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);
                Assert.Equal(buffer, pingReply.Buffer);
            });
        }
コード例 #6
0
        public static async Task Sends_ReuseInstance_Hostname()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            using (Ping p = new Ping())
            {
                for (int i = 0; i < 3; i++)
                {
                    PingReply pingReply = p.Send(TestSettings.LocalHost);
                    PingResultValidator(pingReply, localIpAddress);
                }
            }
        }
コード例 #7
0
        public async Task SendPingAsyncWithIPAddressAndTimeoutAndBuffer()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            byte[] buffer = GetPingPayload(localIpAddress.AddressFamily);

            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);
                Assert.Equal(buffer, pingReply.Buffer);
            });
        }
コード例 #8
0
        public static async Task SendAsyncs_ReuseInstance_Hostname()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            using (Ping p = new Ping())
            {
                TaskCompletionSource <bool> tcs = null;
                PingCompletedEventArgs      ea  = null;
                p.PingCompleted += (s, e) =>
                {
                    ea = e;
                    tcs.TrySetResult(true);
                };
                Action reset = () =>
                {
                    ea  = null;
                    tcs = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);
                };

                // Several normal iterations
                for (int i = 0; i < 3; i++)
                {
                    reset();
                    p.SendAsync(TestSettings.LocalHost, null);
                    await tcs.Task;

                    Assert.NotNull(ea);
                    PingResultValidator(ea.Reply, localIpAddress);
                }

                // Several canceled iterations
                for (int i = 0; i < 3; i++)
                {
                    reset();
                    p.SendAsync(TestSettings.LocalHost, null);
                    p.SendAsyncCancel(); // will block until operation can be started again
                    await tcs.Task;

                    bool      cancelled = ea.Cancelled;
                    Exception error     = ea.Error;
                    PingReply reply     = ea.Reply;
                    Assert.True(cancelled ^ (error != null) ^ (reply != null),
                                "Cancelled: " + cancelled +
                                (error == null ? "" : (Environment.NewLine + "Error Message: " + error.Message + Environment.NewLine + "Error Inner Exception: " + error.InnerException)) +
                                (reply == null ? "" : (Environment.NewLine + "Reply Address: " + reply.Address + Environment.NewLine + "Reply Status: " + reply.Status)));
                }
            }
        }
コード例 #9
0
        public async Task SendPingAsyncWithIPAddressAndTimeoutAndBufferAndPingOptions()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            var options = new PingOptions();

            byte[] buffer = TestSettings.PayloadAsBytes;
            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, options),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);
                Assert.Equal(buffer, pingReply.Buffer);
                Assert.InRange(pingReply.RoundtripTime, 0, long.MaxValue);
            });
        }
コード例 #10
0
        public async Task SendPingAsync_InvalidArgs()
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            Ping p = new Ping();

            // Null address
            AssertExtensions.Throws <ArgumentNullException>("address", () => { p.SendPingAsync((IPAddress)null); });
            AssertExtensions.Throws <ArgumentNullException>("hostNameOrAddress", () => { p.SendPingAsync((string)null); });
            AssertExtensions.Throws <ArgumentNullException>("address", () => { p.SendAsync((IPAddress)null, null); });
            AssertExtensions.Throws <ArgumentNullException>("hostNameOrAddress", () => { p.SendAsync((string)null, null); });
            AssertExtensions.Throws <ArgumentNullException>("address", () => { p.Send((IPAddress)null); });
            AssertExtensions.Throws <ArgumentNullException>("hostNameOrAddress", () => { p.Send((string)null); });

            // Invalid address
            AssertExtensions.Throws <ArgumentException>("address", () => { p.SendPingAsync(IPAddress.Any); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.SendPingAsync(IPAddress.IPv6Any); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.SendAsync(IPAddress.Any, null); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.SendAsync(IPAddress.IPv6Any, null); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.Send(IPAddress.Any); });
            AssertExtensions.Throws <ArgumentException>("address", () => { p.Send(IPAddress.IPv6Any); });

            // Negative timeout
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(localIpAddress, -1); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(TestSettings.LocalHost, -1); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.SendAsync(localIpAddress, -1, null); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.SendAsync(TestSettings.LocalHost, -1, null); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.Send(localIpAddress, -1); });
            AssertExtensions.Throws <ArgumentOutOfRangeException>("timeout", () => { p.Send(TestSettings.LocalHost, -1); });

            // Null byte[]
            AssertExtensions.Throws <ArgumentNullException>("buffer", () => { p.SendPingAsync(localIpAddress, 0, null); });
            AssertExtensions.Throws <ArgumentNullException>("buffer", () => { p.SendPingAsync(TestSettings.LocalHost, 0, null); });
            AssertExtensions.Throws <ArgumentNullException>("buffer", () => { p.SendAsync(localIpAddress, 0, null, null); });
            AssertExtensions.Throws <ArgumentNullException>("buffer", () => { p.SendAsync(TestSettings.LocalHost, 0, null, null); });
            AssertExtensions.Throws <ArgumentNullException>("buffer", () => { p.Send(localIpAddress, 0, null); });
            AssertExtensions.Throws <ArgumentNullException>("buffer", () => { p.Send(TestSettings.LocalHost, 0, null); });

            // Too large byte[]
            AssertExtensions.Throws <ArgumentException>("buffer", () => { p.SendPingAsync(localIpAddress, 1, new byte[65501]); });
            AssertExtensions.Throws <ArgumentException>("buffer", () => { p.SendPingAsync(TestSettings.LocalHost, 1, new byte[65501]); });
            AssertExtensions.Throws <ArgumentException>("buffer", () => { p.SendAsync(localIpAddress, 1, new byte[65501], null); });
            AssertExtensions.Throws <ArgumentException>("buffer", () => { p.SendAsync(TestSettings.LocalHost, 1, new byte[65501], null); });
            AssertExtensions.Throws <ArgumentException>("buffer", () => { p.Send(localIpAddress, 1, new byte[65501]); });
            AssertExtensions.Throws <ArgumentException>("buffer", () => { p.Send(TestSettings.LocalHost, 1, new byte[65501]); });
        }
コード例 #11
0
        public async Task SendPingAsyncWithIPAddress(AddressFamily addressFamily)
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync(addressFamily);

            if (localIpAddress == null)
            {
                // No local address for given address family.
                return;
            }

            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(localIpAddress),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);
            });
        }
コード例 #12
0
        public async Task SendPingAsyncWithHostAndTtlAndFragmentPingOptions(bool fragment)
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            byte[] buffer = TestSettings.PayloadAsBytes;

            PingOptions options = new PingOptions();

            options.Ttl          = 32;
            options.DontFragment = fragment;

            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, options),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);
            });
        }
コード例 #13
0
        public async Task SendPingAsyncWithIPAddressAndTimeoutAndBufferAndPingOptions_Unix(AddressFamily addressFamily)
        {
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync(addressFamily);

            if (localIpAddress == null)
            {
                // No local address for given address family.
                return;
            }

            byte[] buffer = GetPingPayload(localIpAddress.AddressFamily);

            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, new PingOptions()),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);
                Assert.Equal(buffer, pingReply.Buffer);
            });
        }
コード例 #14
0
ファイル: PingTest.cs プロジェクト: criteo-forks/runtime
        public async Task SendPingAsyncWithIPAddressAndTimeoutAndBuffer_Unix()
        {
            byte[]    buffer         = TestSettings.PayloadAsBytes;
            IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();

            await SendBatchPingAsync(
                (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer),
                (pingReply) =>
            {
                PingResultValidator(pingReply, localIpAddress);

                // Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
                if (Capability.CanUseRawSockets(localIpAddress.AddressFamily) || PlatformDetection.IsOSXLike)
                {
                    Assert.Equal(buffer, pingReply.Buffer);
                }
                else
                {
                    Assert.Equal(Array.Empty <byte>(), pingReply.Buffer);
                }
            });
        }
コード例 #15
0
        [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests un-priviledged Ping support on Unix
        public static async Task PacketSizeIsRespected(int payloadSize)
        {
            IPAddress localAddress = await TestSettings.GetLocalIPAddressAsync();

            bool   ipv4        = localAddress.AddressFamily == AddressFamily.InterNetwork;
            string arguments   = UnixCommandLinePing.ConstructCommandLine(payloadSize, localAddress.ToString(), ipv4);
            string utilityPath = (localAddress.AddressFamily == AddressFamily.InterNetwork)
                ? UnixCommandLinePing.Ping4UtilityPath
                : UnixCommandLinePing.Ping6UtilityPath;

            var p = new Process();

            p.StartInfo.FileName        = utilityPath;
            p.StartInfo.Arguments       = arguments;
            p.StartInfo.UseShellExecute = false;

            p.StartInfo.RedirectStandardOutput = true;
            var stdOutLines = new List <string>();

            p.OutputDataReceived += new DataReceivedEventHandler(
                delegate(object sendingProcess, DataReceivedEventArgs outputLine) { stdOutLines.Add(outputLine.Data); });

            p.StartInfo.RedirectStandardError = true;
            var stdErrLines = new List <string>();

            p.ErrorDataReceived += new DataReceivedEventHandler(
                delegate(object sendingProcess, DataReceivedEventArgs errorLine) { stdErrLines.Add(errorLine.Data); });

            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            // There are multiple issues with ping6 in macOS 10.12 (Sierra), see https://github.com/dotnet/corefx/issues/26358.
            bool isPing6OnMacSierra = utilityPath.Equals(UnixCommandLinePing.Ping6UtilityPath) &&
                                      RuntimeInformation.IsOSPlatform(OSPlatform.OSX) &&
                                      !PlatformDetection.IsMacOsHighSierraOrHigher;

            string pingOutput;

            if (!p.WaitForExit(TestSettings.PingTimeout))
            {
                // Workaround known issues with ping6 in macOS 10.12
                if (isPing6OnMacSierra)
                {
                    return;
                }

                pingOutput = string.Join("\n", stdOutLines);
                string stdErr = string.Join("\n", stdErrLines);
                throw new Exception(
                          $"[{utilityPath} {arguments}] process did not exit in {TestSettings.PingTimeout} ms.\nStdOut:[{pingOutput}]\nStdErr:[{stdErr}]");
            }

            // Ensure standard output and error are flushed
            p.WaitForExit();

            pingOutput = string.Join("\n", stdOutLines);
            var exitCode = p.ExitCode;

            if (exitCode != 0)
            {
                // Workaround known issues with ping6 in macOS 10.12
                if (isPing6OnMacSierra)
                {
                    return;
                }

                string stdErr = string.Join("\n", stdErrLines);
                throw new Exception(
                          $"[{utilityPath} {arguments}] process exit code is {exitCode}.\nStdOut:[{pingOutput}]\nStdErr:[{stdErr}]");
            }

            try
            {
                // Validate that the returned data size is correct.
                // It should be equal to the bytes we sent plus the size of the ICMP header.
                int receivedBytes = ParseReturnedPacketSize(pingOutput);
                int expected      = Math.Max(16, payloadSize) + IcmpHeaderLengthInBytes;
                Assert.Equal(expected, receivedBytes);

                // Validate that we only sent one ping with the "-c 1" argument.
                int numPingsSent = ParseNumPingsSent(pingOutput);
                Assert.Equal(1, numPingsSent);

                long rtt = UnixCommandLinePing.ParseRoundTripTime(pingOutput);
                Assert.InRange(rtt, 0, long.MaxValue);
            }
            catch (Exception e)
            {
                string stdErr = string.Join("\n", stdErrLines);
                throw new Exception(
                          $"Parse error for [{utilityPath} {arguments}] process exit code is {exitCode}.\nStdOut:[{pingOutput}]\nStdErr:[{stdErr}]", e);
            }
        }
コード例 #16
0
        [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests un-priviledged Ping support on Unix
        public static async Task PacketSizeIsRespected(int payloadSize)
        {
            var stdOutLines = new List <string>();
            var stdErrLines = new List <string>();

            Process p = ConstructPingProcess(await TestSettings.GetLocalIPAddressAsync(), payloadSize, 1000);

            p.StartInfo.RedirectStandardOutput = true;
            p.OutputDataReceived += delegate(object sendingProcess, DataReceivedEventArgs outputLine)
            {
                stdOutLines.Add(outputLine.Data);
            };

            p.StartInfo.RedirectStandardError = true;
            p.ErrorDataReceived += delegate(object sendingProcess, DataReceivedEventArgs errorLine)
            {
                stdErrLines.Add(errorLine.Data);
            };

            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            string pingOutput;

            if (!p.WaitForExit(TestSettings.PingTimeout))
            {
                pingOutput = string.Join("\n", stdOutLines);
                string stdErr = string.Join("\n", stdErrLines);
                throw new Exception(
                          $"[{p.StartInfo.FileName} {p.StartInfo.Arguments}] process did not exit in {TestSettings.PingTimeout} ms.\nStdOut:[{pingOutput}]\nStdErr:[{stdErr}]");
            }

            // Ensure standard output and error are flushed
            p.WaitForExit();

            pingOutput = string.Join("\n", stdOutLines);
            var exitCode = p.ExitCode;

            if (exitCode != 0)
            {
                string stdErr = string.Join("\n", stdErrLines);
                throw new Exception(
                          $"[{p.StartInfo.FileName} {p.StartInfo.Arguments}] process exit code is {exitCode}.\nStdOut:[{pingOutput}]\nStdErr:[{stdErr}]");
            }

            try
            {
                // Validate that the returned data size is correct.
                // It should be equal to the bytes we sent plus the size of the ICMP header.
                int receivedBytes = ParseReturnedPacketSize(pingOutput);
                int expected      = Math.Max(16, payloadSize) + IcmpHeaderLengthInBytes;
                Assert.Equal(expected, receivedBytes);

                // Validate that we only sent one ping with the "-c 1" argument.
                int numPingsSent = ParseNumPingsSent(pingOutput);
                Assert.Equal(1, numPingsSent);

                long rtt = UnixCommandLinePing.ParseRoundTripTime(pingOutput);
                Assert.InRange(rtt, 0, long.MaxValue);
            }
            catch (Exception e)
            {
                string stdErr = string.Join("\n", stdErrLines);
                throw new Exception(
                          $"Parse error for [{p.StartInfo.FileName} {p.StartInfo.Arguments}] process exit code is {exitCode}.\nStdOut:[{pingOutput}]\nStdErr:[{stdErr}]", e);
            }
        }