Skip to content

Commit

Permalink
.NET 6 warning fixing
Browse files Browse the repository at this point in the history
Removed update checker code
  • Loading branch information
Killeroo committed Oct 21, 2023
1 parent ff07ff6 commit d8e7fed
Show file tree
Hide file tree
Showing 15 changed files with 273 additions and 171 deletions.
52 changes: 33 additions & 19 deletions src/Commands/Listen.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,32 +23,41 @@ internal static class Listen

public static void Start(CancellationToken cancellationToken, string address = "")
{
IPAddress[] addresses = new IPAddress[0];
if (System.Environment.OSVersion.Platform != PlatformID.Win32NT)
{
Helper.ErrorAndExit("Listen mode is not supported on a non windows platform.");
return;
}

// Look up local addresses to listen on
IPAddress[]? localAddresses;
if (address == "")
{
// If no address is given then listen on all local addresses
addresses = GetLocalAddresses();
if (addresses == null)
{
return;
}
localAddresses = GetLocalAddresses();

}
else
{
// Otherwise just listen on the address we are given
addresses = new IPAddress[] { IPAddress.Parse(address) };
localAddresses = new IPAddress[] { IPAddress.Parse(address) };
}

if (localAddresses == null)
{
Helper.ErrorAndExit("Could not find local addresses to listen on.");
return;
}

// Start a listening thread for each ipv4 local address
int size = addresses.Length;
int size = localAddresses.Length;
_listenThreads = new Thread[size];
for (int x = 0; x < addresses.Length; x++)
for (int x = 0; x < localAddresses.Length; x++)
{
int index = x;
_listenThreads[index] = new Thread(() =>
_listenThreads[index] = new(() =>
{
ListenForICMPOnAddress(addresses[index]);
ListenForICMPOnAddress(localAddresses[index]);
});
_listenThreads[index].IsBackground = true;
_listenThreads[index].Start();
Expand All @@ -68,9 +77,9 @@ public static void Start(CancellationToken cancellationToken, string address = "
//Display.ListenResults(results);
}

private static IPAddress[] GetLocalAddresses()
private static IPAddress[]? GetLocalAddresses()
{
IPHostEntry hostAddress = null;
IPHostEntry hostAddress;

// Get all addresses assocatied with this computer
try
Expand All @@ -80,10 +89,11 @@ private static IPAddress[] GetLocalAddresses()
catch (Exception e)
{
ConsoleDisplay.Error($"Could not fetch local addresses ({e.GetType().ToString().Split('.').Last()})");
return null;
}

// Only get IPv4 address
List<IPAddress> addresses = new List<IPAddress>();
List<IPAddress> addresses = new();
foreach (IPAddress address in hostAddress.AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
Expand All @@ -97,16 +107,18 @@ private static IPAddress[] GetLocalAddresses()

public static void ListenForICMPOnAddress(IPAddress address)
{
Socket listeningSocket = null;
PingResults results = new PingResults();
Socket listeningSocket;
PingResults results = new();
int bufferSize = 4096;

// Create listener socket
try
{
listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
listeningSocket.Bind(new IPEndPoint(address, 0));
#pragma warning disable CA1416 // Validate platform compatibility - We shouldn't be running listen mode on non windows platform
listeningSocket.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 }); // Set SIO_RCVALL flag to socket IO control
#pragma warning restore CA1416 // Validate platform compatibility
listeningSocket.ReceiveBufferSize = bufferSize;
}
catch (Exception e)
Expand All @@ -127,10 +139,11 @@ public static void ListenForICMPOnAddress(IPAddress address)
// 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);
ICMP response = new(buffer, bytesRead);
string remoteEndPointIp = remoteEndPoint.ToString() ?? string.Empty;

// Display captured packet
ConsoleDisplay.CapturedPacket(address.ToString(), response, remoteEndPoint.ToString(), DateTime.Now.ToString("h:mm:ss.ff tt"), bytesRead);
ConsoleDisplay.CapturedPacket(address.ToString(), response, remoteEndPointIp, DateTime.Now.ToString("h:mm:ss.ff tt"), bytesRead);

// Store results
results.CountPacketType(response.Type);
Expand All @@ -145,7 +158,8 @@ public static void ListenForICMPOnAddress(IPAddress address)
}
}

listeningSocket.Close();
// No nice way to cancel from listening and close socket. Just to got to hope/assume runtime does it when the thread is killed.
//listeningSocket.Close();
}
}
}
46 changes: 42 additions & 4 deletions src/Commands/Lookup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Xml;

namespace PowerPing
Expand Down Expand Up @@ -57,6 +59,39 @@ public static string GetLocalAddress()
/// <param name="detailed">Display detailed or simplified location info</param>
public static string GetAddressLocationInfo(string addr, bool detailed)
{
//using (HttpClient webClient = new())
//{
// try
// {
// string jsonResult = string.Empty;
// webClient.DefaultRequestHeaders.Add("User-Agent", "PowerPing (version_check)");
// webClient.BaseAddress = new Uri(@"http://api.github.com/repos/killeroo/powerping/releases/latest");
// webClient.GetStringAsync(jsonResult).GetAwaiter().GetResult();

// Dictionary<string, string>? jsonTable = JsonSerializer.Deserialize<Dictionary<string, string>>(jsonResult);

// // Extract version from returned json
// if (jsonTable.ContainsKey("tag_name"))
// {
// string matchString = jsonTable["tag_name"];
// Version theirVersion = new(matchString.Split(':')[1].Replace("\"", string.Empty).Replace("v", string.Empty));
// Version? ourVersion = Assembly.GetExecutingAssembly().GetName().Version;

// if (theirVersion > ourVersion)
// {
// Console.WriteLine();
// Console.WriteLine("=========================================================");
// Console.WriteLine("A new version of PowerPing is available ({0})", theirVersion);
// Console.WriteLine("Download the new version at: {0}", @"https://github.com/killeroo/powerping/releases/latest");
// Console.WriteLine("=========================================================");
// Console.WriteLine();
// }
// }
// }
// catch (Exception) { } // We just want to blanket catch any exception and silently continue
//}


string result = "";

try
Expand All @@ -70,7 +105,7 @@ public static string GetAddressLocationInfo(string addr, bool detailed)
$"http://api.ipstack.com/{addr}?access_key={key}&output=xml");

// Load xml file into object
XmlDocument xmlDoc = new XmlDocument();
XmlDocument xmlDoc = new();
xmlDoc.LoadXml(downloadedText);
XmlNodeList elements = (xmlDoc.DocumentElement).ChildNodes;

Expand Down Expand Up @@ -121,7 +156,7 @@ public static string GetAddressLocationInfo(string addr, bool detailed)
/// <returns></returns>
public static string QueryDNS(string address, AddressFamily af)
{
IPAddress ipAddr = null;
IPAddress? ipAddr;

// Check address format
if (Uri.CheckHostName(address) == UriHostNameType.Unknown)
Expand Down Expand Up @@ -154,9 +189,12 @@ public static string QueryDNS(string address, AddressFamily af)
if (ipAddr == null)
{
Helper.ErrorAndExit("PowerPing could not find host [" + address + "] " + Environment.NewLine + "Check address and try again.");
return string.Empty;
}
else
{
return ipAddr.ToString();
}

return ipAddr.ToString();
}

/// <summary>
Expand Down
18 changes: 12 additions & 6 deletions src/Commands/Scan.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,29 @@ public class HostInformation
public string Address { get; set; }
public string HostName { get; set; }
public double ResponseTime { get; set; }

public HostInformation()
{
Address = string.Empty;
HostName = string.Empty;
}
}

private static volatile bool _cancelled = false;

public static void Start(string range, CancellationToken cancellationToken)
{
List<string> addresses = new List<string>();
List<HostInformation> activeHosts = new List<HostInformation>();
Stopwatch timer = new Stopwatch();
List<string> addresses = new();
List<HostInformation> activeHosts = new();
Stopwatch timer = new();

// Get addresses to scan from range
addresses = ParseRange(range);

// Setup addresses and threads
var splitAddresses = Helper.PartitionList(addresses, THREAD_COUNT);
List<string>[] splitAddresses = Helper.PartitionList(addresses, THREAD_COUNT);
Thread[] threads = new Thread[THREAD_COUNT];
object lockObject = new object();
object lockObject = new();
int scanned = 0;

// Run the threads
Expand All @@ -72,7 +78,7 @@ public static void Start(string range, CancellationToken cancellationToken)

// Send ping
PingResults results = ping.Send(host);
if (results.ScanWasCanceled) {
if (results.ScanWasCancelled) {
// Cancel was requested during scan
throw new OperationCanceledException();
}
Expand Down
25 changes: 19 additions & 6 deletions src/Display/ConsoleDisplay.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace PowerPing
/// </summary>
internal class ConsoleDisplay
{
public static DisplayConfiguration? Configuration { get; set; }
public static DisplayConfiguration Configuration { get; set; } = new DisplayConfiguration();
public static CancellationToken CancellationToken { get; set; }

// Stores console cursor position, used for updating text at position
Expand Down Expand Up @@ -133,7 +133,7 @@ public static void SetAsciiReplySymbolsTheme(int theme)
public static void Version()
{
string assemblyVersion = Helper.GetVersionString();
string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
string assemblyName = Assembly.GetExecutingAssembly().GetName().Name ?? string.Empty;

Console.WriteLine(assemblyName + " " + assemblyVersion);
}
Expand All @@ -146,8 +146,6 @@ public static void Help()
// Print help message
Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + " " + Helper.GetVersionString());
Console.WriteLine(ProgramStrings.HELP_MSG);

Helper.CheckRecentVersion();
}

/// <summary>
Expand Down Expand Up @@ -696,7 +694,7 @@ public static void Timeout(int seq)
/// Display error message
/// </summary>
/// <param name="errMsg">Error message to display</param>
public static void Error(string errMsg, Exception e = null)
public static void Error(string errMsg, Exception e)
{
Console.ForegroundColor = ConsoleColor.Yellow;
string errorText = (e != null ? $"{errMsg} ({e.GetType().Name})" : errMsg);
Expand All @@ -708,7 +706,22 @@ public static void Error(string errMsg, Exception e = null)
ResetColor();
}

public static void Fatal(string errMsg, Exception e = null)
/// <summary>
/// Display error message
/// </summary>
/// <param name="errMsg">Error message to display</param>
public static void Error(string errMsg)
{
Console.ForegroundColor = ConsoleColor.Yellow;

// Write error message
Console.WriteLine(errMsg);

// Reset console colours
ResetColor();
}

public static void Fatal(string errMsg, Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
string errorText = (e != null ? $"{errMsg} ({e.GetType().Name})" : errMsg);
Expand Down
32 changes: 17 additions & 15 deletions src/Display/ConsoleMessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
{
public class ConsoleMessageHandler
{
public DisplayConfiguration DisplayConfig = new DisplayConfiguration();
public PingAttributes Attributes = new PingAttributes();
public CancellationToken Token = new CancellationToken();
public DisplayConfiguration DisplayConfig = new();
public PingAttributes Attributes = new();
public CancellationToken Token = new();

public ConsoleMessageHandler(DisplayConfiguration config, CancellationToken token)
{
DisplayConfig = config;
Attributes = new();
DisplayConfig = config ?? new DisplayConfiguration();
Token = token;
}

Expand All @@ -17,9 +18,6 @@ public void OnError(PingError error)
if (error.Fatal)
{
ConsoleDisplay.Fatal(error.Message, error.Exception);

// Exit on fatal error
Helper.ExitWithError();
}
else
{
Expand All @@ -36,19 +34,23 @@ public void OnReply(PingReply response)
{
// Determine what form the response address is going to be displayed in
// TODO: Move this when lookup refactor is done
string responseAddress = response.Endpoint.ToString();
if (DisplayConfig.UseResolvedAddress)
string responseAddress = response.EndpointAddress;
if (responseAddress == string.Empty || DisplayConfig.UseInputtedAddress)
{
if (Attributes != null && Attributes.InputtedAddress != null)
{
responseAddress = Attributes.InputtedAddress;
}
}
else if (DisplayConfig.UseResolvedAddress)
{

// Returned address normally have port at the end (eg 8.8.8.8:0) so we need to remove that before trying to query the DNS
string responseIP = responseAddress.ToString().Split(':')[0];
string responseIP = responseAddress.Split(':')[0];

// Resolve the ip and store as the response address
responseAddress = Helper.RunWithCancellationToken(() => Lookup.QueryHost(responseIP), Token);
}
else if (DisplayConfig.UseInputtedAddress)
{
responseAddress = Attributes.InputtedAddress;
}

ConsoleDisplay.ReplyPacket(
response.Packet,
Expand All @@ -57,7 +59,7 @@ public void OnReply(PingReply response)
response.RoundTripTime,
response.BytesRead);

if (Attributes.BeepMode == 2)
if (Attributes != null && Attributes.BeepMode == 2)
{
try { Console.Beep(); }
catch (Exception) { } // Silently continue if Console.Beep errors
Expand Down
2 changes: 1 addition & 1 deletion src/File/LogMessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ internal void OnReply(PingReply reply)
_logFile.Append($"[{_destinationAddress}] " +
$"[{reply.Timestamp.ToString(DATETIME_STRING_FORMAT)}] " +
$"[REPLY] " +
$"endpoint={reply.Endpoint.ToString()} " +
$"endpoint={reply.EndpointAddress} " +
$"seq={reply.SequenceNumber} " +
$"bytes={reply.BytesRead} " +
$"type={reply.Packet.Type} " +
Expand Down
Loading

0 comments on commit d8e7fed

Please sign in to comment.