From 69f4364cf33cd37822cd975604f49127c3e782bc Mon Sep 17 00:00:00 2001 From: Daniel Chalmers Date: Sun, 11 Oct 2026 23:24:33 -0500 Subject: [PATCH] Add option to change the ping address MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add "Ping address…" to the context menu; the address is saved with the other settings - Accept only literal IPv4/IPv6 addresses; reject names, zones, ports and leading zeros - Reset latency history and the outage clock when the address changes - Track replied networks per address, so a new silent address isn't shown as an outage - Mention the ping address and bits/bytes casing in the README --- Network Monitor.Tests/OutageTests.cs | 2 +- Network Monitor.Tests/PingAddressTests.cs | 206 +++++++++++++++++++++ Network Monitor.Tests/SettingsTests.cs | 39 ++++ Network Monitor/MainViewModel.cs | 2 +- Network Monitor/MainWindow.xaml | 3 + Network Monitor/MainWindow.xaml.cs | 10 + Network Monitor/Monitors/LatencyMonitor.cs | 58 +++++- Network Monitor/Monitors/NetworkStatus.cs | 43 ++--- Network Monitor/Monitors/Outage.cs | 8 +- Network Monitor/Monitors/PingAddress.cs | 47 +++++ Network Monitor/PingAddressDialog.xaml | 42 +++++ Network Monitor/PingAddressDialog.xaml.cs | 52 ++++++ Network Monitor/Properties/Settings.cs | 18 +- README.md | 6 +- 14 files changed, 492 insertions(+), 44 deletions(-) create mode 100644 Network Monitor.Tests/PingAddressTests.cs create mode 100644 Network Monitor/Monitors/PingAddress.cs create mode 100644 Network Monitor/PingAddressDialog.xaml create mode 100644 Network Monitor/PingAddressDialog.xaml.cs diff --git a/Network Monitor.Tests/OutageTests.cs b/Network Monitor.Tests/OutageTests.cs index 3617aa0..4ed8b36 100644 --- a/Network Monitor.Tests/OutageTests.cs +++ b/Network Monitor.Tests/OutageTests.cs @@ -141,7 +141,7 @@ public void Decide_OnANetworkThatHasNeverReplied_SaysItMayBlockPing() Assert.Equal("—", view.Value); Assert.False(view.IsOutage); Assert.True(view.IsBlockedNetwork); - Assert.Equal("No replies on this network yet. It may block ping.", view.NoteLine); + Assert.Equal("No replies on this network yet. It or the address may block ping.", view.NoteLine); } [Fact] diff --git a/Network Monitor.Tests/PingAddressTests.cs b/Network Monitor.Tests/PingAddressTests.cs new file mode 100644 index 0000000..3850ce9 --- /dev/null +++ b/Network Monitor.Tests/PingAddressTests.cs @@ -0,0 +1,206 @@ +using System.Net; +using Network_Monitor.Monitors; + +namespace Network_Monitor.Tests; + +public class PingAddressTests +{ + [Theory] + [InlineData("8.8.8.8")] + [InlineData("1.1.1.1")] + [InlineData("192.168.1.1")] + [InlineData("10.0.0.138")] + [InlineData("127.0.0.1")] + [InlineData("1.0.0.0")] + [InlineData("100.64.0.1")] + [InlineData("169.254.1.1")] + [InlineData("223.255.255.255")] + [InlineData("240.0.0.1")] + [InlineData("255.255.255.254")] + public void TryParse_TakesAPlainIPv4Address(string text) + { + Assert.True(PingAddress.TryParse(text, out var address)); + Assert.Equal(IPAddress.Parse(text), address); + } + + [Theory] + [InlineData("2001:4860:4860::8888", "2001:4860:4860:0:0:0:0:8888")] + [InlineData("2001:4860:4860:0:0:0:0:8888", "2001:4860:4860:0:0:0:0:8888")] + [InlineData("2001:4860:4860:0000:0000:0000:0000:8888", "2001:4860:4860:0:0:0:0:8888")] + [InlineData("2606:4700:4700::1111", "2606:4700:4700:0:0:0:0:1111")] + [InlineData("2001:DB8::A", "2001:db8:0:0:0:0:0:a")] + [InlineData("::1", "0:0:0:0:0:0:0:1")] + [InlineData("1::", "1:0:0:0:0:0:0:0")] + [InlineData("fe80::1", "fe80:0:0:0:0:0:0:1")] + [InlineData("fd00::1:2", "fd00:0:0:0:0:0:1:2")] + [InlineData("1:2:3:4:5:6:7:8", "1:2:3:4:5:6:7:8")] + [InlineData("1:2:3:4:5:6::8", "1:2:3:4:5:6:0:8")] + [InlineData("::2:3:4:5:6:7:8", "0:2:3:4:5:6:7:8")] + [InlineData("1:2:3:4:5:6:7::", "1:2:3:4:5:6:7:0")] + [InlineData("64:ff9b::8.8.8.8", "64:ff9b:0:0:0:0:808:808")] + [InlineData("1:2:3:4:5:6:8.8.8.8", "1:2:3:4:5:6:808:808")] + public void TryParse_TakesAnIPv6Address(string text, string written) + { + Assert.True(PingAddress.TryParse(text, out var address)); + Assert.Equal(IPAddress.Parse(written), address); + Assert.Equal(0, address.ScopeId); + } + + [Theory] + [InlineData(" 8.8.8.8")] + [InlineData("8.8.8.8 ")] + [InlineData("\t8.8.8.8\r\n")] + [InlineData(" 8.8.8.8 ")] // Like one pasted from a web page. + public void TryParse_IgnoresSpacesAround(string text) + { + Assert.True(PingAddress.TryParse(text, out var address)); + Assert.Equal(IPAddress.Parse("8.8.8.8"), address); + } + + [Fact] + public void TryParse_IgnoresSpacesAroundAnIPv6Address() + { + Assert.True(PingAddress.TryParse(" 2001:4860:4860::8888 ", out var address)); + Assert.Equal(IPAddress.Parse("2001:4860:4860::8888"), address); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void TryParse_WithNothingTyped_IsFalse(string text) + { + Assert.False(PingAddress.TryParse(text, out var address)); + Assert.Null(address); + } + + [Theory] + [InlineData("google.com")] + [InlineData("dns.google")] + [InlineData("localhost")] + [InlineData("router")] + [InlineData("one.one.one.one")] + [InlineData("8.8.8.8.in-addr.arpa")] + [InlineData("xn--bcher-kva.example")] + [InlineData("http://8.8.8.8")] + [InlineData("\\\\8.8.8.8")] + public void TryParse_RejectsNames(string text) + { + Assert.False(PingAddress.TryParse(text, out var address)); + Assert.Null(address); + } + + [Theory] + [InlineData("1")] // IPAddress.TryParse takes this as 0.0.0.1. + [InlineData("8")] + [InlineData("134744072")] // 8.8.8.8 as one number. + [InlineData("1.2")] + [InlineData("1.2.3")] // 1.2.0.3. + [InlineData("1.2.3.4.5")] + [InlineData("0x7f.1")] // 127.0.0.1. + [InlineData("0x08.8.8.8")] + [InlineData("0X8.8.8.8")] + [InlineData("010.1.1.1")] // Octal, so 8.1.1.1. + [InlineData("08.8.8.8")] + [InlineData("8.8.8.08")] + [InlineData("8.8.08.8")] + [InlineData("00.1.1.1")] + [InlineData("0008.8.8.8")] + [InlineData("256.1.1.1")] + [InlineData("8.8.8.256")] + [InlineData("999.8.8.8")] + [InlineData("-1.8.8.8")] + [InlineData("+8.8.8.8")] + [InlineData("8.8.8.-8")] + [InlineData("8..8.8")] + [InlineData(".8.8.8.8")] + [InlineData("8.8.8.8.")] + [InlineData("8.8.8.")] + [InlineData("8 .8.8.8")] + [InlineData("8.8. 8.8")] + [InlineData("8.8.8.8x")] + [InlineData("8,8,8,8")] + [InlineData("8.8.8.8/32")] + [InlineData("٨.٨.٨.٨")] // Arabic-Indic digits, which char.IsDigit takes. + [InlineData("8.8.8.8")] // Full-width digits. + public void TryParse_RejectsIPv4AddressesThatArentWrittenOutInFull(string text) + { + Assert.False(PingAddress.TryParse(text, out var address)); + Assert.Null(address); + } + + [Theory] + [InlineData("8.8.8.8:53")] + [InlineData("[2001:4860:4860::8888]")] + [InlineData("[2001:4860:4860::8888]:53")] + [InlineData("fe80::1%12")] // A zone, which picks an adapter. + [InlineData("fe80::1%eth0")] + [InlineData("fe80::1%")] + [InlineData(":")] + [InlineData(":::")] + [InlineData("1:::2")] + [InlineData("1::2::3")] + [InlineData("::1::")] + [InlineData(":1:2:3:4:5:6:7")] + [InlineData("1:2:3:4:5:6:7:")] + [InlineData(":1:2:3:4:5:6:7:8")] + [InlineData("1:2:3:4:5:6:7")] // Seven groups with nothing left out. + [InlineData("1:2:3:4:5:6:7:8:9")] + [InlineData("::1:2:3:4:5:6:7:8")] // "::" has to leave out at least one group. + [InlineData("1:2:3:4::5:6:7:8")] + [InlineData("1:2:3:4:5:6:7:8::")] + [InlineData("12345::1")] + [InlineData("2001:db8::g")] + [InlineData("2001:0db8:0000:0000:0000:0000:0000:00001")] + [InlineData("0x2001::1")] + [InlineData("2001: db8::1")] + [InlineData("2001:db8 ::1")] + [InlineData("1:2:3:4:5:6:7:8.8.8.8")] // Nine groups with the IPv4 part. + [InlineData("::8.8.8")] + [InlineData("::8.8.8.256")] + [InlineData("8.8.8.8::")] // An IPv4 part only goes at the end. + [InlineData("8.8.8.8::1")] + [InlineData("::8.8.8.8:1")] + [InlineData("::8.8.8.8.8")] + [InlineData("::١")] + [InlineData("::a")] // A full-width "a". + public void TryParse_RejectsWhatIsntAnIPv6Address(string text) + { + Assert.False(PingAddress.TryParse(text, out var address)); + Assert.Null(address); + } + + [Theory] + [InlineData("0.0.0.0")] // No address at all. + [InlineData("0.1.2.3")] // This network. + [InlineData("255.255.255.255")] // Every device on the network. + [InlineData("224.0.0.1")] // Multicast, from 224 to 239. + [InlineData("224.0.0.251")] + [InlineData("239.255.255.250")] + [InlineData("::")] + [InlineData("0:0:0:0:0:0:0:0")] + [InlineData("::0.0.0.0")] + [InlineData("ff02::1")] + [InlineData("FF05::1:3")] + [InlineData("ff0e::101")] + public void TryParse_RejectsAddressesThatArentOneDevice(string text) + { + // Written correctly, so IPAddress.TryParse takes them too. + Assert.True(IPAddress.TryParse(text, out _)); + + Assert.False(PingAddress.TryParse(text, out var address)); + Assert.Null(address); + } + + [Theory] + [InlineData("1")] + [InlineData("1.2.3")] + [InlineData("0x7f.1")] + [InlineData("010.1.1.1")] + [InlineData("fe80::1%12")] + public void TryParse_RejectsWhatIPAddressTryParseTakes(string text) + { + Assert.True(IPAddress.TryParse(text, out _)); + Assert.False(PingAddress.TryParse(text, out _)); + } +} diff --git a/Network Monitor.Tests/SettingsTests.cs b/Network Monitor.Tests/SettingsTests.cs index 376d74c..25ebb1e 100644 --- a/Network Monitor.Tests/SettingsTests.cs +++ b/Network Monitor.Tests/SettingsTests.cs @@ -45,6 +45,7 @@ public void Dispose() public void Save_ThenLoad_KeepsEverySetting() { var original = Load(); + original.PingHost = "2606:4700:4700::1111"; original.Bits = false; original.InterfaceId = "{4D36E972-E325-11CE-BFC1-08002BE10318}"; original.Topmost = false; @@ -57,6 +58,7 @@ public void Save_ThenLoad_KeepsEverySetting() Assert.True(original.Save()); var loaded = Load(); + Assert.Equal("2606:4700:4700::1111", loaded.PingHost); Assert.False(loaded.Bits); Assert.Equal("{4D36E972-E325-11CE-BFC1-08002BE10318}", loaded.InterfaceId); Assert.False(loaded.Topmost); @@ -147,6 +149,7 @@ public void Load_WithSomeBadValues_KeepsTheGoodOnes() { File.WriteAllText(FilePath, """ { + "PingHost": "google.com", "Bits": "maybe", "InterfaceId": 7, "Topmost": false, @@ -160,6 +163,7 @@ public void Load_WithSomeBadValues_KeepsTheGoodOnes() var settings = Load(); + Assert.Equal("8.8.8.8", settings.PingHost); Assert.True(settings.Bits); Assert.Equal(string.Empty, settings.InterfaceId); Assert.False(settings.Topmost); @@ -215,6 +219,41 @@ public void Load_WithASizeOutOfRange_KeepsTheWidgetOnScreen(int size, int expect Assert.Equal(expected, Load().Size); } + [Fact] + public void Load_ReadsAPingAddressEditedByHand() + { + File.WriteAllText(FilePath, """{ "PingHost": " 1.1.1.1 " }"""); + + Assert.Equal("1.1.1.1", Load().PingHost); + } + + [Theory] + [InlineData("\"one.one.one.one\"")] + [InlineData("\"1.1.1\"")] + [InlineData("\"255.255.255.255\"")] + [InlineData("\"\"")] + [InlineData("null")] + [InlineData("1")] + public void Load_WithAPingAddressThatCantBePinged_KeepsTheDefault(string pingHost) + { + File.WriteAllText(FilePath, $$"""{ "PingHost": {{pingHost}} }"""); + + Assert.Equal("8.8.8.8", Load().PingHost); + } + + [Fact] + public void PingHost_GivenOneThatCantBePinged_KeepsTheAddressBefore() + { + var settings = Load(); + settings.PingHost = "192.168.1.1"; + + settings.PingHost = "router.local"; + Assert.Equal("192.168.1.1", settings.PingHost); + + settings.PingHost = null; + Assert.Equal("192.168.1.1", settings.PingHost); + } + [Fact] public void Save_OverAnExistingFile_LeavesNoTemporaryFileBehind() { diff --git a/Network Monitor/MainViewModel.cs b/Network Monitor/MainViewModel.cs index 45d31e4..539629d 100644 --- a/Network Monitor/MainViewModel.cs +++ b/Network Monitor/MainViewModel.cs @@ -18,7 +18,7 @@ public MainViewModel() { Monitors = new List { - new LatencyMonitor(Settings.Default.PingHost, Settings.Default.Timeout), + new LatencyMonitor(Settings.Default.Timeout), new DownloadMonitor(), new UploadMonitor() }; diff --git a/Network Monitor/MainWindow.xaml b/Network Monitor/MainWindow.xaml index 1abb69e..3c3cbbf 100644 --- a/Network Monitor/MainWindow.xaml +++ b/Network Monitor/MainWindow.xaml @@ -72,6 +72,9 @@ + + + diff --git a/Network Monitor/MainWindow.xaml.cs b/Network Monitor/MainWindow.xaml.cs index ca94b63..d90f052 100644 --- a/Network Monitor/MainWindow.xaml.cs +++ b/Network Monitor/MainWindow.xaml.cs @@ -193,6 +193,16 @@ private static MenuItem CreateAdapterMenuItem(string header, string interfaceId) return item; } + private void MenuItemPingAddress_OnClick(object sender, RoutedEventArgs e) + { + // Owned by the widget, so it stays in front of it when the widget is always on top. + var dialog = new PingAddressDialog(Settings.Default.PingHost) { Owner = this }; + + // The latency reading moves to it on the next tick. + if (dialog.ShowDialog() == true) + Settings.Default.PingHost = dialog.Address; + } + private void MenuItemCopy_OnClick(object sender, RoutedEventArgs e) { CopyOverview(); diff --git a/Network Monitor/Monitors/LatencyMonitor.cs b/Network Monitor/Monitors/LatencyMonitor.cs index 70f5d8a..6e9979b 100644 --- a/Network Monitor/Monitors/LatencyMonitor.cs +++ b/Network Monitor/Monitors/LatencyMonitor.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; +using System.Net; using System.Net.NetworkInformation; using System.Threading; @@ -17,7 +18,6 @@ public class LatencyMonitor : Monitor /// private const int WindowSeconds = 60; - private readonly string _host; private readonly int _timeout; /// @@ -34,6 +34,17 @@ public class LatencyMonitor : Monitor private int _pingsOut; + /// + /// The address being pinged, as it was typed, which the tooltip shows. + /// + private string _host; + + /// + /// The address being pinged. + /// It and are only touched from the clock tick, which moves them to the one picked in the menu. + /// + private IPAddress _address; + /// /// What the reading showed on the latest tick, which the tooltip and screen readers describe. /// @@ -49,7 +60,7 @@ public class LatencyMonitor : Monitor /// private (DateTime Start, DateTime End)? _lastOutage; - public LatencyMonitor(string host, TimeSpan timeout) : base(true) + public LatencyMonitor(TimeSpan timeout) : base(true) { Name = "Latency"; Icon = '⟳'; @@ -58,13 +69,14 @@ public LatencyMonitor(string host, TimeSpan timeout) : base(true) // A healthy connection's few milliseconds of wobble should look like a wobble, not fill the graph's whole height like a real spike. HistoryMinimumTop = 50; - _host = host; _timeout = (int)timeout.TotalMilliseconds; _maxPingsOut = (int)Math.Ceiling(timeout.TotalSeconds) + 2; } protected override string GetDisplayValue() { + FollowPingHost(); + // Show the last second whose ping has finished, then send this second's. var snapshot = _history.GetSnapshot(); var finished = LatencyHistory.GetFinished(snapshot.Slots); @@ -80,7 +92,7 @@ protected override string GetDisplayValue() snapshot.LastReplyAt, now, NetworkStatus.IsReconnecting, - NetworkStatus.HasRepliedOnThisNetwork); + NetworkStatus.HasRepliedOnThisNetwork(_address)); StartPing(); RememberOutage(view, snapshot.LastReplyAt, now); @@ -133,6 +145,32 @@ protected override void ResetHistory() _outageStart = null; } + /// + /// Moves to the address picked in the menu, from this tick on. + /// The last minute's stats, graph, and outage were measured against the old address, so they start fresh rather than being shown under the new one, as they do when another adapter is picked. + /// So, as after the PC wakes, there's no outage clock until the new address has replied once, even if it's one that replied before. + /// This is checked here on the clock tick, which owns the history, rather than when the setting changes. + /// + private void FollowPingHost() + { + var host = Properties.Settings.Default.PingHost; + + // Most ticks it hasn't changed. The settings only keep an address that can be pinged, so it can always be read. + if (host == _host || !PingAddress.TryParse(host, out var address)) + return; + + // The first tick has nothing to start over from, and the same address written another way, like in capitals, only changes how it's shown. + if (_address != null && !address.Equals(_address)) + { + _history.Reset(); + _outageStart = null; + _lastOutage = null; + } + + _host = host; + _address = address; + } + /// /// Notes when an outage clock starts, and once replies are back, how long the outage lasted. /// @@ -190,21 +228,25 @@ private void StartPing() return; } - SendPing(ticket); + SendPing(ticket, _address); } - private async void SendPing(LatencyHistory.Ticket ticket) + /// + /// Sends one ping and files how it went. + /// The address is passed in rather than read when the reply comes back, so a reply that arrives after another address was picked counts for the one it came from. + /// + private async void SendPing(LatencyHistory.Ticket ticket, IPAddress address) { if (!_idlePings.TryTake(out var ping)) ping = new Ping(); try { - var reply = await ping.SendPingAsync(_host, _timeout).ConfigureAwait(false); + var reply = await ping.SendPingAsync(address, _timeout).ConfigureAwait(false); var success = reply.Status == IPStatus.Success; if (success) - NetworkStatus.ReportReply(); + NetworkStatus.ReportReply(address); _history.Complete(ticket, success ? reply.RoundtripTime : null); _idlePings.Add(ping); diff --git a/Network Monitor/Monitors/NetworkStatus.cs b/Network Monitor/Monitors/NetworkStatus.cs index 60c0e4b..e431857 100644 --- a/Network Monitor/Monitors/NetworkStatus.cs +++ b/Network Monitor/Monitors/NetworkStatus.cs @@ -36,10 +36,11 @@ public static class NetworkStatus private static readonly long ReconnectingTicks = 5 * Stopwatch.Frequency; /// - /// The networks a ping has come back through, which tells a network having an outage from one that blocks ping. + /// The networks a ping has come back through, for each address pinged, which tells a network having an outage from one that blocks ping. + /// Kept for each address, so after replies from the one pinged before, a new one that never answers, like a typo or a server that ignores ping, says it may block ping rather than waiting for a reply for good. /// Only kept while the app runs. /// - private static readonly List RepliedNetworks = new(); + private static readonly Dictionary> RepliedNetworks = new(); /// /// Keeps a network-change event, the recheck timer, and the clock tick from refreshing at the same time and leaving an older result behind. @@ -105,29 +106,26 @@ public static bool IsReconnecting } /// - /// Whether a ping has ever come back through the network internet traffic leaves through now. - /// If so, failing pings are an outage; if not, the network may just block ping, like many work VPNs and public Wi-Fi. - /// It's remembered per router, so a router that restarts still counts, and only a different network starts over. + /// Whether a ping to has ever come back through the network internet traffic leaves through now. + /// If so, failing pings are an outage; if not, the network may just block ping, like many work VPNs and public Wi-Fi, or the address may not answer. + /// It's remembered per router, so a router that restarts still counts, and only a different network or address starts over. /// - public static bool HasRepliedOnThisNetwork + public static bool HasRepliedOnThisNetwork(IPAddress address) { - get - { - var network = _currentNetwork; + var network = _currentNetwork; - // Without a route there's no network to tell apart. - if (network.Length == 0) - return true; + // Without a route there's no network to tell apart. + if (network.Length == 0) + return true; - lock (RepliedNetworks) - return GetComparable(network).Any(x => RepliedNetworks.Any(x.Matches)); - } + lock (RepliedNetworks) + return RepliedNetworks.TryGetValue(address, out var replied) && GetComparable(network).Any(x => replied.Any(x.Matches)); } /// - /// Records that a ping came back, and through which network. + /// Records that a ping to came back, and through which network. /// - public static void ReportReply() + public static void ReportReply(IPAddress address) { Interlocked.Exchange(ref _lastReplyTimestamp, Stopwatch.GetTimestamp()); @@ -135,14 +133,17 @@ public static void ReportReply() lock (RepliedNetworks) { + if (!RepliedNetworks.TryGetValue(address, out var replied)) + RepliedNetworks[address] = replied = new List(); + foreach (var id in network) { - var known = RepliedNetworks.FindIndex(x => x.Matches(id)); + var known = replied.FindIndex(x => x.Matches(id)); if (known < 0) - RepliedNetworks.Add(id); - else if (RepliedNetworks[known].GatewayHardwareAddress is null && id.GatewayHardwareAddress != null) - RepliedNetworks[known] = id; + replied.Add(id); + else if (replied[known].GatewayHardwareAddress is null && id.GatewayHardwareAddress != null) + replied[known] = id; } } } diff --git a/Network Monitor/Monitors/Outage.cs b/Network Monitor/Monitors/Outage.cs index 9587b4d..cf14f20 100644 --- a/Network Monitor/Monitors/Outage.cs +++ b/Network Monitor/Monitors/Outage.cs @@ -89,7 +89,7 @@ public static string DescribeRecovery(DateTime start, DateTime end, DateTime now /// When the last reply arrived, in UTC, or null if none has. /// The current time, in UTC. /// Whether the PC only just got its connection back, when pings often fail for a few seconds. - /// Whether a ping has ever come back through this network's router. + /// Whether a ping to this address has ever come back through this network's router. public static LatencyView Decide(long? newestFinished, bool isWaiting, long? lastRoundtrip, long? secondsSinceReply, DateTime? lastReplyAt, DateTime now, bool isReconnecting, bool hasRepliedOnThisNetwork) { if (newestFinished is long roundtrip && roundtrip >= 0 && !isWaiting) @@ -101,7 +101,7 @@ public static LatencyView Decide(long? newestFinished, bool isWaiting, long? las if (isReconnecting) return LatencyView.Note("Reconnecting…", "reconnecting"); - // Some networks, like many public Wi-Fi and work networks, block ping; a clock counting up there would only ever cry wolf. + // Some networks, like many public Wi-Fi and work networks, block ping, and so do some addresses; a clock counting up there would only ever cry wolf. if (!hasRepliedOnThisNetwork && (newestFinished == LatencyHistory.Lost || secondsSinceReply >= ClockAfterSeconds)) return LatencyView.BlockedNetwork(); @@ -156,7 +156,7 @@ private LatencyView(string value, bool isStale, string note, string spoken, bool public bool IsOutage { get; } /// - /// Whether the network seems to block ping, so time on it isn't an outage. + /// Whether the network or the address seems to block ping, so time without replies isn't an outage. /// public bool IsBlockedNetwork { get; } @@ -174,7 +174,7 @@ public static LatencyView Dimmed(long roundtrip) => public static LatencyView Note(string note, string spoken) => new("—", false, note, spoken, false); public static LatencyView BlockedNetwork() => - new("—", false, "No replies on this network yet. It may block ping.", "no replies on this network", false, true); + new("—", false, "No replies on this network yet. It or the address may block ping.", "no replies on this network", false, true); /// How long since the last reply. /// When the last reply arrived, in UTC. diff --git a/Network Monitor/Monitors/PingAddress.cs b/Network Monitor/Monitors/PingAddress.cs new file mode 100644 index 0000000..925af6f --- /dev/null +++ b/Network Monitor/Monitors/PingAddress.cs @@ -0,0 +1,47 @@ +using System.Linq; +using System.Net; +using System.Net.Sockets; + +namespace Network_Monitor.Monitors; + +/// +/// Reads an address typed in to be pinged, which has to be a plain IPv4 address like 8.8.8.8 or IPv6 address like 2001:4860:4860::8888. +/// +/// +/// takes far more than that, so a typo could quietly ping somewhere else: +/// "1.2.3" is 1.2.0.3, "010.1.1.1" is 8.1.1.1 because a leading zero makes it octal, and "fe80::1%12" picks an adapter. +/// Names like google.com aren't taken either, so latency never includes looking one up. +/// +public static class PingAddress +{ + /// + /// Reads as an address to ping, ignoring spaces around it. + /// + /// What was typed. + /// The address, or null if it can't be pinged. + /// Whether it's a plain IP address of one device, which a ping can be sent to. + public static bool TryParse(string text, out IPAddress address) + { + address = null; + text = text?.Trim(); + + if (string.IsNullOrEmpty(text) || !IPAddress.TryParse(text, out var parsed)) + return false; + + // IPv4 has to be four decimal numbers with no leading zeros, and IPv6 can't have a zone, brackets, or a port. + var isPlain = parsed.AddressFamily == AddressFamily.InterNetwork + ? text.Split('.') is { Length: 4 } parts && parts.All(x => x.Length is >= 1 and <= 3 && x.All(c => c is >= '0' and <= '9') && (x.Length == 1 || x[0] != '0')) + : text.IndexOfAny(new[] { '%', '[', ']' }) < 0; + + // A ping goes to one device, so not to this network itself (0.x.x.x or ::), a group of devices (multicast), or every device on the network. + var isOneDevice = parsed.AddressFamily == AddressFamily.InterNetwork + ? parsed.GetAddressBytes()[0] is not (0 or (>= 224 and <= 239)) && !parsed.Equals(IPAddress.Broadcast) + : !parsed.Equals(IPAddress.IPv6Any) && !parsed.IsIPv6Multicast; + + if (!isPlain || !isOneDevice) + return false; + + address = parsed; + return true; + } +} diff --git a/Network Monitor/PingAddressDialog.xaml b/Network Monitor/PingAddressDialog.xaml new file mode 100644 index 0000000..b045f21 --- /dev/null +++ b/Network Monitor/PingAddressDialog.xaml @@ -0,0 +1,42 @@ + + + private Dictionary ToJson() => new() { + [nameof(PingHost)] = PingHost, [nameof(Bits)] = Bits, [nameof(InterfaceId)] = InterfaceId, [nameof(Topmost)] = Topmost, diff --git a/README.md b/README.md index 44ff852..c42a87a 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ Hover for a 60-second sparkline and the stats behind it: min/avg/max, jitter, pa - **Three live readings:** round-trip latency (ping), download speed, and upload speed, updated every second. - **Hover for history:** a 60-second sparkline with min/avg/max, jitter, packet loss, and session totals. - **Pick your adapter:** Automatic follows whichever adapter reaches the internet, or pick one, or all of them. +- **Choose what to ping:** `8.8.8.8` by default, or any IPv4 or IPv6 address, like `1.1.1.1` or your router's. - **Bits or bytes:** switch between Mbps and MB/s; units auto-scale from K to T as traffic changes. - **Vertical or horizontal:** a slim column or a wide strip, so it fits any edge of your screen. - **Light, dark, or auto:** pick a theme, or let Auto follow the Windows light/dark mode and accent color. @@ -53,5 +54,6 @@ Hover for a 60-second sparkline and the stats behind it: min/avg/max, jitter, pa - **Resize it:** hold **Ctrl** and scroll over it, or use the **Size** slider in the menu. - **Hover it:** hold the cursor over any reading for a sparkline and detailed stats from the last minute. - **Lost it?** Start Network Monitor again and the running widget comes back into view. -- **Options:** right-click for network adapter, bits/bytes, orientation, theme, always on top, etc. -- Latency is measured by pinging `8.8.8.8` (Google DNS); download and upload follow your internet adapter. +- **Options:** right-click for network adapter, ping address, bits/bytes, orientation, theme, always on top, etc. +- Latency pings `8.8.8.8` (Google DNS) or your **Ping address**; download and upload follow your internet adapter. +- Lowercase means bits and uppercase means bytes: `45m` is 45 Mbps, and `45M` is 45 MB/s.