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.
33 using System.Diagnostics;
34 using System.Globalization;
35 using System.ComponentModel;
36 using System.Net.Sockets;
37 using System.Security.Principal;
38 using System.Runtime.InteropServices;
40 namespace System.Net.NetworkInformation {
41 [MonoTODO ("IPv6 support is missing")]
42 public class Ping : Component, IDisposable
44 [StructLayout(LayoutKind.Sequential)]
45 struct cap_user_header_t
47 public UInt32 version;
51 [StructLayout(LayoutKind.Sequential)]
52 struct cap_user_data_t
54 public UInt32 effective;
55 public UInt32 permitted;
56 public UInt32 inheritable;
59 const int DefaultCount = 1;
60 static readonly string [] PingBinPaths = new string [] {
65 static readonly string PingBinPath;
66 const int default_timeout = 4000; // 4 sec.
67 const int identifier = 1; // no need to be const, but there's no place to change it.
69 // This value is correct as of Linux kernel version 2.6.25.9
70 // See /usr/include/linux/capability.h
71 const UInt32 linux_cap_version = 0x20071026;
73 static readonly byte [] default_buffer = new byte [0];
74 static bool canSendPrivileged;
77 BackgroundWorker worker;
78 object user_async_state;
80 public event PingCompletedEventHandler PingCompleted;
84 if (Environment.OSVersion.Platform == PlatformID.Unix) {
85 CheckLinuxCapabilities ();
86 if (!canSendPrivileged && WindowsIdentity.GetCurrent ().Name == "root")
87 canSendPrivileged = true;
89 // Since different Unix systems can have different path to bin, we try some
91 foreach (string ping_path in PingBinPaths)
92 if (File.Exists (ping_path)) {
93 PingBinPath = ping_path;
98 canSendPrivileged = true;
100 if (PingBinPath == null)
101 PingBinPath = "/bin/ping"; // default, fallback value
108 [DllImport ("libc", EntryPoint="capget")]
109 static extern int capget (ref cap_user_header_t header, ref cap_user_data_t data);
111 static void CheckLinuxCapabilities ()
114 cap_user_header_t header = new cap_user_header_t ();
115 cap_user_data_t data = new cap_user_data_t ();
117 header.version = linux_cap_version;
122 ret = capget (ref header, ref data);
123 } catch (Exception) {
129 canSendPrivileged = (data.effective & (1 << 13)) != 0;
131 canSendPrivileged = false;
135 void IDisposable.Dispose ()
139 protected void OnPingCompleted (PingCompletedEventArgs e)
141 if (PingCompleted != null)
142 PingCompleted (this, e);
143 user_async_state = null;
149 public PingReply Send (IPAddress address)
151 return Send (address, default_timeout);
154 public PingReply Send (IPAddress address, int timeout)
156 return Send (address, timeout, default_buffer);
159 public PingReply Send (IPAddress address, int timeout, byte [] buffer)
161 return Send (address, timeout, buffer, new PingOptions ());
164 public PingReply Send (string hostNameOrAddress)
166 return Send (hostNameOrAddress, default_timeout);
169 public PingReply Send (string hostNameOrAddress, int timeout)
171 return Send (hostNameOrAddress, timeout, default_buffer);
174 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer)
176 return Send (hostNameOrAddress, timeout, buffer, new PingOptions ());
179 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
181 IPAddress [] addresses = Dns.GetHostAddresses (hostNameOrAddress);
182 return Send (addresses [0], timeout, buffer, options);
185 static IPAddress GetNonLoopbackIP ()
187 foreach (IPAddress addr in Dns.GetHostByName (Dns.GetHostName ()).AddressList)
188 if (!IPAddress.IsLoopback (addr))
190 throw new InvalidOperationException ("Could not resolve non-loopback IP address for localhost");
193 public PingReply Send (IPAddress address, int timeout, byte [] buffer, PingOptions options)
196 throw new ArgumentNullException ("address");
198 throw new ArgumentOutOfRangeException ("timeout", "timeout must be non-negative integer");
200 throw new ArgumentNullException ("buffer");
201 if (buffer.Length > 65500)
202 throw new ArgumentException ("buffer");
203 // options can be null.
205 if (canSendPrivileged)
206 return SendPrivileged (address, timeout, buffer, options);
207 return SendUnprivileged (address, timeout, buffer, options);
210 private PingReply SendPrivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
212 IPEndPoint target = new IPEndPoint (address, 0);
213 IPEndPoint client = new IPEndPoint (GetNonLoopbackIP (), 0);
215 // FIXME: support IPv6
216 using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)) {
217 if (options != null) {
218 s.DontFragment = options.DontFragment;
219 s.Ttl = (short) options.Ttl;
221 s.SendTimeout = timeout;
222 s.ReceiveTimeout = timeout;
223 // not sure why Identifier = 0 is unacceptable ...
224 IcmpMessage send = new IcmpMessage (8, 0, identifier, 0, buffer);
225 byte [] bytes = send.GetBytes ();
226 s.SendBufferSize = bytes.Length;
227 s.SendTo (bytes, bytes.Length, SocketFlags.None, target);
229 DateTime sentTime = DateTime.Now;
232 bytes = new byte [100];
234 EndPoint endpoint = client;
236 int rc = s.ReceiveFrom_nochecks_exc (bytes, 0, 100, SocketFlags.None,
237 ref endpoint, false, out error);
240 if (error == (int) SocketError.TimedOut) {
241 return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
243 throw new NotSupportedException (String.Format ("Unexpected socket error during ping request: {0}", error));
245 long rtt = (long) (DateTime.Now - sentTime).TotalMilliseconds;
246 int headerLength = (bytes [0] & 0xF) << 2;
247 int bodyLength = rc - headerLength;
249 // Ping reply to different request. discard it.
250 if (!((IPEndPoint) endpoint).Address.Equals (target.Address)) {
251 long t = timeout - rtt;
253 return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
254 s.ReceiveTimeout = (int) t;
258 IcmpMessage recv = new IcmpMessage (bytes, headerLength, bodyLength);
260 /* discard ping reply to different request or echo requests if running on same host. */
261 if (recv.Identifier != identifier || recv.Type == 8) {
262 long t = timeout - rtt;
264 return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
265 s.ReceiveTimeout = (int) t;
269 return new PingReply (address, recv.Data, options, rtt, recv.IPStatus);
274 private PingReply SendUnprivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
276 DateTime sentTime = DateTime.Now;
278 Process ping = new Process ();
279 string args = BuildPingArgs (address, timeout, options);
282 ping.StartInfo.FileName = PingBinPath;
283 ping.StartInfo.Arguments = args;
285 ping.StartInfo.CreateNoWindow = true;
286 ping.StartInfo.UseShellExecute = false;
288 ping.StartInfo.RedirectStandardOutput = true;
289 ping.StartInfo.RedirectStandardError = true;
294 #pragma warning disable 219
295 // No need to read stdout or stderr as long as the output is less than 4k on linux <= 2.6.11 and 65k after that
296 // string stdout = ping.StandardOutput.ReadToEnd ();
297 // string stderr = ping.StandardError.ReadToEnd ();
298 #pragma warning restore 219
300 trip_time = (long) (DateTime.Now - sentTime).TotalMilliseconds;
301 if (!ping.WaitForExit (timeout) || (ping.HasExited && ping.ExitCode == 2))
302 return new PingReply (address, buffer, options, trip_time, IPStatus.TimedOut);
304 if (ping.ExitCode == 1)
305 return new PingReply (address, buffer, options, trip_time, IPStatus.TtlExpired);
306 } catch (Exception) {
307 return new PingReply (address, buffer, options, trip_time, IPStatus.Unknown);
316 return new PingReply (address, buffer, options, trip_time, IPStatus.Success);
321 public void SendAsync (IPAddress address, int timeout, byte [] buffer, object userToken)
323 SendAsync (address, default_timeout, default_buffer, new PingOptions (), userToken);
326 public void SendAsync (IPAddress address, int timeout, object userToken)
328 SendAsync (address, default_timeout, default_buffer, userToken);
331 public void SendAsync (IPAddress address, object userToken)
333 SendAsync (address, default_timeout, userToken);
336 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, object userToken)
338 SendAsync (hostNameOrAddress, timeout, buffer, new PingOptions (), userToken);
341 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options, object userToken)
343 IPAddress address = Dns.GetHostEntry (hostNameOrAddress).AddressList [0];
344 SendAsync (address, timeout, buffer, options, userToken);
347 public void SendAsync (string hostNameOrAddress, int timeout, object userToken)
349 SendAsync (hostNameOrAddress, timeout, default_buffer, userToken);
352 public void SendAsync (string hostNameOrAddress, object userToken)
354 SendAsync (hostNameOrAddress, default_timeout, userToken);
357 public void SendAsync (IPAddress address, int timeout, byte [] buffer, PingOptions options, object userToken)
360 throw new InvalidOperationException ("Another SendAsync operation is in progress");
362 worker = new BackgroundWorker ();
363 worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
365 user_async_state = ea.Argument;
366 ea.Result = Send (address, timeout, buffer, options);
367 } catch (Exception ex) {
371 worker.WorkerSupportsCancellation = true;
372 worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
373 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
374 OnPingCompleted (new PingCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state, ea.Result as PingReply));
376 worker.RunWorkerAsync (userToken);
381 public void SendAsyncCancel ()
384 throw new InvalidOperationException ("SendAsync operation is not in progress");
385 worker.CancelAsync ();
395 public IcmpMessage (byte [] bytes, int offset, int size)
397 this.bytes = new byte [size];
398 Buffer.BlockCopy (bytes, offset, this.bytes, 0, size);
402 public IcmpMessage (byte type, byte code, short identifier, short sequence, byte [] data)
404 bytes = new byte [data.Length + 8];
407 bytes [4] = (byte) (identifier & 0xFF);
408 bytes [5] = (byte) ((int) identifier >> 8);
409 bytes [6] = (byte) (sequence & 0xFF);
410 bytes [7] = (byte) ((int) sequence >> 8);
411 Buffer.BlockCopy (data, 0, bytes, 8, data.Length);
413 ushort checksum = ComputeChecksum (bytes);
414 bytes [2] = (byte) (checksum & 0xFF);
415 bytes [3] = (byte) ((int) checksum >> 8);
419 get { return bytes [0]; }
423 get { return bytes [1]; }
426 public byte Identifier {
427 get { return (byte) (bytes [4] + (bytes [5] << 8)); }
430 public byte Sequence {
431 get { return (byte) (bytes [6] + (bytes [7] << 8)); }
434 public byte [] Data {
436 byte [] data = new byte [bytes.Length - 8];
437 Buffer.BlockCopy (bytes, 0, data, 0, data.Length);
442 public byte [] GetBytes ()
447 static ushort ComputeChecksum (byte [] data)
450 for (int i = 0; i < data.Length; i += 2) {
451 ushort us = i + 1 < data.Length ? data [i + 1] : (byte) 0;
456 ret = (ret >> 16) + (ret & 0xFFFF);
457 return (ushort) ~ ret;
460 public IPStatus IPStatus {
464 return IPStatus.Success;
465 case 3: // destination unreacheable
468 return IPStatus.DestinationNetworkUnreachable;
470 return IPStatus.DestinationHostUnreachable;
472 return IPStatus.DestinationProtocolUnreachable;
474 return IPStatus.DestinationPortUnreachable;
476 return IPStatus.BadOption; // FIXME: likely wrong
478 return IPStatus.BadRoute; // not sure if it is correct
484 return IPStatus.TimeExceeded;
486 return IPStatus.TtlReassemblyTimeExceeded;
490 return IPStatus.ParameterProblem;
492 return IPStatus.SourceQuench;
494 return IPStatus.Success;
496 return IPStatus.Unknown;
497 //throw new NotSupportedException (String.Format ("Unexpected pair of ICMP message type and code: type is {0} and code is {1}", Type, Code));
502 private string BuildPingArgs (IPAddress address, int timeout, PingOptions options)
504 CultureInfo culture = CultureInfo.InvariantCulture;
505 StringBuilder args = new StringBuilder ();
506 uint t = Convert.ToUInt32 (Math.Floor ((timeout + 1000) / 1000.0));
508 bool is_mac = ((int) Environment.OSVersion.Platform == 6);
511 args.AppendFormat (culture, "-q -n -c {0} -w {1} -t {2} -M ", DefaultCount, t, options.Ttl);
514 args.AppendFormat (culture, "-q -n -c {0} -t {1} -o -m {2} ", DefaultCount, t, options.Ttl);
517 args.Append (options.DontFragment ? "do " : "dont ");
519 else if (options.DontFragment)
523 args.Append (address.ToString ());
525 return args.ToString ();