Fix multiple bugs and improve code

This commit is contained in:
Stone_Red
2023-12-16 18:17:51 +01:00
parent 83aeda2340
commit 97ebf4d145
4 changed files with 78 additions and 43 deletions
+1 -1
View File
@@ -10,7 +10,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="ArpLookup" Version="2.0.3" /> <PackageReference Include="ArpLookup" Version="2.0.3" />
<PackageReference Include="IPAddressRange" Version="5.0.0" /> <PackageReference Include="IPAddressRange" Version="6.0.0" />
<PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.3.1" /> <PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.3.1" />
</ItemGroup> </ItemGroup>
+52
View File
@@ -0,0 +1,52 @@
using NetTools;
using System.Diagnostics;
namespace ARP_Scanner;
internal static class ExtentionMethods
{
public static long Count(this IPAddressRange ipAddresses)
{
byte[] byteBegin = ipAddresses.Begin.GetAddressBytes();
byte[] byteEnd = ipAddresses.End.GetAddressBytes();
long sum = 1;
for (int i = byteBegin.Length - 1; i >= 0; i--)
{
if (byteEnd[i] - byteBegin[i] == 0)
{
continue;
}
sum += (long)((byteEnd[i] - byteBegin[i]) * Math.Pow(2D, (double)(byteBegin.Length - 1 - i) * 8));
Debug.WriteLine(sum);
}
return sum;
}
public static T[,] To2D<T>(this T[][] source)
{
try
{
int FirstDim = source.Length;
int SecondDim = source.GroupBy(row => row.Length).Single().Key; // throws InvalidOperationException if source is not rectangular
T[,]? result = new T[FirstDim, SecondDim];
for (int i = 0; i < FirstDim; ++i)
{
for (int j = 0; j < SecondDim; ++j)
{
result[i, j] = source[i][j];
}
}
return result;
}
catch (InvalidOperationException)
{
throw new InvalidOperationException("The given jagged array is not rectangular.");
}
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ internal class MacVendorLookup
public string[] GetInformation(string macAdress) public string[] GetInformation(string macAdress)
{ {
string[]? data = fields.FirstOrDefault(f => macAdress.StartsWith(f[0]))?.ToArray(); string[]? data = Array.Find(fields, f => macAdress.StartsWith(f[0]));
if (fields.Length == 0 || header.Length == 0) if (fields.Length == 0 || header.Length == 0)
{ {
+24 -41
View File
@@ -15,8 +15,6 @@ internal static class Program
{ {
private static async Task Main(string[] args) private static async Task Main(string[] args)
{ {
bool success = false;
IPAddress[]? ipAddresses = null;
MacVendorLookup macVendorLookup = new MacVendorLookup("mac-vendors.csv"); MacVendorLookup macVendorLookup = new MacVendorLookup("mac-vendors.csv");
if (!Arp.IsSupported) if (!Arp.IsSupported)
@@ -25,20 +23,15 @@ internal static class Program
return; return;
} }
if (args.Length >= 1) if (!IPAddressRange.TryParse(string.Join("", args), out IPAddressRange ipAddressRange))
{
success = IPAddressRange.TryParse(string.Join("", args), out IPAddressRange iPAddressRange);
ipAddresses = iPAddressRange.AsEnumerable().ToArray();
}
if (!success || ipAddresses is null)
{ {
ConsoleExt.WriteLine("Invalid IP range!", ConsoleColor.Red); ConsoleExt.WriteLine("Invalid IP range!", ConsoleColor.Red);
return; return;
} }
int ipAddressesCount = ipAddresses.Length; long ipAddressesCount = ipAddressRange.Count();
int processedIpAddressesCount = 0; long processedIpAddressesCount = 0;
int numberOfDigits = ipAddressesCount.ToString().Length;
List<string> header = new List<string>() { "IP", "MAC" }; List<string> header = new List<string>() { "IP", "MAC" };
ConcurrentBag<string[]> activeHosts = new ConcurrentBag<string[]>(); ConcurrentBag<string[]> activeHosts = new ConcurrentBag<string[]>();
@@ -47,23 +40,37 @@ internal static class Program
ConsoleExt.WriteLine("Starting scan...", ConsoleColor.DarkYellow); ConsoleExt.WriteLine("Starting scan...", ConsoleColor.DarkYellow);
await Parallel.ForEachAsync(ipAddresses, async (ipAddress, _) => await Parallel.ForEachAsync(ipAddressRange, async (IPAddress ipAddress, CancellationToken _) =>
{ {
PhysicalAddress? mac = await Arp.LookupAsync(ipAddress); PhysicalAddress? mac = null;
bool fail = false;
int localProcessedIpAddressesCount = Interlocked.Increment(ref processedIpAddressesCount); try
{
mac = await Arp.LookupAsync(ipAddress);
}
catch
{
fail = true;
}
long localProcessedIpAddressesCount = Interlocked.Increment(ref processedIpAddressesCount);
if (mac is not null) if (mac is not null)
{ {
string formattedMac = BitConverter.ToString(mac.GetAddressBytes()); string formattedMac = BitConverter.ToString(mac.GetAddressBytes());
List<string> info = new List<string> { ipAddress.ToString(), formattedMac }; List<string> info = new List<string> { ipAddress.ToString(), formattedMac };
info.AddRange(macVendorLookup.GetInformation(formattedMac)); info.AddRange(macVendorLookup.GetInformation(formattedMac));
ConsoleExt.WriteLine($"Progress: {localProcessedIpAddressesCount}/{ipAddressesCount} [{100d / ipAddressesCount * localProcessedIpAddressesCount:0.00}%] | Active: {ipAddress}", ConsoleColor.Green); ConsoleExt.WriteLine($"Progress: {localProcessedIpAddressesCount.ToString().PadLeft(numberOfDigits)}/{ipAddressesCount} [{100d / ipAddressesCount * localProcessedIpAddressesCount,6:##0.00}%] | Active: {ipAddress}", ConsoleColor.Green);
activeHosts.Add(info.ToArray()); activeHosts.Add(info.ToArray());
} }
else if (fail)
{
ConsoleExt.WriteLine($"Progress: {localProcessedIpAddressesCount.ToString().PadLeft(numberOfDigits)}/{ipAddressesCount} [{100d / ipAddressesCount * localProcessedIpAddressesCount,6:##0.00}%] | Failed: {ipAddress}", ConsoleColor.Red);
}
else else
{ {
ConsoleExt.WriteLine($"Progress: {localProcessedIpAddressesCount}/{ipAddressesCount} [{100d / ipAddressesCount * localProcessedIpAddressesCount:0.00}%] | Inactive: {ipAddress}", ConsoleColor.Red); ConsoleExt.WriteLine($"Progress: {localProcessedIpAddressesCount.ToString().PadLeft(numberOfDigits)}/{ipAddressesCount} [{100d / ipAddressesCount * localProcessedIpAddressesCount,6:##0.00}%] | Inactive: {ipAddress}", ConsoleColor.Red);
} }
}); });
@@ -75,7 +82,7 @@ internal static class Program
activeHostsTable.Insert(0, header.ToArray()); activeHostsTable.Insert(0, header.ToArray());
To2D(activeHostsTable.ToArray()).PrintTable(TableStyle.List); activeHostsTable.ToArray().To2D().PrintTable(TableStyle.List);
ConsoleExt.WriteLine($"{Environment.NewLine}Found {activeHosts.Count} active hosts", ConsoleColor.Green); ConsoleExt.WriteLine($"{Environment.NewLine}Found {activeHosts.Count} active hosts", ConsoleColor.Green);
} }
@@ -84,28 +91,4 @@ internal static class Program
ConsoleExt.WriteLine($"{Environment.NewLine}No active hosts found", ConsoleColor.Red); ConsoleExt.WriteLine($"{Environment.NewLine}No active hosts found", ConsoleColor.Red);
} }
} }
private static T[,] To2D<T>(T[][] source)
{
try
{
int FirstDim = source.Length;
int SecondDim = source.GroupBy(row => row.Length).Single().Key; // throws InvalidOperationException if source is not rectangular
T[,]? result = new T[FirstDim, SecondDim];
for (int i = 0; i < FirstDim; ++i)
{
for (int j = 0; j < SecondDim; ++j)
{
result[i, j] = source[i][j];
}
}
return result;
}
catch (InvalidOperationException)
{
throw new InvalidOperationException("The given jagged array is not rectangular.");
}
}
} }