static void Main(string[] args) { ArgumentParser arg = new ArgumentParser("ping"); var echoCount = new Argument<int>("count", 4); var bufferSize = new Argument<int>("size", 32); var ttl = new Argument<short>("TTL", 64); var timeout = new Argument<int>("timeout", 2000); var targetname = new Argument<string>("targetname"); var endless = arg.AddOption("t", help: "Ping the specified host until stopped."); var rarp = arg.AddOption("a", help: "Resolve addresses to hostnames"); var help = arg.AddOption("h", help: "Show this help"); help.IsUsed += (se, e) => { Console.Write(arg.Help()); Environment.Exit(0); }; arg.AddOption("n", arguments: new Argument[] { echoCount }, help: "Number of echo requests to send."); arg.AddOption("l", arguments: new Argument[] { bufferSize }, help: "Send buffer size."); arg.AddOption("i", arguments: new Argument[] { ttl }, help: "Time To Live."); arg.AddOption("w", arguments: new Argument[] { timeout }, help: "Timeout in milliseconds to wait for each reply."); arg.AddArgument(targetname); if (!arg.Parse(args)) { Console.WriteLine(arg.Help()); return; } IPAddress ip = null; try { ip = Dns.GetHostEntry(targetname.Value).AddressList.FirstOrDefault(); } catch(Exception) { ip = null; } if (ip == null) { Console.WriteLine("IP or Host is invalid!"); return; } int dataLen = bufferSize.Value; int waitTime = timeout.Value; int count = echoCount.Value; Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); s.ReceiveTimeout = timeout.Value; Console.WriteLine("Pinging " + ip + " with " + dataLen + " bytes of data:"); while (endless.Used || count > 0) { if (!endless.Used) { count--; } ICMPMessage m = new ICMPMessage(ICMPType.Echo, ip); m.Data = new byte[dataLen]; // Generate Random Data as Payload Random rand = new Random(); for (int i = 0; i < dataLen; i++) { m.Data[i] = (byte)rand.Next(255); } Stopwatch timing = new Stopwatch(); s.Ttl = ttl.Value; timing.Start(); s.SendTo(m, new IPEndPoint(m.Destination, 0)); byte[] data = new byte[2000]; try { EndPoint ep = new IPEndPoint(IPAddress.Any, 0); int recv = s.ReceiveFrom(data, ref ep); timing.Stop(); DateTime receiveTime = DateTime.Now; m = ICMPMessage.Parse(data.Take(recv).ToArray()); if (m.Type == ICMPType.EchoReply) { Console.WriteLine("Reply from {0}: bytes={1} time={2}ms TTL={3}", m.Source, m.Data.Length, timing.Elapsed.TotalMilliseconds, m.TTL); } else if (m.Type == ICMPType.TimeToLiveExpired) { Console.WriteLine("Reply from {0}: TTL expired in transit.", m.Source); } } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.TimedOut) { Console.WriteLine("Request timed out."); } else { Console.WriteLine("Error: " + ex.SocketErrorCode); } } Thread.Sleep(1000); } }
private static void PrintResult(bool resolve, int currentTtl, ICMPMessage m, Stopwatch timing) { string hostname = ""; if (resolve) { try { hostname = Dns.GetHostEntry(m.Source).HostName; } catch { } } if (string.IsNullOrWhiteSpace(hostname)) { Console.WriteLine("{0,-3} {1,10:0.0000} ms {2}", currentTtl, timing.Elapsed.TotalMilliseconds, m.Source); } else { Console.WriteLine("{0,-3} {1,10:0.0000} ms {2} [{3}]", currentTtl, timing.Elapsed.TotalMilliseconds, hostname, m.Source); } }
/* Usage: tracert [-d] [-h maximum_hops] [-j host-list] [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name Options: -d Do not resolve addresses to hostnames. -h maximum_hops Maximum number of hops to search for target. -j host-list Loose source route along host-list (IPv4-only). -w timeout Wait timeout milliseconds for each reply. -R Trace round-trip path (IPv6-only). -S srcaddr Source address to use (IPv6-only). -4 Force using IPv4. -6 Force using IPv6.*/ static void Main(string[] args) { ArgumentParser arg = new ArgumentParser("tracert"); var maximumHops = new Argument<int>("maximumhops", 30); var timeout = new Argument<int>("timeout", 2000); var dontresolve = arg.AddOption("d", help: "Do not resolve addresses to hostnames."); var targetname = new Argument<string>("targetname"); var help = arg.AddOption("h", help: "Show this help"); help.IsUsed += (se, e) => { Console.Write(arg.Help()); Environment.Exit(0); }; arg.AddOption("h", arguments: new Argument[] { maximumHops }, help: "Maximum number of hops to search for target."); arg.AddOption("w", arguments: new Argument[] { timeout }, help: "Wait timeout milliseconds for each reply."); arg.AddArgument(targetname); if (!arg.Parse(args)) { Console.WriteLine(arg.Help()); return; } string name = targetname.Value; IPAddress ip = null; try { if (IPAddress.TryParse(name, out ip)) { name = Dns.GetHostEntry(ip).HostName; } else { ip = Dns.GetHostEntry(name).AddressList.FirstOrDefault(); } } catch (Exception) { ip = null; } if (ip == null) { Console.WriteLine("IP or Host is invalid!"); return; } int dataLen = 0; int waitTime = timeout.Value; Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); s.ReceiveTimeout = timeout.Value; Console.WriteLine("Tracing route to {0} [{1}]", name, ip); Console.WriteLine("over a maximum of {0} hops:", maximumHops.Value); Console.WriteLine(); bool targetReached = false; short currentTtl = 1; while (!targetReached || currentTtl == maximumHops.Value) { ICMPMessage m = new ICMPMessage(ICMPType.Echo, ip); m.Data = new byte[dataLen]; // Generate Random Data as Payload Random rand = new Random(); for (int i = 0; i < dataLen; i++) { m.Data[i] = (byte)rand.Next(255); } Stopwatch timing = new Stopwatch(); s.Ttl = currentTtl; timing.Start(); s.SendTo(m, new IPEndPoint(m.Destination, 0)); byte[] data = new byte[2000]; try { EndPoint ep = new IPEndPoint(IPAddress.Any, 0); int recv = s.ReceiveFrom(data, ref ep); timing.Stop(); DateTime receiveTime = DateTime.Now; m = ICMPMessage.Parse(data.Take(recv).ToArray()); if (m.Type == ICMPType.EchoReply) { targetReached = true; PrintResult(!dontresolve.Used, currentTtl, m, timing); } else if (m.Type == ICMPType.TimeToLiveExpired) { PrintResult(!dontresolve.Used, currentTtl, m, timing); } } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.TimedOut) { Console.WriteLine("{0,-3} {1,10} Request timed out", currentTtl, "*"); } else { Console.WriteLine("Error: " + ex.SocketErrorCode); } } currentTtl++; } Console.WriteLine(); Console.WriteLine("Trace complete."); }
public static ICMPMessage Parse(byte[] data) { if (data.Length < 20) { // damn! kein ip header?! throw new Exception("No IP Header received!"); } ICMPMessage m = new ICMPMessage(); m.TTL = data[8]; m.Source = new IPAddress((uint)data[12] | (uint)data[13] << 8 | (uint)data[14] << 16 | (uint)data[15] << 24); m.Destination = new IPAddress((uint)data[16] | (uint)data[17] << 8 | (uint)data[18] << 16 | (uint)data[19] << 24); // 20 bytes == IP Header byte[] icmpMessage = data.Skip(20).ToArray(); if (icmpMessage.Length < 8) { // damn! kein icmp header?! throw new Exception("No ICMP Header received!"); } m.Type = (ICMPType)icmpMessage[0]; m.Code = icmpMessage[1]; m.Checksum = (ushort)(icmpMessage[2] << 8 | icmpMessage[3]); m.Identifier = (ushort)(icmpMessage[4] << 8 | icmpMessage[5]); m.SequenceNumber = (ushort)(icmpMessage[6] << 8 | icmpMessage[7]); m.Data = icmpMessage.Skip(8).ToArray(); return m; }