forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPingTest.cs
More file actions
865 lines (749 loc) · 36.5 KB
/
Copy pathPingTest.cs
File metadata and controls
865 lines (749 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.DotNet.XUnitExtensions;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.NetworkInformation.Tests
{
public class PingTest
{
public readonly ITestOutputHelper _output;
private class FinalizingPing : Ping
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingPing();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
public PingTest(ITestOutputHelper output)
{
_output = output;
}
private void PingResultValidator(PingReply pingReply, IPAddress localIpAddress)
{
PingResultValidator(pingReply, new IPAddress[] { localIpAddress }, _output);
}
private void PingResultValidator(PingReply pingReply, IPAddress[] localIpAddresses) => PingResultValidator(pingReply, localIpAddresses, null);
private static void PingResultValidator(PingReply pingReply, IPAddress[] localIpAddresses, ITestOutputHelper output)
{
Assert.Equal(IPStatus.Success, pingReply.Status);
if (localIpAddresses.Any(addr => pingReply.Address.Equals(addr)))
{
// response did come from expected address. Test will pass.
return;
}
// We did not find response address in given list.
// Test is going to fail. Collect some more info.
if (output != null)
{
output.WriteLine($"Reply address {pingReply.Address} is not expected local address.");
foreach (IPAddress address in localIpAddresses)
{
output.WriteLine($"Local address {address}");
}
}
Assert.Contains(pingReply.Address, localIpAddresses); ///, "Reply address {pingReply.Address} is not expected local address.");
}
private static byte[] GetPingPayload(AddressFamily addressFamily)
// On Unix, Non-root processes cannot send arbitrary data in the ping packet payload
=> Capability.CanUseRawSockets(addressFamily) || PlatformDetection.IsOSXLike
? TestSettings.PayloadAsBytes
: Array.Empty<byte>();
public static bool DoesNotUsePingUtility => !UsesPingUtility;
public static bool UsesPingUtility => (OperatingSystem.IsLinux() || OperatingSystem.IsAndroid()) && !Capability.CanUseRawSockets(TestSettings.GetLocalIPAddress().AddressFamily);
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
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]); });
}
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public void SendPingWithIPAddress(AddressFamily addressFamily)
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
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);
});
}
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public void SendPingWithIPAddress_AddressAsString(AddressFamily addressFamily)
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
SendBatchPing(
(ping) => ping.Send(localIpAddress.ToString()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task SendPingAsyncWithIPAddress_AddressAsString()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(localIpAddress.ToString()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Fact]
public void SendPingWithIPAddressAndTimeout()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task SendPingAsyncWithIPAddressAndTimeout()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
});
}
[Fact]
public void SendPingWithIPAddressAndTimeoutAndBuffer()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
byte[] buffer = GetPingPayload(localIpAddress.AddressFamily);
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
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);
});
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
public void SendPingWithIPAddressAndTimeoutAndBufferAndPingOptions()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
var options = new PingOptions();
byte[] buffer = TestSettings.PayloadAsBytes;
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout, buffer, options),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
Assert.InRange(pingReply.RoundtripTime, 0, long.MaxValue);
});
}
[PlatformSpecific(TestPlatforms.Windows)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
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);
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public void SendPingWithIPAddressAndTimeoutAndBufferAndPingOptions_Unix(AddressFamily addressFamily)
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
byte[] buffer = GetPingPayload(localIpAddress.AddressFamily);
SendBatchPing(
(ping) => ping.Send(localIpAddress, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
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);
});
}
[Fact]
public void SendPingWithHost()
{
IPAddress[] localIpAddresses = TestSettings.GetLocalIPAddresses();
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddresses);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task SendPingAsyncWithHost()
{
IPAddress[] localIpAddresses = await TestSettings.GetLocalIPAddressesAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddresses);
});
}
[Fact]
public void SendPingWithHostAndTimeout()
{
IPAddress[] localIpAddresses = TestSettings.GetLocalIPAddresses();
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddresses);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task SendPingAsyncWithHostAndTimeout()
{
IPAddress[] localIpAddresses = await TestSettings.GetLocalIPAddressesAsync();
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddresses);
});
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/64963", TestPlatforms.OSX)]
public void SendPingWithHostAndTimeoutAndBuffer()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
byte[] buffer = GetPingPayload(localIpAddress.AddressFamily);
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/64963", TestPlatforms.OSX)]
public async Task SendPingAsyncWithHostAndTimeoutAndBuffer()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
byte[] buffer = GetPingPayload(localIpAddress.AddressFamily);
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/64963", TestPlatforms.OSX)]
public void SendPingWithHostAndTimeoutAndBufferAndPingOptions()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
byte[] buffer = GetPingPayload(localIpAddress.AddressFamily);
SendBatchPing(
(ping) => ping.Send(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[ActiveIssue("https://github.com/dotnet/runtime/issues/64963", TestPlatforms.OSX)]
public async Task SendPingAsyncWithHostAndTimeoutAndBufferAndPingOptions()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddressAsync();
byte[] buffer = GetPingPayload(localIpAddress.AddressFamily);
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
[ConditionalFact(nameof(DoesNotUsePingUtility))]
public async Task SendPingWithIPAddressAndBigSize()
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress();
using (Ping p = new Ping())
{
// Assert.DoesNotThrow
PingReply pingReply = await p.SendPingAsync(localIpAddress, TestSettings.PingTimeout, new byte[10001]);
// Depending on platform the call may either succeed, report timeout or report too big packet. It
// should not throw wrapped SocketException though which is what this test guards.
//
// On Windows 10 the maximum ping size seems essentially limited to 65500 bytes and thus any buffer
// size on the loopback ping succeeds. On macOS anything bigger than 8184 will report packet too
// big error.
if (OperatingSystem.IsMacOS())
{
Assert.Equal(IPStatus.PacketTooBig, pingReply.Status);
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task SendPings_ReuseInstance_Hostname()
{
IPAddress[] localIpAddresses = await TestSettings.GetLocalIPAddressesAsync();
using (Ping p = new Ping())
{
for (int i = 0; i < 3; i++)
{
PingReply pingReply = await p.SendPingAsync(TestSettings.LocalHost);
PingResultValidator(pingReply, localIpAddresses);
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task Sends_ReuseInstance_Hostname()
{
IPAddress[] localIpAddresses = await TestSettings.GetLocalIPAddressesAsync();
using (Ping p = new Ping())
{
for (int i = 0; i < 3; i++)
{
PingReply pingReply = p.Send(TestSettings.LocalHost);
PingResultValidator(pingReply, localIpAddresses);
}
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public async Task SendAsyncs_ReuseInstance_Hostname()
{
IPAddress[] localIpAddresses = await TestSettings.GetLocalIPAddressesAsync();
using (Ping p = new Ping())
{
TaskCompletionSource tcs = null;
PingCompletedEventArgs ea = null;
p.PingCompleted += (s, e) =>
{
ea = e;
tcs.TrySetResult();
};
Action reset = () =>
{
ea = null;
tcs = new TaskCompletionSource(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, localIpAddresses);
}
// 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)));
}
}
}
[Fact]
public static void Ping_DisposeAfterSend_Success()
{
Ping p = new Ping();
p.Send(TestSettings.LocalHost);
p.Dispose();
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
public static async Task PingAsync_DisposeAfterSend_Success()
{
Ping p = new Ping();
await p.SendPingAsync(TestSettings.LocalHost);
p.Dispose();
}
[Fact]
public static void Ping_DisposeMultipletimes_Success()
{
Ping p = new Ping();
p.Dispose();
p.Dispose();
}
[Fact]
public static void Ping_SendAfterDispose_ThrowsSynchronously()
{
Ping p = new Ping();
p.Dispose();
Assert.Throws<ObjectDisposedException>(() => { p.Send(TestSettings.LocalHost); });
}
[Fact]
public static void PingAsync_SendAfterDispose_ThrowsSynchronously()
{
Ping p = new Ping();
p.Dispose();
Assert.Throws<ObjectDisposedException>(() => { p.SendPingAsync(TestSettings.LocalHost); });
}
private static readonly int s_pingcount = 4;
private static void SendBatchPing(Func<Ping, PingReply> sendPing, Action<PingReply> pingResultValidator)
{
for (int i = 0; i < s_pingcount; i++)
{
SendPing(sendPing, pingResultValidator);
}
}
private static Task SendBatchPingAsync(Func<Ping, Task<PingReply>> sendPing, Action<PingReply> pingResultValidator)
{
// create several concurrent pings
Task[] pingTasks = new Task[s_pingcount];
for (int i = 0; i < s_pingcount; i++)
{
pingTasks[i] = SendPingAsync(sendPing, pingResultValidator);
}
return Task.WhenAll(pingTasks);
}
private static void SendPing(Func<Ping, PingReply> sendPing, Action<PingReply> pingResultValidator)
{
var pingResult = sendPing(new Ping());
pingResultValidator(pingResult);
}
private static async Task SendPingAsync(Func<Ping, Task<PingReply>> sendPing, Action<PingReply> pingResultValidator)
{
var pingResult = await sendPing(new Ping());
pingResultValidator(pingResult);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsPreciseGcSupported))]
public void CanBeFinalized()
{
FinalizingPing.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingPing.WasFinalized);
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[InlineData(true)]
[InlineData(false)]
public async Task SendPingAsyncWithHostAndTtlAndFragmentPingOptions(bool fragment)
{
IPAddress[] localIpAddresses = await TestSettings.GetLocalIPAddressesAsync();
byte[] buffer = GetPingPayload(localIpAddresses[0].AddressFamily);
PingOptions options = new PingOptions();
options.Ttl = 32;
options.DontFragment = fragment;
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, options),
(pingReply) =>
{
PingResultValidator(pingReply, localIpAddresses);
});
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))]
[OuterLoop] // Depends on external host and assumption that network respects and does not change TTL
public async Task SendPingToExternalHostWithLowTtlTest()
{
string host = System.Net.Test.Common.Configuration.Ping.PingHost;
PingReply pingReply;
PingOptions options = new PingOptions();
bool reachable = false;
Ping ping = new Ping();
for (int i = 0; i < s_pingcount; i++)
{
pingReply = await ping.SendPingAsync(host, TestSettings.PingTimeout, TestSettings.PayloadAsBytesShort);
if (pingReply.Status == IPStatus.Success)
{
reachable = true;
break;
}
}
if (!reachable)
{
throw new SkipTestException($"Host {host} is not reachable. Skipping test.");
}
options.Ttl = 1;
// This should always fail unless host is one IP hop away.
pingReply = await ping.SendPingAsync(host, TestSettings.PingTimeout, TestSettings.PayloadAsBytesShort, options);
Assert.True(pingReply.Status == IPStatus.TimeExceeded || pingReply.Status == IPStatus.TtlExpired);
Assert.NotEqual(IPAddress.Any, pingReply.Address);
}
[Fact]
[OuterLoop]
public void Ping_TimedOut_Sync_Success()
{
var sender = new Ping();
PingReply reply = sender.Send(TestSettings.UnreachableAddress);
Assert.Equal(IPStatus.TimedOut, reply.Status);
}
[Fact]
[OuterLoop]
public async Task Ping_TimedOut_EAP_Success()
{
var sender = new Ping();
sender.PingCompleted += (s, e) =>
{
var tcs = (TaskCompletionSource<PingReply>)e.UserState;
if (e.Cancelled)
{
tcs.TrySetCanceled();
}
else if (e.Error != null)
{
tcs.TrySetException(e.Error);
}
else
{
tcs.TrySetResult(e.Reply);
}
};
var tcs = new TaskCompletionSource<PingReply>();
sender.SendAsync(TestSettings.UnreachableAddress, tcs);
PingReply reply = await tcs.Task;
Assert.Equal(IPStatus.TimedOut, reply.Status);
}
[Fact]
[OuterLoop]
public async Task Ping_TimedOut_TAP_Success()
{
var sender = new Ping();
PingReply reply = await sender.SendPingAsync(TestSettings.UnreachableAddress);
Assert.Equal(IPStatus.TimedOut, reply.Status);
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
[OuterLoop] // Depends on sudo
public void SendPingWithIPAddressAndTimeoutAndBufferAndPingOptions_ElevatedUnix(AddressFamily addressFamily)
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
_output.WriteLine($"pinging '{localIpAddress}'");
RemoteExecutor.Invoke(address =>
{
byte[] buffer = TestSettings.PayloadAsBytes;
SendBatchPing(
(ping) => ping.Send(address, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
PingResultValidator(pingReply, new IPAddress[] { IPAddress.Parse(address) }, null);
Assert.Equal(buffer, pingReply.Buffer);
});
}, localIpAddress.ToString(), new RemoteInvokeOptions { RunAsSudo = true }).Dispose();
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[InlineData(AddressFamily.InterNetwork, "ja_JP.UTF8", null, null)]
[InlineData(AddressFamily.InterNetwork, "en_US.UTF8", "ja_JP.UTF8", null)]
[InlineData(AddressFamily.InterNetwork, "en_US.UTF8", null, "ja_JP.UTF8")]
[InlineData(AddressFamily.InterNetworkV6, "ja_JP.UTF8", null, null)]
[InlineData(AddressFamily.InterNetworkV6, "en_US.UTF8", "ja_JP.UTF8", null)]
[InlineData(AddressFamily.InterNetworkV6, "en_US.UTF8", null, "ja_JP.UTF8")]
public void SendPing_LocaleEnvVarsMustBeIgnored(AddressFamily addressFamily, string envVar_LANG, string envVar_LC_MESSAGES, string envVar_LC_ALL)
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
var remoteInvokeStartInfo = new ProcessStartInfo();
remoteInvokeStartInfo.EnvironmentVariables["LANG"] = envVar_LANG;
remoteInvokeStartInfo.EnvironmentVariables["LC_MESSAGES"] = envVar_LC_MESSAGES;
remoteInvokeStartInfo.EnvironmentVariables["LC_ALL"] = envVar_LC_ALL;
RemoteExecutor.Invoke(address =>
{
SendBatchPing(
(ping) => ping.Send(address, TestSettings.PingTimeout),
(pingReply) =>
{
PingResultValidator(pingReply, new IPAddress[] { IPAddress.Parse(address) }, null);
});
}, localIpAddress.ToString(), new RemoteInvokeOptions { StartInfo = remoteInvokeStartInfo }).Dispose();
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[InlineData(AddressFamily.InterNetwork, "ja_JP.UTF8", null, null)]
[InlineData(AddressFamily.InterNetwork, "en_US.UTF8", "ja_JP.UTF8", null)]
[InlineData(AddressFamily.InterNetwork, "en_US.UTF8", null, "ja_JP.UTF8")]
[InlineData(AddressFamily.InterNetworkV6, "ja_JP.UTF8", null, null)]
[InlineData(AddressFamily.InterNetworkV6, "en_US.UTF8", "ja_JP.UTF8", null)]
[InlineData(AddressFamily.InterNetworkV6, "en_US.UTF8", null, "ja_JP.UTF8")]
public void SendPingAsync_LocaleEnvVarsMustBeIgnored(AddressFamily addressFamily, string envVar_LANG, string envVar_LC_MESSAGES, string envVar_LC_ALL)
{
IPAddress localIpAddress = TestSettings.GetLocalIPAddress(addressFamily);
if (localIpAddress == null)
{
// No local address for given address family.
return;
}
var remoteInvokeStartInfo = new ProcessStartInfo();
remoteInvokeStartInfo.EnvironmentVariables["LANG"] = envVar_LANG;
remoteInvokeStartInfo.EnvironmentVariables["LC_MESSAGES"] = envVar_LC_MESSAGES;
remoteInvokeStartInfo.EnvironmentVariables["LC_ALL"] = envVar_LC_ALL;
RemoteExecutor.Invoke(async address =>
{
await SendBatchPingAsync(
(ping) => ping.SendPingAsync(address),
(pingReply) =>
{
PingResultValidator(pingReply, new IPAddress[] { IPAddress.Parse(address) }, null);
});
}, localIpAddress.ToString(), new RemoteInvokeOptions { StartInfo = remoteInvokeStartInfo }).Dispose();
}
[ConditionalFact(nameof(UsesPingUtility))]
public void SendPing_CustomPayload_InsufficientPrivileges_Throws()
{
IPAddress[] localIpAddresses = TestSettings.GetLocalIPAddresses();
byte[] buffer = TestSettings.PayloadAsBytes;
Ping ping = new Ping();
Assert.Throws<PlatformNotSupportedException>(() => ping.Send(TestSettings.LocalHost, TestSettings.PingTimeout, buffer));
}
[ConditionalFact(nameof(UsesPingUtility))]
public async Task SendPingAsync_CustomPayload_InsufficientPrivileges_Throws()
{
IPAddress[] localIpAddresses = TestSettings.GetLocalIPAddresses();
byte[] buffer = TestSettings.PayloadAsBytes;
Ping ping = new Ping();
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer));
}
}
}