public void Start(string address, CancellationToken cancellationToken) { PingAttributes attrs = new PingAttributes(); _address = address; // Verify address attrs.ResolvedAddress = Lookup.QueryDNS(address, AddressFamily.InterNetwork); // Setup ping attributes attrs.Interval = 0; attrs.Timeout = 100; attrs.Message = "R U Dead Yet?"; // TODO: Option for 'heavy' flood with bloated packet sizes attrs.Continous = true; // Setup ping object Ping p = new Ping(attrs, cancellationToken); p.OnResultsUpdate += OnResultsUpdate; // Start flooding PingResults results = p.Send(); ConsoleDisplay.PingResults(attrs, results); }
/// <summary> /// Internal whois function for recursive lookup /// </summary> /// <param name="address"></param> /// <returns></returns> public static void QueryWhoIs(string address, bool full = true) { // Trim the inputted address address = address.Split('/')[0]; string keyword = address.Split('.')[0]; string tld = address.Split('.').Last(); // Quick sanity check before we proceed if (keyword == "" || tld == "") { Helper.ErrorAndExit("Incorrectly formatted address, please check format and try again"); } ConsoleDisplay.Message("WHOIS [" + address + "]:", ConsoleColor.Yellow); // Find appropriate whois for the tld ConsoleDisplay.Message("QUERYING [" + ROOT_WHOIS_SERVER + "] FOR TLD [" + tld + "]:", ConsoleColor.Yellow, false); string whoisRoot = PerformWhoIsLookup(ROOT_WHOIS_SERVER, tld); ConsoleDisplay.Message(" DONE", ConsoleColor.Yellow); if (full) { Console.WriteLine(whoisRoot); } whoisRoot = whoisRoot.Remove(0, whoisRoot.IndexOf("whois:", StringComparison.Ordinal) + 6).TrimStart(); whoisRoot = whoisRoot.Substring(0, whoisRoot.IndexOf('\r')); ConsoleDisplay.Message("QUERYING [" + whoisRoot + "] FOR DOMAIN [" + address + "]:", ConsoleColor.Yellow, false); // Next query resulting whois for the domain string result = PerformWhoIsLookup(whoisRoot, address); ConsoleDisplay.Message(" DONE", ConsoleColor.Yellow); Console.WriteLine(result); ConsoleDisplay.Message("WHOIS LOOKUP FOR [" + address + "] COMPLETE.", ConsoleColor.Yellow); }
private static IPAddress[] GetLocalAddresses() { IPHostEntry hostAddress = null; // Get all addresses assocatied with this computer try { hostAddress = Dns.GetHostEntry(Dns.GetHostName()); } catch (Exception e) { ConsoleDisplay.Error($"Could not fetch local addresses ({e.GetType().ToString().Split('.').Last()})"); } // Only get IPv4 address List <IPAddress> addresses = new List <IPAddress>(); foreach (IPAddress address in hostAddress.AddressList) { if (address.AddressFamily == AddressFamily.InterNetwork) { addresses.Add(address); } } return(addresses.ToArray()); }
/// <summary> /// Prints and error message and then exits with exit code 1 /// </summary> /// <param name="msg">Error message to print</param> /// <param name="pause">Wait for user input before exitingt</param> public static void ErrorAndExit(string msg) { ConsoleDisplay.Error(msg); if (RequireInput) { Helper.WaitForUserInput(); } Environment.Exit(1); }
public static void ListenForICMPOnAddress(IPAddress address) { Socket listeningSocket = null; PingResults results = new PingResults(); int bufferSize = 4096; // Create listener socket try { listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); listeningSocket.Bind(new IPEndPoint(address, 0)); listeningSocket.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 }); // Set SIO_RCVALL flag to socket IO control listeningSocket.ReceiveBufferSize = bufferSize; } catch (Exception e) { ConsoleDisplay.Error($"Exception occured while trying to create listening socket for {address.ToString()} ({e.GetType().ToString().Split('.').Last()})"); return; } ConsoleDisplay.ListenIntroMsg(address.ToString()); // Listening loop while (true) { byte[] buffer = new byte[bufferSize]; try { // Recieve any incoming ICMPv4 packets EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); int bytesRead = listeningSocket.ReceiveFrom(buffer, ref remoteEndPoint); ICMP response = new ICMP(buffer, bytesRead); // Display captured packet ConsoleDisplay.CapturedPacket(address.ToString(), response, remoteEndPoint.ToString(), DateTime.Now.ToString("h:mm:ss.ff tt"), bytesRead); // Store results results.CountPacketType(response.Type); results.IncrementReceivedPackets(); } catch (OperationCanceledException) { } catch (SocketException) { ConsoleDisplay.Error("Could not read packet from socket"); } } listeningSocket.Close(); }
public void Append(string line) { if (_fileStream != null && _fileStream.CanWrite) { _fileStream.Write(_asciiEncoder.GetBytes(line + Environment.NewLine)); try { _fileStream.Flush(); } catch (Exception ex) { ConsoleDisplay.Error($"Error writing to log file ({_filePath})", ex); } } }
// This callback will run after each ping iteration public void OnResultsUpdate(PingResults r) { // Make sure we're not updating the display too frequently if (!_displayUpdateLimiter.RequestRun()) { return; } // Calculate pings per second double pingsPerSecond = 0; if (_displayUpdateLimiter.ElapsedSinceLastRun != TimeSpan.Zero) { pingsPerSecond = (r.Sent - _previousPingsSent) / _displayUpdateLimiter.ElapsedSinceLastRun.TotalSeconds; } _previousPingsSent = r.Sent; // Update results text ConsoleDisplay.FloodProgress(r.Sent, (ulong)Math.Round(pingsPerSecond), _address); }
public void Create(string filePath) { string?path = ""; try { if (filePath.Contains(Path.DirectorySeparatorChar)) { // Check the directory we want to write to exits path = Path.GetDirectoryName(filePath); if (path != null && !Directory.Exists(path)) { Directory.CreateDirectory(path); } } } catch (Exception e) { ConsoleDisplay.Error($"Cannot create file at {path} changing to {Directory.GetCurrentDirectory()}", e); // Change file to be written to current directory // when we can't create our first directory choice filePath = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(filePath)); } try { // Create the file _fileStream = File.Create(filePath); } catch (Exception ex) { ConsoleDisplay.Error($"Cannot write to log file ({filePath})", ex); _fileStream = null; } }
public static void Start(string range, CancellationToken cancellationToken) { List <string> addresses = new List <string>(); List <HostInformation> activeHosts = new List <HostInformation>(); Stopwatch timer = new Stopwatch(); // Get addresses to scan from range addresses = ParseRange(range); // Setup addresses and threads var splitAddresses = Helper.PartitionList(addresses, THREAD_COUNT); Thread[] threads = new Thread[THREAD_COUNT]; object lockObject = new object(); int scanned = 0; // Run the threads timer.Start(); for (int i = 0; i < THREAD_COUNT; i++) { List <string> addrs = splitAddresses[i]; threads[i] = new Thread(() => { PingAttributes attrs = new PingAttributes(); attrs.InputtedAddress = "127.0.0.1"; attrs.Timeout = 500; attrs.Interval = 0; attrs.Count = 1; Ping ping = new Ping(attrs, cancellationToken); try { foreach (string host in addrs) { // Send ping PingResults results = ping.Send(host); if (results.ScanWasCanceled) { // Cancel was requested during scan throw new OperationCanceledException(); } Interlocked.Increment(ref scanned); if (results.Lost == 0 && results.ErrorPackets != 1) { // If host is active, add to list lock (lockObject) { activeHosts.Add(new HostInformation { Address = host, HostName = "", ResponseTime = results.CurrTime }); } } } } catch (OperationCanceledException) { _cancelled = true; } }); threads[i].IsBackground = true; threads[i].Start(); } // Wait for all threads to exit int lastSent = 0, pingsPerSecond = 0; int lastSpeedCheck = 0; while (threads.Where(x => x.IsAlive).ToList().Count > 0) { int count = 0; lock (lockObject) { count = activeHosts.Count; } if (lastSpeedCheck == 5) { pingsPerSecond = Math.Abs((scanned - lastSent)); lastSent = scanned; lastSpeedCheck = 0; } ConsoleDisplay.ScanProgress( scanned, activeHosts.Count, addresses.Count, pingsPerSecond, timer.Elapsed, range); lastSpeedCheck++; Thread.Sleep(200); } // Display one last time so the bar actually completes // (scan could have completed while the main thread was sleeping) ConsoleDisplay.ScanProgress( scanned, activeHosts.Count, addresses.Count, pingsPerSecond, timer.Elapsed, range); // Exit out when the operation has been canceled if (_cancelled) { ConsoleDisplay.ScanResults(scanned, false, activeHosts); return; } // Lookup host's name Console.WriteLine(); Console.Write("Looking up host names, one sec..."); Console.CursorLeft = 0; foreach (HostInformation host in activeHosts) { string hostName = Helper.RunWithCancellationToken(() => Lookup.QueryHost(host.Address), cancellationToken); host.HostName = hostName; } Console.WriteLine(" "); Console.CursorTop--; ConsoleDisplay.ScanResults(scanned, !cancellationToken.IsCancellationRequested, activeHosts); }