mirror of
https://github.com/Stone-Red-Code/ARP-Scanner.git
synced 2026-09-04 00:46:04 +02:00
Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25b95d7605 | ||
|
|
e5f69fd256 | ||
|
|
a99903eec6 | ||
|
|
e6943924cc | ||
|
|
cb5a4f2fe3 | ||
|
|
edc7ea95dd | ||
|
|
4c38d52709 | ||
|
|
c094f0400e | ||
|
|
975e7b7d59 | ||
|
|
7e043c2fe2 | ||
|
|
6e86058862 | ||
|
|
1b5278bf09 | ||
|
|
701cd8e3fc | ||
|
|
ae8055fac8 | ||
|
|
11a45e1cc6 | ||
|
|
08b84f3dad | ||
|
|
a06dfe82a8 | ||
|
|
3c5d165ebb | ||
|
|
553fd97e2a | ||
|
|
5ceee1092f | ||
|
|
9f49f2d595 | ||
|
|
92b1fd0598 | ||
|
|
6f6a2c2ee5 | ||
|
|
687b882d5e | ||
|
|
95774eaee8 | ||
|
|
6de6edbf48 | ||
|
|
dabc878624 | ||
|
|
1420655b8d | ||
|
|
96b261238e | ||
|
|
89f1401de9 | ||
|
|
924e0016cb | ||
|
|
40cb53d037 | ||
|
|
a0c2811fae | ||
|
|
a4536f05d8 | ||
|
|
38ea2e99c7 | ||
|
|
3263d1bdae | ||
|
|
ab327d9312 | ||
|
|
9da39c3731 | ||
|
|
a8eaa849f2 | ||
|
|
8e1f610928 | ||
|
|
a1f5e7fe05 |
@@ -1,22 +1,32 @@
|
||||
# ARP-Scanner
|
||||
|
||||
> A lightweight cross-platform IP scanner
|
||||

|
||||
|
||||
## Usage
|
||||
|
||||
1. Download the latest release
|
||||
1. Download & install the latest release
|
||||
- Chocolatey (Windows): `choco install arp-scanner`
|
||||
- Snapcraft (Linux): `snap install arp-scanner`\
|
||||
and `snap connect arp-scanner:network-control` to give it permission to send arp requests
|
||||
- GitHub (Windows/Linux): https://github.com/Stone-Red-Code/ARP-Scanner/releases
|
||||
1. Start `arp-scanner` with the IP range it should scan as parameter (e.g. `192.168.1.0 - 192.168.1.255`)
|
||||
- Snapcraft (Linux): `snap install arp-scanner`
|
||||
- GitHub (Windows/Linux): [releases](https://github.com/Stone-Red-Code/ARP-Scanner/releases)
|
||||
1. Use the `arp-scanner` command
|
||||
- `arp-scanner help` lists all available commands
|
||||
- `arp-scanner scan` scans the network for devices
|
||||
- `arp-scanner scan --help` lists all available options for the scan command
|
||||
- `arp-scanner monitor` continuously scans the network for devices
|
||||
- `arp-scanner monitor --help` lists all available options for the monitor command
|
||||
|
||||
> Note: This programm may not work on all linux distributions because the [ArpLookup](https://github.com/georg-jung/ArpLookup) library has some [limitations](https://github.com/georg-jung/ArpLookup#supported-platforms)
|
||||
> [!Note]
|
||||
> This programm may not work on all linux distributions because the [ArpLookup](https://github.com/georg-jung/ArpLookup) library has some [limitations](https://github.com/georg-jung/ArpLookup#supported-platforms)
|
||||
|
||||
## Follow the development
|
||||
|
||||
[](https://twitter.com/search?q=%23ArpScanner%20%40StoneRedCode&f=live)
|
||||
|
||||
## Example
|
||||
|
||||
Start `arp-scanner` with the IP range it should scan as parameter (e.g. `192.168.1.0-192.168.1.255`)
|
||||

|
||||
|
||||
|
||||
## Third party licenses
|
||||
|
||||
- [ArpLookup](https://github.com/georg-jung/ArpLookup) - [MIT](https://github.com/georg-jung/ArpLookup/blob/master/LICENSE.txt)
|
||||
- [IPAddressRange](https://github.com/jsakamoto/ipaddressrange) - [MPL-2.0](https://github.com/jsakamoto/ipaddressrange/blob/master/LICENSE)
|
||||
- [Humanizer](https://github.com/Humanizr/Humanizer) - [MIT](https://github.com/Humanizr/Humanizer/blob/main/license.txt)
|
||||
|
||||
+17
-12
@@ -40,7 +40,7 @@ enclosed in quotation marks, you should use an editor that supports UTF-8, not t
|
||||
<!-- Note that unstable versions like 0.0.1 can be considered a released version, but it's
|
||||
possible that one can release a 0.0.1-beta before you release a 0.0.1 version. If the version
|
||||
number is final, that is considered a released version and not a prerelease. -->
|
||||
<version>0.2.0.0</version>
|
||||
<version>1.1.0.20250627</version>
|
||||
<!-- <packageSourceUrl>Where is this Chocolatey package located (think GitHub)? packageSourceUrl
|
||||
is highly recommended for the community feed</packageSourceUrl>-->
|
||||
<!-- owners is a poor name for maintainers of the package. It sticks around by this name for
|
||||
@@ -67,26 +67,31 @@ enclosed in quotation marks, you should use an editor that supports UTF-8, not t
|
||||
<!--<docsUrl>At
|
||||
what url are the software docs located?</docsUrl>-->
|
||||
<!--<mailingListUrl></mailingListUrl>-->
|
||||
<!--<bugTrackerUrl></bugTrackerUrl>-->
|
||||
<tags>arp-scanner arp p2p fiel-transfer</tags>
|
||||
<bugTrackerUrl>https://github.com/Stone-Red-Code/ARP-Scanner/issues</bugTrackerUrl>
|
||||
<tags>arp-scanner arp</tags>
|
||||
<summary>A lightweight cross-platform IP scanner</summary>
|
||||
<description>
|
||||
**Usage**
|
||||
|
||||
1. Download the latest release
|
||||
- Chocolatey (Windows): `choco install arp-scanner --version=0.2.0`
|
||||
- Snapcraft (Linux): `snap install arp-scanner`\
|
||||
and `snap connect arp-scanner:network-control` to give it permission to send arp requests
|
||||
- GitHub (Windows/Linux): https://github.com/Stone-Red-Code/ARP-Scanner/releases
|
||||
1. Start `arp-scanner` with the IP range it should scan as parameter (e.g. `192.168.1.0 - 192.168.1.255`)
|
||||
1. Download & install the latest release
|
||||
- Chocolatey (Windows): `choco install arp-scanner`
|
||||
- Snapcraft (Linux): `snap install arp-scanner`
|
||||
- GitHub (Windows/Linux): releases (https://github.com/Stone-Red-Code/ARP-Scanner/releases)
|
||||
2. Use the `arp-scanner` command
|
||||
- `arp-scanner help` lists all available commands
|
||||
- `arp-scanner scan` scans the network for devices
|
||||
- `arp-scanner scan --help` lists all available options for the scan command
|
||||
- `arp-scanner monitor` continuously scans the network for devices
|
||||
- `arp-scanner monitor --help` lists all available options for the monitor command
|
||||
|
||||
> Note: This programm may not work on all linux distributions because the [ArpLookup](https://github.com/georg-jung/ArpLookup) library has some [limitations](https://github.com/georg-jung/ArpLookup#supported-platforms)
|
||||
Note: This programm may not work on all linux distributions because the ArpLookup (https://github.com/georg-jung/ArpLookup) library has some limitations (https://github.com/georg-jung/ArpLookup#supported-platforms)
|
||||
|
||||
**Third party licenses**
|
||||
- ArpLookup (https://github.com/georg-jung/ArpLookup) - MIT (https://github.com/georg-jung/ArpLookup/blob/master/LICENSE.txt)
|
||||
- IPAddressRange (https://github.com/jsakamoto/ipaddressrange) - MPL-2.0 (https://github.com/jsakamoto/ipaddressrange/blob/master/LICENSE)
|
||||
- Humanizer (https://github.com/Humanizr/Humanizer) - MIT (https://github.com/Humanizr/Humanizer/blob/main/license.txt)
|
||||
</description>
|
||||
<!-- <releaseNotes>__REPLACE_OR_REMOVE__MarkDown_Okay</releaseNotes> -->
|
||||
<releaseNotes>https://github.com/Stone-Red-Code/ARP-Scanner/releases/latest</releaseNotes>
|
||||
<!-- =============================== -->
|
||||
|
||||
<!-- Specifying dependencies and version ranges?
|
||||
@@ -112,6 +117,6 @@ enclosed in quotation marks, you should use an editor that supports UTF-8, not t
|
||||
<files>
|
||||
<!-- this section controls what actually gets packaged into the Chocolatey package -->
|
||||
<file src="tools\**" target="tools" />
|
||||
<file src="..\src\ARP-Scanner\bin\Release\net6.0\**" target="tools" />
|
||||
<file src="..\src\ARP-Scanner\bin\Release\net8.0\**" target="tools" />
|
||||
</files>
|
||||
</package>
|
||||
@@ -2,5 +2,7 @@
|
||||
Verification is intended to assist the Chocolatey moderators and community
|
||||
in verifying that this package's contents are trustworthy.
|
||||
|
||||
Checksum: c37a793bae228da768c9d4223d12608bfa28decbe7142e9ac19a49795cf23b82b2f0434032b98883343c658276bf2e4423926fbf79c65c48ae6cf11ad48d37ad
|
||||
Veify using: certutil -hashfile ARP-Scanner.exe sha512
|
||||
Source Code: https://github.com/Stone-Red-Code/Arp-Scanner
|
||||
Releases: https://github.com/Stone-Red-Code/ARP-Scanner/releases
|
||||
Checksum: 551d33306839687dcb226e5290e4bb4d3d5786a9231799e0dba9f9c2a3b4711c346bf2aeb29f4fab54008b6b19c88ebb2649c6545343d41b11bed6b034407374
|
||||
Verify using: certutil -hashfile C:\ProgramData\Chocolatey\lib\arp-scanner\ARP-Scanner.exe sha512
|
||||
+16
-13
@@ -1,25 +1,28 @@
|
||||
name: arp-scanner # you probably want to 'snapcraft register <name>'
|
||||
version: "0.2.0.0" # just for humans, typically '1.2+git' or '1.3.2'
|
||||
version: "1.1.0.20250627" # just for humans, typically '1.2+git' or '1.3.2'
|
||||
grade: stable # must be 'stable' to release into candidate/stable channels
|
||||
summary: A lightweight cross-platform IP scanner # 79 char long summary
|
||||
description: |
|
||||
**Usage**
|
||||
|
||||
1. Download the latest release
|
||||
- Chocolatey (Windows): `choco install arp-scanner --version=0.2.0`
|
||||
- Snapcraft (Linux): `snap install arp-scanner`\
|
||||
and `snap connect arp-scanner:network-control` to give it permission to send arp requests
|
||||
- GitHub (Windows/Linux): https://github.com/Stone-Red-Code/ARP-Scanner/releases
|
||||
1. Start `arp-scanner` with the IP range it should scan as parameter (e.g. `192.168.1.0 - 192.168.1.255`)
|
||||
1. Download & install the latest release
|
||||
- Chocolatey (Windows): `choco install arp-scanner`
|
||||
- Snapcraft (Linux): `snap install arp-scanner`
|
||||
- GitHub (Windows/Linux): releases (https://github.com/Stone-Red-Code/ARP-Scanner/releases)
|
||||
2. Use the `arp-scanner` command
|
||||
- `arp-scanner help` lists all available commands
|
||||
- `arp-scanner scan` scans the network for devices
|
||||
- `arp-scanner scan --help` lists all available options for the scan command
|
||||
- `arp-scanner monitor` continuously scans the network for devices
|
||||
- `arp-scanner monitor --help` lists all available options for the monitor command
|
||||
|
||||
> Note: This programm may not work on all linux distributions because the [ArpLookup](https://github.com/georg-jung/ArpLookup) library has some [limitations](https://github.com/georg-jung/ArpLookup#supported-platforms)
|
||||
> Note: This programm may not work on all linux distributions because the ArpLookup (https://github.com/georg-jung/ArpLookup) library has some limitations (https://github.com/georg-jung/ArpLookup#supported-platforms)
|
||||
|
||||
**Third party licenses**
|
||||
- ArpLookup (https://github.com/georg-jung/ArpLookup) - MIT (https://github.com/georg-jung/ArpLookup/blob/master/LICENSE.txt)
|
||||
- IPAddressRange (https://github.com/jsakamoto/ipaddressrange) - MPL-2.0 (https://github.com/jsakamoto/ipaddressrange/blob/master/LICENSE)
|
||||
|
||||
- Humanizer (https://github.com/Humanizr/Humanizer) - MIT (https://github.com/Humanizr/Humanizer/blob/main/license.txt)
|
||||
base: core22 # the base snap is the execution environment for this snap
|
||||
|
||||
architectures:
|
||||
- build-on: amd64
|
||||
- build-on: arm64
|
||||
@@ -34,7 +37,7 @@ parts:
|
||||
dotnet-self-contained-runtime-identifier: linux-x64
|
||||
source: ./src/ARP-Scanner
|
||||
build-packages:
|
||||
- dotnet-sdk-6.0
|
||||
- dotnet-sdk-8.0
|
||||
stage-packages:
|
||||
- libicu70
|
||||
|
||||
@@ -42,5 +45,5 @@ apps:
|
||||
arp-scanner:
|
||||
command: ARP-Scanner
|
||||
plugs:
|
||||
- network
|
||||
- network-control
|
||||
- network-observe
|
||||
- home
|
||||
|
||||
@@ -2,22 +2,20 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<RootNamespace>ARP_Scanner</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<Version>1.1.0.20250627</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ArpLookup" Version="2.0.3" />
|
||||
<PackageReference Include="IPAddressRange" Version="6.0.0" />
|
||||
<PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.3.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="mac-vendors.csv">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<PackageReference Include="CommandLineParser" Version="2.9.1" />
|
||||
<PackageReference Include="CuteUtils" Version="1.1.1" />
|
||||
<PackageReference Include="Humanizer" Version="2.14.1" />
|
||||
<PackageReference Include="IPAddressRange" Version="6.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
namespace ARP_Scanner;
|
||||
|
||||
internal class JsonResult
|
||||
{
|
||||
public IEnumerable<HostInformation> Hosts { get; set; } = [];
|
||||
|
||||
public IEnumerable<HostInformation> NewHosts { get; set; } = [];
|
||||
|
||||
public IEnumerable<HostInformation> RemovedHosts { get; set; } = [];
|
||||
|
||||
public static JsonResult Parse(IEnumerable<string[]> activeHosts, List<string[]> previousHosts)
|
||||
{
|
||||
JsonResult result = new JsonResult
|
||||
{
|
||||
Hosts = activeHosts.Select(HostInformation.Parse)
|
||||
};
|
||||
|
||||
if (previousHosts.Count == 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
result.NewHosts = result.Hosts.Where(host => !previousHosts.Exists(previousHost => previousHost[1] == host.Mac));
|
||||
result.RemovedHosts = previousHosts.Where(previousHost => !result.Hosts.Any(host => host.Mac == previousHost[1])).Select(HostInformation.Parse);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public class HostInformation
|
||||
{
|
||||
public required string Ip { get; set; }
|
||||
public required string Mac { get; set; }
|
||||
public required string VendorName { get; set; }
|
||||
public required string BlockType { get; set; }
|
||||
public bool? Private { get; set; }
|
||||
public required string LastUpdate { get; set; }
|
||||
|
||||
public static HostInformation Parse(string[] row)
|
||||
{
|
||||
bool success = bool.TryParse(row[4], out bool isPrivate);
|
||||
|
||||
return new HostInformation
|
||||
{
|
||||
Ip = row[0],
|
||||
Mac = row[1],
|
||||
VendorName = row[2],
|
||||
BlockType = row[3],
|
||||
Private = success ? isPrivate : null,
|
||||
LastUpdate = row[5]
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace ARP_Scanner;
|
||||
|
||||
internal class MacDatabase
|
||||
{
|
||||
public DateTime LastUpdate { get; set; }
|
||||
public List<MacInformation> MacInformations { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ARP_Scanner;
|
||||
|
||||
internal class MacInformation
|
||||
{
|
||||
[JsonPropertyName("macPrefix")]
|
||||
public required string MacPrefix { get; set; }
|
||||
|
||||
[JsonPropertyName("vendorName")]
|
||||
public required string VendorName { get; set; }
|
||||
|
||||
[JsonPropertyName("private")]
|
||||
public bool? Private { get; set; }
|
||||
|
||||
[JsonPropertyName("blockType")]
|
||||
public required string BlockType { get; set; }
|
||||
|
||||
[JsonPropertyName("lastUpdate")]
|
||||
public required string LastUpdate { get; set; }
|
||||
}
|
||||
@@ -1,57 +1,121 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using CuteUtils.Misc;
|
||||
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ARP_Scanner;
|
||||
|
||||
internal class MacVendorLookup
|
||||
internal partial class MacVendorLookup
|
||||
{
|
||||
public readonly string[] header;
|
||||
private readonly string[][] fields;
|
||||
private const string macLookupUrl = "https://maclookup.app/downloads/json-database/get-db";
|
||||
private readonly HttpClient httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(20) };
|
||||
|
||||
public MacVendorLookup(string csvPath)
|
||||
private MacDatabase macDatabase = new MacDatabase();
|
||||
|
||||
public async Task Initialize(bool silent)
|
||||
{
|
||||
if (!File.Exists(csvPath))
|
||||
if (macDatabase.MacInformations.Count != 0)
|
||||
{
|
||||
header = Array.Empty<string>();
|
||||
fields = Array.Empty<string[]>();
|
||||
// Already initialized
|
||||
return;
|
||||
}
|
||||
|
||||
string[] lines = File.ReadAllLines(csvPath);
|
||||
string cachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "macDatabase.json");
|
||||
|
||||
header = lines[0].Split(',');
|
||||
fields = lines.Skip(1).Select(l => Regex.Split(l, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))")).ToArray();
|
||||
// Snap support
|
||||
string? snapUserCommon = Environment.GetEnvironmentVariable("SNAP_USER_COMMON");
|
||||
|
||||
if (snapUserCommon is not null)
|
||||
{
|
||||
cachePath = Path.Combine(snapUserCommon, "macDatabase.json");
|
||||
}
|
||||
|
||||
public string[] GetInformation(string macAdress)
|
||||
if (File.Exists(cachePath))
|
||||
{
|
||||
string[]? data = Array.Find(fields, f => macAdress.StartsWith(f[0]));
|
||||
try
|
||||
{
|
||||
macDatabase = JsonSerializer.Deserialize<MacDatabase>(File.ReadAllText(cachePath)) ?? new MacDatabase();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!silent)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Failed to read MAC database cache: {ex.Message}", ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (fields.Length == 0 || header.Length == 0)
|
||||
// Update MAC database if it's older than a week
|
||||
if (macDatabase.LastUpdate > DateTime.Now.AddDays(-7))
|
||||
{
|
||||
return Array.Empty<string>();
|
||||
if (!silent)
|
||||
{
|
||||
ConsoleExt.WriteLine("Using cached MAC database...", ConsoleColor.DarkYellow);
|
||||
}
|
||||
else if (data is null)
|
||||
{
|
||||
string[] result = new string[header.Length - 1];
|
||||
for (int i = 0; i < result.Length; i++)
|
||||
{
|
||||
result[i] = "Unknown";
|
||||
return;
|
||||
}
|
||||
return result;
|
||||
|
||||
if (!silent)
|
||||
{
|
||||
ConsoleExt.WriteLine("Downloading MAC database from maclookup.app...", ConsoleColor.DarkYellow);
|
||||
}
|
||||
|
||||
List<MacInformation>? newMacInformation = null;
|
||||
|
||||
try
|
||||
{
|
||||
newMacInformation = await httpClient.GetFromJsonAsync<List<MacInformation>>(macLookupUrl);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!silent)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Failed to download MAC database: {ex.Message}", ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
|
||||
if (newMacInformation is null)
|
||||
{
|
||||
if (silent)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (macDatabase.MacInformations.Count != 0)
|
||||
{
|
||||
ConsoleExt.WriteLine("Failed to download MAC database, using cache...", ConsoleColor.DarkYellow);
|
||||
}
|
||||
else
|
||||
{
|
||||
List<string> result = new List<string>();
|
||||
for (int i = 1; i < header.Length; i++)
|
||||
{
|
||||
result.Add($"{data[i]}");
|
||||
ConsoleExt.WriteLine("Failed to download MAC database and no cache found, using empty database...", ConsoleColor.Red);
|
||||
}
|
||||
return result.ToArray();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!silent)
|
||||
{
|
||||
ConsoleExt.WriteLine("MAC database downloaded successfully!", ConsoleColor.Green);
|
||||
}
|
||||
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(cachePath)!);
|
||||
|
||||
macDatabase.MacInformations = newMacInformation;
|
||||
macDatabase.LastUpdate = DateTime.Now;
|
||||
File.WriteAllText(cachePath, JsonSerializer.Serialize(macDatabase));
|
||||
}
|
||||
}
|
||||
|
||||
public string[] GetHeader()
|
||||
public MacInformation GetInformation(string macAddress)
|
||||
{
|
||||
return header!.Skip(1).ToArray();
|
||||
macAddress = macAddress.Replace("-", ":")[..8].ToUpper();
|
||||
|
||||
return macDatabase.MacInformations.Find(m => m.MacPrefix == macAddress) ?? new MacInformation()
|
||||
{
|
||||
MacPrefix = macAddress,
|
||||
VendorName = "Unknown",
|
||||
BlockType = "Unknown",
|
||||
Private = null,
|
||||
LastUpdate = "Unknown"
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using CommandLine;
|
||||
|
||||
namespace ARP_Scanner;
|
||||
|
||||
[Verb("monitor", HelpText = "Continuously monitor the specified IP range.")]
|
||||
internal class MonitorOptions : ScanOptions
|
||||
{
|
||||
[Option('d', "delay", Required = false, Default = 60, HelpText = "The delay between each scan in seconds.")]
|
||||
public int Delay { get; set; }
|
||||
}
|
||||
+281
-26
@@ -1,94 +1,349 @@
|
||||
using ArpLookup;
|
||||
|
||||
using CommandLine;
|
||||
|
||||
using CuteUtils.Misc;
|
||||
|
||||
using Humanizer;
|
||||
using Humanizer.Localisation;
|
||||
|
||||
using NetTools;
|
||||
|
||||
using Stone_Red_Utilities.CollectionExtentions;
|
||||
using Stone_Red_Utilities.ConsoleExtentions;
|
||||
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ARP_Scanner;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static async Task Main(string[] args)
|
||||
{
|
||||
MacVendorLookup macVendorLookup = new MacVendorLookup("mac-vendors.csv");
|
||||
private static readonly MacVendorLookup macVendorLookup = new();
|
||||
private static readonly List<string[]> previouslyActiveHosts = [];
|
||||
|
||||
private static readonly JsonSerializerOptions jsonSerializerOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
||||
};
|
||||
|
||||
private static async Task<int> Main(string[] args)
|
||||
{
|
||||
if (!Arp.IsSupported)
|
||||
{
|
||||
ConsoleExt.WriteLine("ARP is not supported on this platform!", ConsoleColor.Red);
|
||||
return;
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!IPAddressRange.TryParse(string.Join("", args), out IPAddressRange ipAddressRange))
|
||||
return await Parser.Default.ParseArguments<ScanOptions, MonitorOptions>(args)
|
||||
.MapResult(
|
||||
(MonitorOptions monitorOptions) => StartMonitor(monitorOptions),
|
||||
(ScanOptions scanOptions) => StartScan(scanOptions),
|
||||
HandleParseError);
|
||||
}
|
||||
|
||||
private static async Task<int> StartMonitor(MonitorOptions options)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Monitoring IP range '{options.IpRange}' every {options.Delay} seconds...", ConsoleColor.DarkYellow);
|
||||
|
||||
while (true)
|
||||
{
|
||||
int exitCode = await StartScan(options);
|
||||
|
||||
if (exitCode != 0)
|
||||
{
|
||||
return exitCode;
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
|
||||
bool printed = false;
|
||||
|
||||
while (stopwatch.Elapsed < TimeSpan.FromSeconds(options.Delay))
|
||||
{
|
||||
TimeSpan remainingTime = TimeSpan.FromSeconds(options.Delay) - stopwatch.Elapsed;
|
||||
Console.Write($"\rNext scan in: {remainingTime.Humanize(3, minUnit: TimeUnit.Second)} ");
|
||||
await Task.Delay(1000);
|
||||
printed = true;
|
||||
}
|
||||
|
||||
if (printed)
|
||||
{
|
||||
Console.Write($"\r{new string(' ', Console.WindowWidth)}\r");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<int> StartScan(ScanOptions options)
|
||||
{
|
||||
if (!IPAddressRange.TryParse(options.IpRange, out IPAddressRange ipAddressRange))
|
||||
{
|
||||
ConsoleExt.WriteLine("Invalid IP range!", ConsoleColor.Red);
|
||||
return;
|
||||
return 2;
|
||||
}
|
||||
|
||||
await macVendorLookup.Initialize(options.Silent);
|
||||
|
||||
long ipAddressesCount = ipAddressRange.Count();
|
||||
long processedIpAddressesCount = 0;
|
||||
int numberOfDigits = ipAddressesCount.ToString().Length;
|
||||
int exitCode = 0;
|
||||
|
||||
List<string> header = new List<string>() { "IP", "MAC" };
|
||||
ConcurrentBag<string[]> activeHosts = new ConcurrentBag<string[]>();
|
||||
ConcurrentBag<string[]> activeHosts = [];
|
||||
|
||||
header.AddRange(macVendorLookup.GetHeader());
|
||||
// If you want to change the header, you also need to change the JsonResult class
|
||||
List<string> header = [
|
||||
"IP",
|
||||
"MAC",
|
||||
nameof(MacInformation.VendorName).Humanize(LetterCasing.Title),
|
||||
nameof(MacInformation.BlockType).Humanize(LetterCasing.Title),
|
||||
nameof(MacInformation.Private).Humanize(LetterCasing.Title),
|
||||
nameof(MacInformation.LastUpdate).Humanize(LetterCasing.Title)];
|
||||
|
||||
if (!options.Silent)
|
||||
{
|
||||
ConsoleExt.WriteLine("Starting scan...", ConsoleColor.DarkYellow);
|
||||
}
|
||||
|
||||
await Parallel.ForEachAsync(ipAddressRange, async (IPAddress ipAddress, CancellationToken _) =>
|
||||
ParallelOptions parallelOptions = new()
|
||||
{
|
||||
MaxDegreeOfParallelism = options.Concurrency
|
||||
};
|
||||
|
||||
await Parallel.ForEachAsync(ipAddressRange, parallelOptions, async (IPAddress ipAddress, CancellationToken _) =>
|
||||
{
|
||||
PhysicalAddress? mac = null;
|
||||
bool fail = false;
|
||||
|
||||
int retry = options.Retry;
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
mac = await Arp.LookupAsync(ipAddress);
|
||||
fail = false;
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!options.Silent)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Failed to lookup MAC address for {ipAddress}: {ex.Message}", ConsoleColor.Red);
|
||||
}
|
||||
fail = true;
|
||||
}
|
||||
}
|
||||
while (retry-- > 0 && (mac is null || fail));
|
||||
|
||||
long localProcessedIpAddressesCount = Interlocked.Increment(ref processedIpAddressesCount);
|
||||
if (mac is not null)
|
||||
if (mac is not null && Array.Exists(mac.GetAddressBytes(), b => b != 0))
|
||||
{
|
||||
string formattedMac = BitConverter.ToString(mac.GetAddressBytes());
|
||||
|
||||
List<string> info = new List<string> { ipAddress.ToString(), formattedMac };
|
||||
info.AddRange(macVendorLookup.GetInformation(formattedMac));
|
||||
MacInformation macInformation = macVendorLookup.GetInformation(formattedMac);
|
||||
|
||||
List<string> info = [ipAddress.ToString(), formattedMac, macInformation.VendorName, macInformation.BlockType, macInformation.Private?.ToString() ?? "Unknown", macInformation.LastUpdate];
|
||||
if (!options.Silent)
|
||||
{
|
||||
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]);
|
||||
}
|
||||
else if (fail)
|
||||
{
|
||||
if (!options.Silent)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Progress: {localProcessedIpAddressesCount.ToString().PadLeft(numberOfDigits)}/{ipAddressesCount} [{100d / ipAddressesCount * localProcessedIpAddressesCount,6:##0.00}%] | Failed: {ipAddress}", ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!options.Silent)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Progress: {localProcessedIpAddressesCount.ToString().PadLeft(numberOfDigits)}/{ipAddressesCount} [{100d / ipAddressesCount * localProcessedIpAddressesCount,6:##0.00}%] | Inactive: {ipAddress}", ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!activeHosts.IsEmpty)
|
||||
if (previouslyActiveHosts.Count > 0 && !options.Silent)
|
||||
{
|
||||
Console.WriteLine(Environment.NewLine + "Active hosts:");
|
||||
PrintDifference(activeHosts, header);
|
||||
}
|
||||
else if (!options.Silent)
|
||||
{
|
||||
PrintActiveHosts(activeHosts, header);
|
||||
}
|
||||
|
||||
List<string[]>? activeHostsTable = activeHosts.ToList();
|
||||
if (!options.Silent && (options.JsonPath is not null || options.CsvPath is not null))
|
||||
{
|
||||
Console.WriteLine();
|
||||
}
|
||||
|
||||
activeHostsTable.Insert(0, header.ToArray());
|
||||
if (options.JsonPath is not null)
|
||||
{
|
||||
string jsonPath = GetOutputPath(options.JsonPath, ".json");
|
||||
|
||||
activeHostsTable.ToArray().To2D().PrintTable(TableStyle.List);
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(Path.GetDirectoryName(jsonPath)))
|
||||
{
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(jsonPath)!);
|
||||
}
|
||||
|
||||
ConsoleExt.WriteLine($"{Environment.NewLine}Found {activeHosts.Count} active hosts", ConsoleColor.Green);
|
||||
string json = JsonSerializer.Serialize(JsonResult.Parse([.. activeHosts], previouslyActiveHosts), jsonSerializerOptions);
|
||||
File.WriteAllText(jsonPath, json);
|
||||
|
||||
if (!options.Silent)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Saved JSON to '{jsonPath}'", ConsoleColor.Green);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!options.Silent)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Failed to save JSON to '{jsonPath}': {ex.Message}", ConsoleColor.Red);
|
||||
}
|
||||
|
||||
exitCode = 3;
|
||||
}
|
||||
}
|
||||
|
||||
if (options.CsvPath is not null)
|
||||
{
|
||||
string csvPath = GetOutputPath(options.CsvPath, ".csv");
|
||||
List<string[]>? activeHostsTable = [.. activeHosts];
|
||||
activeHostsTable.Insert(0, [.. header]);
|
||||
|
||||
try
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(Path.GetDirectoryName(csvPath)))
|
||||
{
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(csvPath)!);
|
||||
}
|
||||
|
||||
File.WriteAllLines(csvPath, activeHostsTable.Select(row => string.Join(",", row)));
|
||||
|
||||
if (!options.Silent)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Saved CSV to '{csvPath}'", ConsoleColor.Green);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!options.Silent)
|
||||
{
|
||||
ConsoleExt.WriteLine($"Failed to save CSV to '{csvPath}': {ex.Message}", ConsoleColor.Red);
|
||||
}
|
||||
|
||||
exitCode = 3;
|
||||
}
|
||||
}
|
||||
|
||||
previouslyActiveHosts.Clear();
|
||||
foreach (string[] activeHost in activeHosts)
|
||||
{
|
||||
previouslyActiveHosts.Add(activeHost);
|
||||
}
|
||||
|
||||
return exitCode;
|
||||
}
|
||||
|
||||
private static Task<int> HandleParseError(IEnumerable<Error> errors)
|
||||
{
|
||||
if (errors.IsHelp() || errors.IsVersion())
|
||||
{
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
ConsoleExt.WriteLine($"{Environment.NewLine}No active hosts found", ConsoleColor.Red);
|
||||
return Task.FromResult(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetOutputPath(string path, string extension)
|
||||
{
|
||||
string directory = Path.GetDirectoryName(path) ?? string.Empty;
|
||||
string fileName = Path.GetFileNameWithoutExtension(path);
|
||||
string fileExtension = Path.GetExtension(path);
|
||||
fileExtension = string.IsNullOrEmpty(fileExtension) ? extension : fileExtension;
|
||||
|
||||
string dateTime = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
|
||||
|
||||
string newPath = Path.Combine(directory, $"{fileName}_{dateTime}{fileExtension}");
|
||||
|
||||
int counter = 0;
|
||||
while (File.Exists(newPath))
|
||||
{
|
||||
newPath = Path.Combine(directory, $"{fileName}_{dateTime}_{++counter}{fileExtension}");
|
||||
}
|
||||
|
||||
return newPath;
|
||||
}
|
||||
|
||||
private static void PrintActiveHosts(ConcurrentBag<string[]> activeHosts, List<string> header)
|
||||
{
|
||||
List<string[]>? activeHostsTable = [.. activeHosts];
|
||||
activeHostsTable.Insert(0, [.. header]);
|
||||
|
||||
Console.WriteLine();
|
||||
|
||||
if (!activeHosts.IsEmpty)
|
||||
{
|
||||
Console.WriteLine($"Active hosts:");
|
||||
|
||||
activeHostsTable.ToArray().To2D().PrintTable(TableStyle.List);
|
||||
|
||||
ConsoleExt.WriteLine($"{Environment.NewLine}Found {"active host".ToQuantity(activeHosts.Count)}", ConsoleColor.Green);
|
||||
}
|
||||
else
|
||||
{
|
||||
ConsoleExt.WriteLine($"No active hosts found", ConsoleColor.Red);
|
||||
}
|
||||
}
|
||||
|
||||
private static void PrintDifference(ConcurrentBag<string[]> activeHosts, List<string> header)
|
||||
{
|
||||
List<string[]> newHosts = activeHosts.Where(activeHost => !previouslyActiveHosts.Exists(previousHost => previousHost[1] == activeHost[1])).ToList();
|
||||
List<string[]> removedHosts = previouslyActiveHosts.Where(previousHost => !activeHosts.Any(activeHost => activeHost[1] == previousHost[1])).ToList();
|
||||
|
||||
List<string[]>? newHostsTable = [.. newHosts];
|
||||
newHostsTable.Insert(0, [.. header]);
|
||||
|
||||
List<string[]>? removedHostsTable = [.. removedHosts];
|
||||
removedHostsTable.Insert(0, [.. header]);
|
||||
|
||||
Console.WriteLine();
|
||||
|
||||
if (newHosts.Count > 0)
|
||||
{
|
||||
Console.WriteLine($"New hosts:");
|
||||
|
||||
newHostsTable.ToArray().To2D().PrintTable(TableStyle.List);
|
||||
|
||||
ConsoleExt.WriteLine($"{Environment.NewLine}Found {"active host".ToQuantity(activeHosts.Count)}", ConsoleColor.Green);
|
||||
}
|
||||
else
|
||||
{
|
||||
ConsoleExt.WriteLine($"No new hosts found", ConsoleColor.Blue);
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
|
||||
if (removedHosts.Count > 0)
|
||||
{
|
||||
// Better term for removed host?
|
||||
Console.WriteLine($"Previously active hosts:");
|
||||
|
||||
removedHostsTable.ToArray().To2D().PrintTable(TableStyle.List);
|
||||
|
||||
ConsoleExt.WriteLine($"{Environment.NewLine}Found {"previously active host".ToQuantity(removedHosts.Count)}", ConsoleColor.Red);
|
||||
}
|
||||
else
|
||||
{
|
||||
ConsoleExt.WriteLine($"No previously active hosts are currently inactive", ConsoleColor.Blue);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"profiles": {
|
||||
"ARP-Scanner": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "192.168.1.0 - 192.168.1.255"
|
||||
"commandLineArgs": "scan 192.168.1.239"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using CommandLine;
|
||||
|
||||
namespace ARP_Scanner;
|
||||
|
||||
[Verb("scan", true, HelpText = "Scan the specified IP range.")]
|
||||
internal class ScanOptions
|
||||
{
|
||||
[Value(0, Required = true, MetaName = "IP range", HelpText = "The IP range to scan.")]
|
||||
public required string IpRange { get; set; }
|
||||
|
||||
[Option('s', "silent", Required = false, HelpText = "Don't print anything to the console.")]
|
||||
public bool Silent { get; set; }
|
||||
|
||||
[Option('r', "retry", Required = false, Default = 0, HelpText = "The number of retries for each ARP request.")]
|
||||
public int Retry { get; set; }
|
||||
|
||||
[Option('c', "concurrency", Required = false, Default = -1, HelpText = "The number of concurrent ARP requests.")]
|
||||
public int Concurrency { get; set; }
|
||||
|
||||
[Option("json", Required = false, HelpText = "The path to the JSON file to save the results.")]
|
||||
public string? JsonPath { get; set; }
|
||||
|
||||
[Option("csv", Required = false, HelpText = "The path to the CSV file to save the results.")]
|
||||
public string? CsvPath { get; set; }
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user