/
Ping.cs
767 lines (687 loc) · 40.7 KB
/
Ping.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.NetworkInformation
{
public partial class Ping : Component
{
private const int DefaultSendBufferSize = 32; // Same as ping.exe on Windows.
private const int DefaultTimeout = 5000; // 5 seconds: same as ping.exe on Windows.
private const int MaxBufferSize = 65500; // Artificial constraint due to win32 api limitations.
private readonly ManualResetEventSlim _lockObject = new ManualResetEventSlim(initialState: true); // doubles as the ability to wait on the current operation
private SendOrPostCallback? _onPingCompletedDelegate;
private bool _disposeRequested;
private byte[]? _defaultSendBuffer;
private CancellationTokenSource? _timeoutOrCancellationSource;
// Used to differentiate between timeout and cancellation when _timeoutOrCancellationSource triggers
private bool _canceled;
// Thread safety:
private const int Free = 0;
private const int InProgress = 1;
private new const int Disposed = 2;
private int _status = Free;
public Ping()
{
// This class once inherited a finalizer. For backward compatibility it has one so that
// any derived class that depends on it will see the behaviour expected. Since it is
// not used by this class itself, suppress it immediately if this is not an instance
// of a derived class it doesn't suffer the GC burden of finalization.
if (GetType() == typeof(Ping))
{
GC.SuppressFinalize(this);
}
}
private void CheckArgs(int timeout, byte[] buffer)
{
ObjectDisposedException.ThrowIf(_disposeRequested, this);
ArgumentNullException.ThrowIfNull(buffer);
if (buffer.Length > MaxBufferSize)
{
throw new ArgumentException(SR.net_invalidPingBufferSize, nameof(buffer));
}
ArgumentOutOfRangeException.ThrowIfNegative(timeout);
}
private void CheckArgs(IPAddress address, int timeout, byte[] buffer)
{
CheckArgs(timeout, buffer);
ArgumentNullException.ThrowIfNull(address);
// Check if address family is installed.
TestIsIpSupported(address);
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address));
}
}
private void CheckDisposed()
{
ObjectDisposedException.ThrowIf(_disposeRequested, this);
}
[MemberNotNull(nameof(_timeoutOrCancellationSource))]
private void CheckStart()
{
int currentStatus;
lock (_lockObject)
{
currentStatus = _status;
if (currentStatus == Free)
{
_timeoutOrCancellationSource ??= new();
_canceled = false;
_status = InProgress;
_lockObject.Reset();
return;
}
}
if (currentStatus == InProgress)
{
throw new InvalidOperationException(SR.net_inasync);
}
else
{
Debug.Assert(currentStatus == Disposed, $"Expected currentStatus == Disposed, got {currentStatus}");
throw new ObjectDisposedException(GetType().FullName);
}
}
private static IPAddress GetAddressSnapshot(IPAddress address)
{
IPAddress addressSnapshot = address.AddressFamily == AddressFamily.InterNetwork ?
#pragma warning disable CS0618 // IPAddress.Address is obsoleted, but it's the most efficient way to get the Int32 IPv4 address
new IPAddress(address.Address) :
#pragma warning restore CS0618
new IPAddress(address.GetAddressBytes(), address.ScopeId);
return addressSnapshot;
}
private void Finish()
{
lock (_lockObject)
{
Debug.Assert(_status == InProgress, $"Invalid status: {_status}");
_status = Free;
if (!_timeoutOrCancellationSource!.TryReset())
{
_timeoutOrCancellationSource = null;
}
_lockObject.Set();
}
if (_disposeRequested)
{
InternalDispose();
}
}
private void InternalDispose()
{
_disposeRequested = true;
lock (_lockObject)
{
if (_status != Free)
{
// Already disposed, or Finish will call Dispose again once Free.
return;
}
_status = Disposed;
}
_timeoutOrCancellationSource?.Dispose();
InternalDisposeCore();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Only on explicit dispose. Otherwise, the GC can cleanup everything else.
InternalDispose();
}
}
public event PingCompletedEventHandler? PingCompleted;
protected void OnPingCompleted(PingCompletedEventArgs e)
{
PingCompleted?.Invoke(this, e);
}
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the specified computer,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="hostNameOrAddress">
/// A <see cref="string"/> that identifies the computer that is the destination for the ICMP echo message.
/// The value specified for this parameter can be a host name or a string representation of an IP address.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="hostNameOrAddress"/> is <see langword="null"/> or is an empty string ("").</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(string hostNameOrAddress)
{
return Send(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer);
}
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the specified computer,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="hostNameOrAddress">
/// A <see cref="string"/> that identifies the computer that is the destination for the ICMP echo message.
/// The value specified for this parameter can be a host name or a string representation of an IP address.
/// </param>
/// <param name="timeout">
/// An <see cref="int"/> value that specifies the maximum number of milliseconds (after sending the echo message) to wait for the ICMP echo reply message.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="hostNameOrAddress"/> is <see langword="null"/> or is an empty string ("").</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="timeout"/> is less than zero.</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(string hostNameOrAddress, int timeout)
{
return Send(hostNameOrAddress, timeout, DefaultSendBuffer);
}
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the computer that has the specified <see cref="IPAddress"/>,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="address">
/// An <see cref="IPAddress"/> that identifies the computer that is the destination for the ICMP echo message.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="address"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(IPAddress address)
{
return Send(address, DefaultTimeout, DefaultSendBuffer);
}
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the computer that has the specified <see cref="IPAddress"/>,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="address">
/// An <see cref="IPAddress"/> that identifies the computer that is the destination for the ICMP echo message.
/// </param>
/// <param name="timeout">
/// An <see cref="int"/> value that specifies the maximum number of milliseconds (after sending the echo message) to wait for the ICMP echo reply message.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="address"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="timeout"/> is less than zero.</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(IPAddress address, int timeout)
{
return Send(address, timeout, DefaultSendBuffer);
}
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the specified computer,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="hostNameOrAddress">
/// A <see cref="string"/> that identifies the computer that is the destination for the ICMP echo message.
/// The value specified for this parameter can be a host name or a string representation of an IP address.
/// </param>
/// <param name="timeout">
/// An <see cref="int"/> value that specifies the maximum number of milliseconds (after sending the echo message) to wait for the ICMP echo reply message.
/// </param>
/// <param name="buffer">
/// A <see cref="byte"/> array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message.
/// The array cannot contain more than 65,500 bytes.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="hostNameOrAddress"/> is <see langword="null"/> or is an empty string ("").</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="timeout"/> is less than zero.</exception>
/// <exception cref="ArgumentException">The <paramref name="buffer"/>'s size is greater than 65,500 bytes.</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer)
{
return Send(hostNameOrAddress, timeout, buffer, null);
}
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the computer that has the specified <see cref="IPAddress"/>,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="address">
/// An <see cref="IPAddress"/> that identifies the computer that is the destination for the ICMP echo message.
/// </param>
/// <param name="timeout">
/// An <see cref="int"/> value that specifies the maximum number of milliseconds (after sending the echo message) to wait for the ICMP echo reply message.
/// </param>
/// <param name="buffer">
/// A <see cref="byte"/> array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message.
/// The array cannot contain more than 65,500 bytes.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="address"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="timeout"/> is less than zero.</exception>
/// <exception cref="ArgumentException">The <paramref name="buffer"/>'s size is greater than 65,500 bytes.</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(IPAddress address, int timeout, byte[] buffer)
{
return Send(address, timeout, buffer, null);
}
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the specified computer,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="hostNameOrAddress">
/// A <see cref="string"/> that identifies the computer that is the destination for the ICMP echo message.
/// The value specified for this parameter can be a host name or a string representation of an IP address.
/// </param>
/// <param name="timeout">
/// An <see cref="int"/> value that specifies the maximum number of milliseconds (after sending the echo message) to wait for the ICMP echo reply message.
/// </param>
/// <param name="buffer">
/// A <see cref="byte"/> array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message.
/// The array cannot contain more than 65,500 bytes.
/// </param>
/// <param name="options">
/// A <see cref="PingOptions"/> object used to control fragmentation and Time-to-Live values for the ICMP echo message packet.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="hostNameOrAddress"/> is <see langword="null"/> or is an empty string ("").</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="timeout"/> is less than zero.</exception>
/// <exception cref="ArgumentException">The <paramref name="buffer"/>'s size is greater than 65,500 bytes.</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions? options)
{
if (string.IsNullOrEmpty(hostNameOrAddress))
{
throw new ArgumentNullException(nameof(hostNameOrAddress));
}
if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address))
{
return Send(address, timeout, buffer, options);
}
CheckArgs(timeout, buffer);
return GetAddressAndSend(hostNameOrAddress, timeout, buffer, options);
}
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the computer that has the specified <see cref="IPAddress"/>,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="address">
/// An <see cref="IPAddress"/> that identifies the computer that is the destination for the ICMP echo message.
/// </param>
/// <param name="timeout">
/// An <see cref="int"/> value that specifies the maximum number of milliseconds (after sending the echo message) to wait for the ICMP echo reply message.
/// </param>
/// <param name="buffer">
/// A <see cref="byte"/> array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message.
/// The array cannot contain more than 65,500 bytes.
/// </param>
/// <param name="options">
/// A <see cref="PingOptions"/> object used to control fragmentation and Time-to-Live values for the ICMP echo message packet.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="address"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="timeout"/> is less than zero.</exception>
/// <exception cref="ArgumentException">The <paramref name="buffer"/>'s size is greater than 65,500 bytes.</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(IPAddress address, int timeout, byte[] buffer, PingOptions? options)
{
CheckArgs(address, timeout, buffer);
// Need to snapshot the address here, so we're sure that it's not changed between now
// and the operation, and to be sure that IPAddress.ToString() is called and not some override.
IPAddress addressSnapshot = GetAddressSnapshot(address);
CheckStart();
try
{
return SendPingCore(addressSnapshot, buffer, timeout, options);
}
catch (Exception e) when (e is not PlatformNotSupportedException)
{
throw new PingException(SR.net_ping, e);
}
finally
{
Finish();
}
}
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the computer that has the specified <see cref="IPAddress"/>,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="address">
/// An <see cref="IPAddress"/> that identifies the computer that is the destination for the ICMP echo message.
/// </param>
/// <param name="timeout">
/// A value that specifies the maximum amount of time (after sending the echo message) to wait for the ICMP echo reply message.
/// </param>
/// <param name="buffer">
/// A <see cref="byte"/> array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message.
/// The array cannot contain more than 65,500 bytes.
/// </param>
/// <param name="options">
/// A <see cref="PingOptions"/> object used to control fragmentation and Time-to-Live values for the ICMP echo message packet.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="address"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="timeout"/> represents a time less than zero milliseconds or greater than <see cref="int.MaxValue"/> milliseconds.</exception>
/// <exception cref="ArgumentException">The <paramref name="buffer"/>'s size is greater than 65,500 bytes.</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(IPAddress address, TimeSpan timeout, byte[]? buffer = null, PingOptions? options = null) =>
Send(address, ToTimeoutMilliseconds(timeout), buffer ?? DefaultSendBuffer, options);
/// <summary>
/// Attempts to send an Internet Control Message Protocol (ICMP) echo message to the specified computer,
/// and receive a corresponding ICMP echo reply message from that computer.
/// </summary>
/// <param name="hostNameOrAddress">
/// A <see cref="string"/> that identifies the computer that is the destination for the ICMP echo message.
/// The value specified for this parameter can be a host name or a string representation of an IP address.
/// </param>
/// <param name="timeout">
/// A value that specifies the maximum amount of time (after sending the echo message) to wait for the ICMP echo reply message.
/// </param>
/// <param name="buffer">
/// A <see cref="byte"/> array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message.
/// The array cannot contain more than 65,500 bytes.
/// </param>
/// <param name="options">
/// A <see cref="PingOptions"/> object used to control fragmentation and Time-to-Live values for the ICMP echo message packet.
/// </param>
/// <returns>
/// A <see cref="PingReply"/> object that provides information about the ICMP echo reply message, if one was received,
/// or provides the reason for the failure, if no message was received.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="hostNameOrAddress"/> is <see langword="null"/> or is an empty string ("").</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="timeout"/> represents a time less than zero milliseconds or greater than <see cref="int.MaxValue"/> milliseconds.</exception>
/// <exception cref="ArgumentException">The <paramref name="buffer"/>'s size is greater than 65,500 bytes.</exception>
/// <exception cref="InvalidOperationException">A call to SendAsync is in progress.</exception>
/// <exception cref="PingException">An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.</exception>
/// <exception cref="ObjectDisposedException">This object has been disposed.</exception>
public PingReply Send(string hostNameOrAddress, TimeSpan timeout, byte[]? buffer = null,
PingOptions? options = null) => Send(hostNameOrAddress, ToTimeoutMilliseconds(timeout), buffer ?? DefaultSendBuffer, options);
public void SendAsync(string hostNameOrAddress, object? userToken)
{
SendAsync(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer, userToken);
}
public void SendAsync(string hostNameOrAddress, int timeout, object? userToken)
{
SendAsync(hostNameOrAddress, timeout, DefaultSendBuffer, userToken);
}
public void SendAsync(IPAddress address, object? userToken)
{
SendAsync(address, DefaultTimeout, DefaultSendBuffer, userToken);
}
public void SendAsync(IPAddress address, int timeout, object? userToken)
{
SendAsync(address, timeout, DefaultSendBuffer, userToken);
}
public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, object? userToken)
{
SendAsync(hostNameOrAddress, timeout, buffer, null, userToken);
}
public void SendAsync(IPAddress address, int timeout, byte[] buffer, object? userToken)
{
SendAsync(address, timeout, buffer, null, userToken);
}
public void SendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions? options, object? userToken)
{
TranslateTaskToEap(userToken, SendPingAsync(hostNameOrAddress, timeout, buffer, options));
}
public void SendAsync(IPAddress address, int timeout, byte[] buffer, PingOptions? options, object? userToken)
{
TranslateTaskToEap(userToken, SendPingAsync(address, timeout, buffer, options));
}
private void TranslateTaskToEap(object? userToken, Task<PingReply> pingTask)
{
pingTask.ContinueWith((t, state) =>
{
var asyncOp = (AsyncOperation)state!;
var e = new PingCompletedEventArgs(t.IsCompletedSuccessfully ? t.Result : null, t.Exception, t.IsCanceled, asyncOp.UserSuppliedState);
SendOrPostCallback callback = _onPingCompletedDelegate ??= new SendOrPostCallback(o => { OnPingCompleted((PingCompletedEventArgs)o!); });
asyncOp.PostOperationCompleted(callback, e);
}, AsyncOperationManager.CreateOperation(userToken), CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
public Task<PingReply> SendPingAsync(IPAddress address)
{
return SendPingAsync(address, DefaultTimeout, DefaultSendBuffer, null);
}
public Task<PingReply> SendPingAsync(string hostNameOrAddress)
{
return SendPingAsync(hostNameOrAddress, DefaultTimeout, DefaultSendBuffer, null);
}
public Task<PingReply> SendPingAsync(IPAddress address, int timeout)
{
return SendPingAsync(address, timeout, DefaultSendBuffer, null);
}
public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout)
{
return SendPingAsync(hostNameOrAddress, timeout, DefaultSendBuffer, null);
}
public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer)
{
return SendPingAsync(address, timeout, buffer, null);
}
public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer)
{
return SendPingAsync(hostNameOrAddress, timeout, buffer, null);
}
public Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions? options)
{
return SendPingAsync(address, timeout, buffer, options, CancellationToken.None);
}
/// <summary>
/// Sends an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the computer that has the specified
/// <see cref="IPAddress"/>, and receives a corresponding ICMP echo reply message from that computer as an asynchronous operation. This
/// overload allows you to specify a time-out value for the operation, a buffer to use for send and receive, control fragmentation and
/// Time-to-Live values, and a <see cref="CancellationToken"/> for the ICMP echo message packet.
/// </summary>
/// <param name="address">An IP address that identifies the computer that is the destination for the ICMP echo message.</param>
/// <param name="timeout">The amount of time (after sending the echo message) to wait for the ICMP echo reply message.</param>
/// <param name="buffer">
/// A <see cref="byte"/> array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message.
/// The array cannot contain more than 65,500 bytes.
/// </param>
/// <param name="options">A <see cref="PingOptions"/> object used to control fragmentation and Time-to-Live values for the ICMP echo message packet.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<PingReply> SendPingAsync(IPAddress address, TimeSpan timeout, byte[]? buffer = null, PingOptions? options = null, CancellationToken cancellationToken = default)
{
return SendPingAsync(address, ToTimeoutMilliseconds(timeout), buffer ?? DefaultSendBuffer, options, cancellationToken);
}
private Task<PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions? options, CancellationToken cancellationToken)
{
CheckArgs(address, timeout, buffer);
return SendPingAsyncInternal(
// Need to snapshot the address here, so we're sure that it's not changed between now
// and the operation, and to be sure that IPAddress.ToString() is called and not some override.
GetAddressSnapshot(address),
static (address, cancellationToken) => new ValueTask<IPAddress>(address),
timeout,
buffer,
options,
cancellationToken);
}
public Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions? options)
{
return SendPingAsync(hostNameOrAddress, timeout, buffer, options, CancellationToken.None);
}
/// <summary>
/// Sends an Internet Control Message Protocol (ICMP) echo message with the specified data buffer to the specified computer, and
/// receives a corresponding ICMP echo reply message from that computer as an asynchronous operation. This overload allows you to
/// specify a time-out value for the operation, a buffer to use for send and receive, control fragmentation and Time-to-Live values,
/// and a <see cref="CancellationToken"/> for the ICMP echo message packet.
/// </summary>
/// <param name="hostNameOrAddress">
/// The computer that is the destination for the ICMP echo message. The value specified for this parameter can be a host name or a
/// string representation of an IP address.
/// </param>
/// <param name="timeout">The amount of time (after sending the echo message) to wait for the ICMP echo reply message.</param>
/// <param name="buffer">
/// A <see cref="byte"/> array that contains data to be sent with the ICMP echo message and returned in the ICMP echo reply message.
/// The array cannot contain more than 65,500 bytes.
/// </param>
/// <param name="options">A <see cref="PingOptions"/> object used to control fragmentation and Time-to-Live values for the ICMP echo message packet.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<PingReply> SendPingAsync(string hostNameOrAddress, TimeSpan timeout, byte[]? buffer = null, PingOptions? options = null, CancellationToken cancellationToken = default)
{
return SendPingAsync(hostNameOrAddress, ToTimeoutMilliseconds(timeout), buffer ?? DefaultSendBuffer, options, cancellationToken);
}
private Task<PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions? options, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(hostNameOrAddress))
{
throw new ArgumentNullException(nameof(hostNameOrAddress));
}
if (IPAddress.TryParse(hostNameOrAddress, out IPAddress? address))
{
return SendPingAsync(address, timeout, buffer, options, cancellationToken);
}
CheckArgs(timeout, buffer);
return SendPingAsyncInternal(
hostNameOrAddress,
static async (hostName, cancellationToken) =>
(await Dns.GetHostAddressesAsync(hostName, cancellationToken).ConfigureAwait(false))[0],
timeout,
buffer,
options,
cancellationToken);
}
private static int ToTimeoutMilliseconds(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
ArgumentOutOfRangeException.ThrowIfLessThan(totalMilliseconds, -1, nameof(timeout));
ArgumentOutOfRangeException.ThrowIfGreaterThan(totalMilliseconds, int.MaxValue, nameof(timeout));
return (int)totalMilliseconds;
}
public void SendAsyncCancel()
{
lock (_lockObject)
{
if (!_lockObject.IsSet)
{
SetCanceled();
}
}
// As in the .NET Framework, synchronously wait for the in-flight operation to complete.
// If there isn't one in flight, this event will already be set.
_lockObject.Wait();
}
private void SetCanceled()
{
_canceled = true;
_timeoutOrCancellationSource?.Cancel();
}
private PingReply GetAddressAndSend(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions? options)
{
CheckStart();
try
{
IPAddress[] addresses = Dns.GetHostAddresses(hostNameOrAddress);
return SendPingCore(addresses[0], buffer, timeout, options);
}
catch (Exception e) when (e is not PlatformNotSupportedException)
{
throw new PingException(SR.net_ping, e);
}
finally
{
Finish();
}
}
private async Task<PingReply> SendPingAsyncInternal<TArg>(
TArg getAddressArg,
Func<TArg, CancellationToken, ValueTask<IPAddress>> getAddress,
int timeout,
byte[] buffer,
PingOptions? options,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
CheckStart();
try
{
using CancellationTokenRegistration _ = cancellationToken.UnsafeRegister(static state => ((Ping)state!).SetCanceled(), this);
IPAddress address = await getAddress(getAddressArg, _timeoutOrCancellationSource.Token).ConfigureAwait(false);
Task<PingReply> pingTask = SendPingAsyncCore(address, buffer, timeout, options);
// Note: we set the cancellation-based timeout only after resolving the address and initiating the ping with the
// intent that the timeout applies solely to the ping operation rather than to any setup steps.
_timeoutOrCancellationSource.CancelAfter(timeout);
return await pingTask.ConfigureAwait(false);
}
catch (Exception e) when (e is not PlatformNotSupportedException && !(e is OperationCanceledException && _canceled))
{
throw new PingException(SR.net_ping, e);
}
finally
{
Finish();
}
}
// Tests if the current machine supports the given ip protocol family.
private static void TestIsIpSupported(IPAddress ip)
{
if (ip.AddressFamily == AddressFamily.InterNetwork && !SocketProtocolSupportPal.OSSupportsIPv4)
{
throw new NotSupportedException(SR.net_ipv4_not_installed);
}
else if ((ip.AddressFamily == AddressFamily.InterNetworkV6 && !SocketProtocolSupportPal.OSSupportsIPv6))
{
throw new NotSupportedException(SR.net_ipv6_not_installed);
}
}
partial void InternalDisposeCore();
// Creates a default send buffer if a buffer wasn't specified. This follows the ping.exe model.
private byte[] DefaultSendBuffer
{
get
{
if (_defaultSendBuffer == null)
{
_defaultSendBuffer = new byte[DefaultSendBufferSize];
for (int i = 0; i < DefaultSendBufferSize; i++)
_defaultSendBuffer[i] = (byte)((int)'a' + i % 23);
}
return _defaultSendBuffer;
}
}
}
}