2 // System.Net.NetworkInformation.Ping
5 // Gonzalo Paniagua Javier (gonzalo@novell.com)
6 // Atsushi Enomoto (atsushi@ximian.com)
8 // Copyright (c) 2006-2007 Novell, Inc. (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Diagnostics;
33 using System.Globalization;
34 using System.ComponentModel;
35 using System.Net.Sockets;
36 using System.Security.Principal;
37 using System.Security.Cryptography;
38 using System.Runtime.InteropServices;
40 using System.Threading;
41 using System.Threading.Tasks;
44 namespace System.Net.NetworkInformation {
45 [MonoTODO ("IPv6 support is missing")]
46 public class Ping : Component, IDisposable
48 [StructLayout(LayoutKind.Sequential)]
49 struct cap_user_header_t
51 public UInt32 version;
55 [StructLayout(LayoutKind.Sequential)]
56 struct cap_user_data_t
58 public UInt32 effective;
59 public UInt32 permitted;
60 public UInt32 inheritable;
63 const int DefaultCount = 1;
64 static readonly string [] PingBinPaths = new string [] {
69 static readonly string PingBinPath;
70 const int default_timeout = 4000; // 4 sec.
73 // This value is correct as of Linux kernel version 2.6.25.9
74 // See /usr/include/linux/capability.h
75 const UInt32 linux_cap_version = 0x20071026;
77 static readonly byte [] default_buffer = new byte [0];
78 static bool canSendPrivileged;
81 BackgroundWorker worker;
82 object user_async_state;
84 CancellationTokenSource cts;
87 public event PingCompletedEventHandler PingCompleted;
91 if (Environment.OSVersion.Platform == PlatformID.Unix) {
92 CheckLinuxCapabilities ();
93 if (!canSendPrivileged && WindowsIdentity.GetCurrent ().Name == "root")
94 canSendPrivileged = true;
96 // Since different Unix systems can have different path to bin, we try some
98 foreach (string ping_path in PingBinPaths)
99 if (File.Exists (ping_path)) {
100 PingBinPath = ping_path;
105 canSendPrivileged = true;
107 if (PingBinPath == null)
108 PingBinPath = "/bin/ping"; // default, fallback value
113 // Generate a new random 16 bit identifier for every ping
114 RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ();
115 byte [] randomIdentifier = new byte [2];
116 rng.GetBytes (randomIdentifier);
117 identifier = (ushort)(randomIdentifier [0] + (randomIdentifier [1] << 8));
120 [DllImport ("libc", EntryPoint="capget")]
121 static extern int capget (ref cap_user_header_t header, ref cap_user_data_t data);
123 static void CheckLinuxCapabilities ()
126 cap_user_header_t header = new cap_user_header_t ();
127 cap_user_data_t data = new cap_user_data_t ();
129 header.version = linux_cap_version;
134 ret = capget (ref header, ref data);
135 } catch (Exception) {
141 canSendPrivileged = (data.effective & (1 << 13)) != 0;
143 canSendPrivileged = false;
147 void IDisposable.Dispose ()
151 protected void OnPingCompleted (PingCompletedEventArgs e)
153 user_async_state = null;
159 if (PingCompleted != null)
160 PingCompleted (this, e);
165 public PingReply Send (IPAddress address)
167 return Send (address, default_timeout);
170 public PingReply Send (IPAddress address, int timeout)
172 return Send (address, timeout, default_buffer);
175 public PingReply Send (IPAddress address, int timeout, byte [] buffer)
177 return Send (address, timeout, buffer, new PingOptions ());
180 public PingReply Send (string hostNameOrAddress)
182 return Send (hostNameOrAddress, default_timeout);
185 public PingReply Send (string hostNameOrAddress, int timeout)
187 return Send (hostNameOrAddress, timeout, default_buffer);
190 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer)
192 return Send (hostNameOrAddress, timeout, buffer, new PingOptions ());
195 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
197 IPAddress [] addresses = Dns.GetHostAddresses (hostNameOrAddress);
198 return Send (addresses [0], timeout, buffer, options);
201 static IPAddress GetNonLoopbackIP ()
203 foreach (IPAddress addr in Dns.GetHostByName (Dns.GetHostName ()).AddressList)
204 if (!IPAddress.IsLoopback (addr))
206 throw new InvalidOperationException ("Could not resolve non-loopback IP address for localhost");
209 public PingReply Send (IPAddress address, int timeout, byte [] buffer, PingOptions options)
212 throw new ArgumentNullException ("address");
214 throw new ArgumentOutOfRangeException ("timeout", "timeout must be non-negative integer");
216 throw new ArgumentNullException ("buffer");
217 if (buffer.Length > 65500)
218 throw new ArgumentException ("buffer");
219 // options can be null.
221 if (canSendPrivileged)
222 return SendPrivileged (address, timeout, buffer, options);
223 return SendUnprivileged (address, timeout, buffer, options);
226 private PingReply SendPrivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
228 IPEndPoint target = new IPEndPoint (address, 0);
229 IPEndPoint client = new IPEndPoint (GetNonLoopbackIP (), 0);
231 // FIXME: support IPv6
232 using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)) {
233 if (options != null) {
234 s.DontFragment = options.DontFragment;
235 s.Ttl = (short) options.Ttl;
237 s.SendTimeout = timeout;
238 s.ReceiveTimeout = timeout;
239 // not sure why Identifier = 0 is unacceptable ...
240 IcmpMessage send = new IcmpMessage (8, 0, identifier, 0, buffer);
241 byte [] bytes = send.GetBytes ();
242 s.SendBufferSize = bytes.Length;
243 s.SendTo (bytes, bytes.Length, SocketFlags.None, target);
245 DateTime sentTime = DateTime.Now;
248 bytes = new byte [100];
250 EndPoint endpoint = client;
252 int rc = s.ReceiveFrom_nochecks_exc (bytes, 0, 100, SocketFlags.None,
253 ref endpoint, false, out error);
256 if (error == (int) SocketError.TimedOut) {
257 return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
259 throw new NotSupportedException (String.Format ("Unexpected socket error during ping request: {0}", error));
261 long rtt = (long) (DateTime.Now - sentTime).TotalMilliseconds;
262 int headerLength = (bytes [0] & 0xF) << 2;
263 int bodyLength = rc - headerLength;
265 // Ping reply to different request. discard it.
266 if (!((IPEndPoint) endpoint).Address.Equals (target.Address)) {
267 long t = timeout - rtt;
269 return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
270 s.ReceiveTimeout = (int) t;
274 IcmpMessage recv = new IcmpMessage (bytes, headerLength, bodyLength);
276 /* discard ping reply to different request or echo requests if running on same host. */
277 if (recv.Identifier != identifier || recv.Type == 8) {
278 long t = timeout - rtt;
280 return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
281 s.ReceiveTimeout = (int) t;
285 return new PingReply (address, recv.Data, options, rtt, recv.IPStatus);
290 private PingReply SendUnprivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
292 DateTime sentTime = DateTime.Now;
294 Process ping = new Process ();
295 string args = BuildPingArgs (address, timeout, options);
298 ping.StartInfo.FileName = PingBinPath;
299 ping.StartInfo.Arguments = args;
301 ping.StartInfo.CreateNoWindow = true;
302 ping.StartInfo.UseShellExecute = false;
304 ping.StartInfo.RedirectStandardOutput = true;
305 ping.StartInfo.RedirectStandardError = true;
310 #pragma warning disable 219
311 string stdout = ping.StandardOutput.ReadToEnd ();
312 string stderr = ping.StandardError.ReadToEnd ();
313 #pragma warning restore 219
315 trip_time = (long) (DateTime.Now - sentTime).TotalMilliseconds;
316 if (!ping.WaitForExit (timeout) || (ping.HasExited && ping.ExitCode == 2))
317 return new PingReply (address, buffer, options, trip_time, IPStatus.TimedOut);
319 if (ping.ExitCode == 1)
320 return new PingReply (address, buffer, options, trip_time, IPStatus.TtlExpired);
321 } catch (Exception) {
322 return new PingReply (address, buffer, options, trip_time, IPStatus.Unknown);
331 return new PingReply (address, buffer, options, trip_time, IPStatus.Success);
336 public void SendAsync (IPAddress address, int timeout, byte [] buffer, object userToken)
338 SendAsync (address, default_timeout, default_buffer, new PingOptions (), userToken);
341 public void SendAsync (IPAddress address, int timeout, object userToken)
343 SendAsync (address, default_timeout, default_buffer, userToken);
346 public void SendAsync (IPAddress address, object userToken)
348 SendAsync (address, default_timeout, userToken);
351 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, object userToken)
353 SendAsync (hostNameOrAddress, timeout, buffer, new PingOptions (), userToken);
356 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options, object userToken)
358 IPAddress address = Dns.GetHostEntry (hostNameOrAddress).AddressList [0];
359 SendAsync (address, timeout, buffer, options, userToken);
362 public void SendAsync (string hostNameOrAddress, int timeout, object userToken)
364 SendAsync (hostNameOrAddress, timeout, default_buffer, userToken);
367 public void SendAsync (string hostNameOrAddress, object userToken)
369 SendAsync (hostNameOrAddress, default_timeout, userToken);
372 public void SendAsync (IPAddress address, int timeout, byte [] buffer, PingOptions options, object userToken)
375 if ((worker != null) || (cts != null))
376 throw new InvalidOperationException ("Another SendAsync operation is in progress");
379 throw new InvalidOperationException ("Another SendAsync operation is in progress");
382 worker = new BackgroundWorker ();
383 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
385 user_async_state = ea.Argument;
386 ea.Result = Send (address, timeout, buffer, options);
387 } catch (Exception ex) {
391 worker.WorkerSupportsCancellation = true;
392 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
393 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
394 OnPingCompleted (new PingCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state, ea.Result as PingReply));
396 worker.RunWorkerAsync (userToken);
401 public void SendAsyncCancel ()
411 throw new InvalidOperationException ("SendAsync operation is not in progress");
412 worker.CancelAsync ();
422 public IcmpMessage (byte [] bytes, int offset, int size)
424 this.bytes = new byte [size];
425 Buffer.BlockCopy (bytes, offset, this.bytes, 0, size);
429 public IcmpMessage (byte type, byte code, ushort identifier, ushort sequence, byte [] data)
431 bytes = new byte [data.Length + 8];
434 bytes [4] = (byte) (identifier & 0xFF);
435 bytes [5] = (byte) ((int) identifier >> 8);
436 bytes [6] = (byte) (sequence & 0xFF);
437 bytes [7] = (byte) ((int) sequence >> 8);
438 Buffer.BlockCopy (data, 0, bytes, 8, data.Length);
440 ushort checksum = ComputeChecksum (bytes);
441 bytes [2] = (byte) (checksum & 0xFF);
442 bytes [3] = (byte) ((int) checksum >> 8);
446 get { return bytes [0]; }
450 get { return bytes [1]; }
453 public ushort Identifier {
454 get { return (ushort) (bytes [4] + (bytes [5] << 8)); }
457 public ushort Sequence {
458 get { return (ushort) (bytes [6] + (bytes [7] << 8)); }
461 public byte [] Data {
463 byte [] data = new byte [bytes.Length - 8];
464 Buffer.BlockCopy (bytes, 8, data, 0, data.Length);
469 public byte [] GetBytes ()
474 static ushort ComputeChecksum (byte [] data)
477 for (int i = 0; i < data.Length; i += 2) {
478 ushort us = i + 1 < data.Length ? data [i + 1] : (byte) 0;
483 ret = (ret >> 16) + (ret & 0xFFFF);
484 return (ushort) ~ ret;
487 public IPStatus IPStatus {
491 return IPStatus.Success;
492 case 3: // destination unreacheable
495 return IPStatus.DestinationNetworkUnreachable;
497 return IPStatus.DestinationHostUnreachable;
499 return IPStatus.DestinationProtocolUnreachable;
501 return IPStatus.DestinationPortUnreachable;
503 return IPStatus.BadOption; // FIXME: likely wrong
505 return IPStatus.BadRoute; // not sure if it is correct
511 return IPStatus.TimeExceeded;
513 return IPStatus.TtlReassemblyTimeExceeded;
517 return IPStatus.ParameterProblem;
519 return IPStatus.SourceQuench;
521 return IPStatus.Success;
523 return IPStatus.Unknown;
524 //throw new NotSupportedException (String.Format ("Unexpected pair of ICMP message type and code: type is {0} and code is {1}", Type, Code));
529 private string BuildPingArgs (IPAddress address, int timeout, PingOptions options)
531 CultureInfo culture = CultureInfo.InvariantCulture;
532 StringBuilder args = new StringBuilder ();
533 uint t = Convert.ToUInt32 (Math.Floor ((timeout + 1000) / 1000.0));
534 bool is_mac = ((int) Environment.OSVersion.Platform == 6);
536 args.AppendFormat (culture, "-q -n -c {0} -w {1} -t {2} -M ", DefaultCount, t, options.Ttl);
538 args.AppendFormat (culture, "-q -n -c {0} -t {1} -o -m {2} ", DefaultCount, t, options.Ttl);
540 args.Append (options.DontFragment ? "do " : "dont ");
541 else if (options.DontFragment)
544 args.Append (address.ToString ());
546 return args.ToString ();
550 public Task<PingReply> SendPingAsync (IPAddress address, int timeout, byte [] buffer)
552 return SendPingAsync (address, default_timeout, default_buffer, new PingOptions ());
555 public Task<PingReply> SendPingAsync (IPAddress address, int timeout)
557 return SendPingAsync (address, default_timeout, default_buffer);
560 public Task<PingReply> SendPingAsync (IPAddress address)
562 return SendPingAsync (address, default_timeout);
565 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout, byte [] buffer)
567 return SendPingAsync (hostNameOrAddress, timeout, buffer, new PingOptions ());
570 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
572 IPAddress address = Dns.GetHostEntry (hostNameOrAddress).AddressList [0];
573 return SendPingAsync (address, timeout, buffer, options);
576 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout)
578 return SendPingAsync (hostNameOrAddress, timeout, default_buffer);
581 public Task<PingReply> SendPingAsync (string hostNameOrAddress)
583 return SendPingAsync (hostNameOrAddress, default_timeout);
586 public Task<PingReply> SendPingAsync (IPAddress address, int timeout, byte [] buffer, PingOptions options)
588 if ((worker != null) || (cts != null))
589 throw new InvalidOperationException ("Another SendAsync operation is in progress");
591 var task = Task<PingReply>.Factory.StartNew (
592 () => Send (address, timeout, buffer, options), cts.Token);
594 task.ContinueWith ((t) => {
596 OnPingCompleted (new PingCompletedEventArgs (null, true, null, null));
597 else if (t.IsFaulted)
598 OnPingCompleted (new PingCompletedEventArgs (t.Exception, false, null, null));
600 OnPingCompleted (new PingCompletedEventArgs (null, false, null, t.Result));