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;
39 using System.Threading;
40 using System.Threading.Tasks;
42 namespace System.Net.NetworkInformation {
43 [MonoTODO ("IPv6 support is missing")]
44 public class Ping : Component, IDisposable
46 [StructLayout(LayoutKind.Sequential)]
47 struct cap_user_header_t
49 public UInt32 version;
53 [StructLayout(LayoutKind.Sequential)]
54 struct cap_user_data_t
56 public UInt32 effective;
57 public UInt32 permitted;
58 public UInt32 inheritable;
61 const int DefaultCount = 1;
62 static readonly string [] PingBinPaths = new string [] {
70 static readonly string PingBinPath;
71 const int default_timeout = 4000; // 4 sec.
74 // This value is correct as of Linux kernel version 2.6.25.9
75 // See /usr/include/linux/capability.h
76 const UInt32 linux_cap_version = 0x20071026;
78 static readonly byte [] default_buffer = new byte [0];
79 static bool canSendPrivileged;
82 BackgroundWorker worker;
83 object user_async_state;
84 CancellationTokenSource cts;
86 public event PingCompletedEventHandler PingCompleted;
90 if (Environment.OSVersion.Platform == PlatformID.Unix) {
91 CheckLinuxCapabilities ();
92 if (!canSendPrivileged && WindowsIdentity.GetCurrent ().Name == "root")
93 canSendPrivileged = true;
95 // Since different Unix systems can have different path to bin, we try some
97 foreach (string ping_path in PingBinPaths)
98 if (File.Exists (ping_path)) {
99 PingBinPath = ping_path;
104 canSendPrivileged = true;
106 if (PingBinPath == null)
107 PingBinPath = "/bin/ping"; // default, fallback value
112 // Generate a new random 16 bit identifier for every ping
113 RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ();
114 byte [] randomIdentifier = new byte [2];
115 rng.GetBytes (randomIdentifier);
116 identifier = (ushort)(randomIdentifier [0] + (randomIdentifier [1] << 8));
119 [DllImport ("libc", EntryPoint="capget")]
120 static extern int capget (ref cap_user_header_t header, ref cap_user_data_t data);
122 static void CheckLinuxCapabilities ()
125 cap_user_header_t header = new cap_user_header_t ();
126 cap_user_data_t data = new cap_user_data_t ();
128 header.version = linux_cap_version;
133 ret = capget (ref header, ref data);
134 } catch (Exception) {
140 canSendPrivileged = (data.effective & (1 << 13)) != 0;
142 canSendPrivileged = false;
146 void IDisposable.Dispose ()
150 protected void OnPingCompleted (PingCompletedEventArgs e)
152 user_async_state = null;
156 if (PingCompleted != null)
157 PingCompleted (this, e);
162 public PingReply Send (IPAddress address)
164 return Send (address, default_timeout);
167 public PingReply Send (IPAddress address, int timeout)
169 return Send (address, timeout, default_buffer);
172 public PingReply Send (IPAddress address, int timeout, byte [] buffer)
174 return Send (address, timeout, buffer, new PingOptions ());
177 public PingReply Send (string hostNameOrAddress)
179 return Send (hostNameOrAddress, default_timeout);
182 public PingReply Send (string hostNameOrAddress, int timeout)
184 return Send (hostNameOrAddress, timeout, default_buffer);
187 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer)
189 return Send (hostNameOrAddress, timeout, buffer, new PingOptions ());
192 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
194 IPAddress [] addresses = Dns.GetHostAddresses (hostNameOrAddress);
195 return Send (addresses [0], timeout, buffer, options);
198 static IPAddress GetNonLoopbackIP ()
200 foreach (IPAddress addr in Dns.GetHostByName (Dns.GetHostName ()).AddressList)
201 if (!IPAddress.IsLoopback (addr))
203 throw new InvalidOperationException ("Could not resolve non-loopback IP address for localhost");
206 public PingReply Send (IPAddress address, int timeout, byte [] buffer, PingOptions options)
209 throw new ArgumentNullException ("address");
211 throw new ArgumentOutOfRangeException ("timeout", "timeout must be non-negative integer");
213 throw new ArgumentNullException ("buffer");
214 if (buffer.Length > 65500)
215 throw new ArgumentException ("buffer");
216 // options can be null.
218 if (canSendPrivileged)
219 return SendPrivileged (address, timeout, buffer, options);
220 return SendUnprivileged (address, timeout, buffer, options);
223 private PingReply SendPrivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
225 IPEndPoint target = new IPEndPoint (address, 0);
226 IPEndPoint client = new IPEndPoint (GetNonLoopbackIP (), 0);
228 // FIXME: support IPv6
229 using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)) {
230 if (options != null) {
231 s.DontFragment = options.DontFragment;
232 s.Ttl = (short) options.Ttl;
234 s.SendTimeout = timeout;
235 s.ReceiveTimeout = timeout;
236 // not sure why Identifier = 0 is unacceptable ...
237 IcmpMessage send = new IcmpMessage (8, 0, identifier, 0, buffer);
238 byte [] bytes = send.GetBytes ();
239 s.SendBufferSize = bytes.Length;
240 s.SendTo (bytes, bytes.Length, SocketFlags.None, target);
242 DateTime sentTime = DateTime.Now;
245 bytes = new byte [100];
247 EndPoint endpoint = client;
249 int rc = s.ReceiveFrom_nochecks_exc (bytes, 0, 100, SocketFlags.None,
250 ref endpoint, false, out error);
253 if (error == (int) SocketError.TimedOut) {
254 return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
256 throw new NotSupportedException (String.Format ("Unexpected socket error during ping request: {0}", error));
258 long rtt = (long) (DateTime.Now - sentTime).TotalMilliseconds;
259 int headerLength = (bytes [0] & 0xF) << 2;
260 int bodyLength = rc - headerLength;
262 // Ping reply to different request. discard it.
263 if (!((IPEndPoint) endpoint).Address.Equals (target.Address)) {
264 long t = timeout - rtt;
266 return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
267 s.ReceiveTimeout = (int) t;
271 IcmpMessage recv = new IcmpMessage (bytes, headerLength, bodyLength);
273 /* discard ping reply to different request or echo requests if running on same host. */
274 if (recv.Identifier != identifier || recv.Type == 8) {
275 long t = timeout - rtt;
277 return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
278 s.ReceiveTimeout = (int) t;
282 return new PingReply (address, recv.Data, options, rtt, recv.IPStatus);
287 private PingReply SendUnprivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
289 DateTime sentTime = DateTime.UtcNow;
291 Process ping = new Process ();
292 string args = BuildPingArgs (address, timeout, options);
295 ping.StartInfo.FileName = PingBinPath;
296 ping.StartInfo.Arguments = args;
298 ping.StartInfo.CreateNoWindow = true;
299 ping.StartInfo.UseShellExecute = false;
301 ping.StartInfo.RedirectStandardOutput = true;
302 ping.StartInfo.RedirectStandardError = true;
304 IPStatus status = IPStatus.Unknown;
308 #pragma warning disable 219
309 string stdout = ping.StandardOutput.ReadToEnd ();
310 string stderr = ping.StandardError.ReadToEnd ();
311 #pragma warning restore 219
313 trip_time = (long) (DateTime.UtcNow - sentTime).TotalMilliseconds;
314 if (!ping.WaitForExit (timeout) || (ping.HasExited && ping.ExitCode == 2))
315 status = IPStatus.TimedOut;
316 else if (ping.ExitCode == 0)
317 status = IPStatus.Success;
318 else if (ping.ExitCode == 1)
319 status = IPStatus.TtlExpired;
327 return new PingReply (address, buffer, options, trip_time, status);
332 public void SendAsync (IPAddress address, int timeout, byte [] buffer, object userToken)
334 SendAsync (address, default_timeout, default_buffer, new PingOptions (), userToken);
337 public void SendAsync (IPAddress address, int timeout, object userToken)
339 SendAsync (address, default_timeout, default_buffer, userToken);
342 public void SendAsync (IPAddress address, object userToken)
344 SendAsync (address, default_timeout, userToken);
347 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, object userToken)
349 SendAsync (hostNameOrAddress, timeout, buffer, new PingOptions (), userToken);
352 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options, object userToken)
354 IPAddress address = Dns.GetHostEntry (hostNameOrAddress).AddressList [0];
355 SendAsync (address, timeout, buffer, options, userToken);
358 public void SendAsync (string hostNameOrAddress, int timeout, object userToken)
360 SendAsync (hostNameOrAddress, timeout, default_buffer, userToken);
363 public void SendAsync (string hostNameOrAddress, object userToken)
365 SendAsync (hostNameOrAddress, default_timeout, userToken);
368 public void SendAsync (IPAddress address, int timeout, byte [] buffer, PingOptions options, object userToken)
370 if ((worker != null) || (cts != null))
371 throw new InvalidOperationException ("Another SendAsync operation is in progress");
373 worker = new BackgroundWorker ();
374 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
376 user_async_state = ea.Argument;
377 ea.Result = Send (address, timeout, buffer, options);
378 } catch (Exception ex) {
382 worker.WorkerSupportsCancellation = true;
383 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
384 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
385 OnPingCompleted (new PingCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state, ea.Result as PingReply));
387 worker.RunWorkerAsync (userToken);
392 public void SendAsyncCancel ()
400 throw new InvalidOperationException ("SendAsync operation is not in progress");
401 worker.CancelAsync ();
411 public IcmpMessage (byte [] bytes, int offset, int size)
413 this.bytes = new byte [size];
414 Buffer.BlockCopy (bytes, offset, this.bytes, 0, size);
418 public IcmpMessage (byte type, byte code, ushort identifier, ushort sequence, byte [] data)
420 bytes = new byte [data.Length + 8];
423 bytes [4] = (byte) (identifier & 0xFF);
424 bytes [5] = (byte) ((int) identifier >> 8);
425 bytes [6] = (byte) (sequence & 0xFF);
426 bytes [7] = (byte) ((int) sequence >> 8);
427 Buffer.BlockCopy (data, 0, bytes, 8, data.Length);
429 ushort checksum = ComputeChecksum (bytes);
430 bytes [2] = (byte) (checksum & 0xFF);
431 bytes [3] = (byte) ((int) checksum >> 8);
435 get { return bytes [0]; }
439 get { return bytes [1]; }
442 public ushort Identifier {
443 get { return (ushort) (bytes [4] + (bytes [5] << 8)); }
446 public ushort Sequence {
447 get { return (ushort) (bytes [6] + (bytes [7] << 8)); }
450 public byte [] Data {
452 byte [] data = new byte [bytes.Length - 8];
453 Buffer.BlockCopy (bytes, 8, data, 0, data.Length);
458 public byte [] GetBytes ()
463 static ushort ComputeChecksum (byte [] data)
466 for (int i = 0; i < data.Length; i += 2) {
467 ushort us = i + 1 < data.Length ? data [i + 1] : (byte) 0;
472 ret = (ret >> 16) + (ret & 0xFFFF);
473 return (ushort) ~ ret;
476 public IPStatus IPStatus {
480 return IPStatus.Success;
481 case 3: // destination unreacheable
484 return IPStatus.DestinationNetworkUnreachable;
486 return IPStatus.DestinationHostUnreachable;
488 return IPStatus.DestinationProtocolUnreachable;
490 return IPStatus.DestinationPortUnreachable;
492 return IPStatus.BadOption; // FIXME: likely wrong
494 return IPStatus.BadRoute; // not sure if it is correct
500 return IPStatus.TimeExceeded;
502 return IPStatus.TtlReassemblyTimeExceeded;
506 return IPStatus.ParameterProblem;
508 return IPStatus.SourceQuench;
510 return IPStatus.Success;
512 return IPStatus.Unknown;
513 //throw new NotSupportedException (String.Format ("Unexpected pair of ICMP message type and code: type is {0} and code is {1}", Type, Code));
518 private string BuildPingArgs (IPAddress address, int timeout, PingOptions options)
520 CultureInfo culture = CultureInfo.InvariantCulture;
521 StringBuilder args = new StringBuilder ();
522 uint t = Convert.ToUInt32 (Math.Floor ((timeout + 1000) / 1000.0));
523 bool is_mac = Platform.IsMacOS;
525 args.AppendFormat (culture, "-q -n -c {0} -w {1} -t {2} -M ", DefaultCount, t, options.Ttl);
527 args.AppendFormat (culture, "-q -n -c {0} -t {1} -o -m {2} ", DefaultCount, t, options.Ttl);
529 args.Append (options.DontFragment ? "do " : "dont ");
530 else if (options.DontFragment)
533 args.Append (address.ToString ());
535 return args.ToString ();
538 public Task<PingReply> SendPingAsync (IPAddress address, int timeout, byte [] buffer)
540 return SendPingAsync (address, default_timeout, default_buffer, new PingOptions ());
543 public Task<PingReply> SendPingAsync (IPAddress address, int timeout)
545 return SendPingAsync (address, default_timeout, default_buffer);
548 public Task<PingReply> SendPingAsync (IPAddress address)
550 return SendPingAsync (address, default_timeout);
553 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout, byte [] buffer)
555 return SendPingAsync (hostNameOrAddress, timeout, buffer, new PingOptions ());
558 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
560 IPAddress address = Dns.GetHostEntry (hostNameOrAddress).AddressList [0];
561 return SendPingAsync (address, timeout, buffer, options);
564 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout)
566 return SendPingAsync (hostNameOrAddress, timeout, default_buffer);
569 public Task<PingReply> SendPingAsync (string hostNameOrAddress)
571 return SendPingAsync (hostNameOrAddress, default_timeout);
574 public Task<PingReply> SendPingAsync (IPAddress address, int timeout, byte [] buffer, PingOptions options)
576 if ((worker != null) || (cts != null))
577 throw new InvalidOperationException ("Another SendAsync operation is in progress");
579 var task = Task<PingReply>.Factory.StartNew (
580 () => Send (address, timeout, buffer, options), cts.Token);
582 task.ContinueWith ((t) => {
584 OnPingCompleted (new PingCompletedEventArgs (null, true, null, null));
585 else if (t.IsFaulted)
586 OnPingCompleted (new PingCompletedEventArgs (t.Exception, false, null, null));
588 OnPingCompleted (new PingCompletedEventArgs (null, false, null, t.Result));