Skip to content

Commit ea150ad

Browse files
dearmbclaudeBornToBeRoot
authored
feat: support newline-separated hosts and shorthand ranges (#3568)
* feat: support newline-separated hosts and shorthand ranges Host input (IP Scanner, Port Scanner, Ping Monitor) now accepts newline-separated entries, so a column pasted from Excel works directly (one IP/range per line). The existing semicolon-separated format keeps working. Shorthand IPv4 ranges like 192.168.0.1-100 (192.168.0.1 to 192.168.0.100) are now supported too, alongside the existing full-range format 192.168.0.1-192.168.0.100. - HostRangeHelper.CreateListFromInput: split on ';', CR, LF - HostRangeHelper.ResolveAsync: expand shorthand ranges - RegexHelper: add IPv4AddressShortRangeRegex - MultipleHostsRangeValidator: accept newlines + shorthand ranges - Docs: document both features * docs: add changelog entry for newline-separated hosts and shorthand ranges Co-Authored-By: Claude <noreply@anthropic.com> * feat: convert multiline clipboard content to semicolon-separated on paste The WPF TextBox inside an editable ComboBox has AcceptsReturn=false, so pasting multiline text (e.g. a column from Excel) silently drops everything after the first line. Add a ComboBoxPasteBehavior attached property that rewrites the clipboard content to the semicolon-separated form in CommandManager.PreviewExecuted, before the paste command runs. Applied to the host input of IP Scanner, Port Scanner and Ping Monitor. Co-Authored-By: Claude <noreply@anthropic.com> * feat: convert multiline clipboard content to semicolon-separated on paste in port input Apply the same paste conversion to the Ports field of the Port Scanner, so a column of ports pasted from Excel works as well. Co-Authored-By: Claude <noreply@anthropic.com> * Fix: guard ComboBoxPasteBehavior clipboard access, document shorthand IPv4 ranges as example input * Chore: Copilot feedback --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com>
1 parent ee3ca24 commit ea150ad

13 files changed

Lines changed: 197 additions & 38 deletions

File tree

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
using System;
2+
using System.Linq;
3+
using System.Runtime.InteropServices;
4+
using System.Windows;
5+
using System.Windows.Controls;
6+
using System.Windows.Input;
7+
8+
namespace NETworkManager.Controls;
9+
10+
/// <summary>
11+
/// Attached property that converts multiline text (e.g. a column pasted from Excel) into a
12+
/// semicolon-separated single line when pasted into an editable <see cref="ComboBox"/>.
13+
///
14+
/// Without this the WPF TextBox inside the ComboBox (<see cref="TextBox.AcceptsReturn"/> is
15+
/// <c>false</c>) silently drops everything after the first line when multiline text is pasted.
16+
/// The conversion is applied by reading the clipboard, replacing the editable text box's
17+
/// selection with the converted text, and marking <see cref="ApplicationCommands.Paste"/> as
18+
/// handled - the system clipboard itself is never modified, so other applications (or a
19+
/// subsequent paste elsewhere) are unaffected.
20+
/// </summary>
21+
public static class ComboBoxPasteBehavior
22+
{
23+
public static readonly DependencyProperty ConvertMultilineToSemicolonProperty =
24+
DependencyProperty.RegisterAttached(
25+
"ConvertMultilineToSemicolon",
26+
typeof(bool),
27+
typeof(ComboBoxPasteBehavior),
28+
new PropertyMetadata(false, OnConvertMultilineToSemicolonChanged));
29+
30+
public static void SetConvertMultilineToSemicolon(UIElement element, bool value) =>
31+
element.SetValue(ConvertMultilineToSemicolonProperty, value);
32+
33+
public static bool GetConvertMultilineToSemicolon(UIElement element) =>
34+
(bool)element.GetValue(ConvertMultilineToSemicolonProperty);
35+
36+
private static void OnConvertMultilineToSemicolonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
37+
{
38+
if (d is not ComboBox comboBox)
39+
return;
40+
41+
if ((bool)e.NewValue)
42+
CommandManager.AddPreviewExecutedHandler(comboBox, OnPreviewExecuted);
43+
else
44+
CommandManager.RemovePreviewExecutedHandler(comboBox, OnPreviewExecuted);
45+
}
46+
47+
private static void OnPreviewExecuted(object sender, ExecutedRoutedEventArgs e)
48+
{
49+
// Keyboard shortcut (Ctrl+V) and the paste context menu item both route through
50+
// ApplicationCommands.Paste. Editing commands don't need to be handled here.
51+
if (e.Command != ApplicationCommands.Paste)
52+
return;
53+
54+
// The command originates from the focused editable text box inside the ComboBox
55+
// template, which is where the pasted text actually needs to be inserted.
56+
if (e.OriginalSource is not TextBox textBox)
57+
return;
58+
59+
string text;
60+
61+
try
62+
{
63+
if (!Clipboard.ContainsText())
64+
return;
65+
66+
text = Clipboard.GetText();
67+
}
68+
catch (ExternalException)
69+
{
70+
// Clipboard is temporarily locked by another process - fall back to the default paste.
71+
return;
72+
}
73+
74+
// Only intervene when there is actual multiline content (e.g. a column pasted from
75+
// Excel). Otherwise let the default paste command handle it as usual.
76+
if (!text.Contains('\n') && !text.Contains('\r'))
77+
return;
78+
79+
var converted = string.Join(";", text
80+
.Replace("\r\n", "\n")
81+
.Replace('\r', '\n')
82+
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
83+
.Select(x => x.Trim()));
84+
85+
// Replace the current selection with the converted text ourselves and mark the command
86+
// handled, instead of letting the default paste run - this avoids touching the system
87+
// clipboard entirely (no risk of losing other clipboard formats or racing a paste
88+
// elsewhere).
89+
var selectionStart = textBox.SelectionStart;
90+
var textBefore = textBox.Text[..selectionStart];
91+
var textAfter = textBox.Text[(selectionStart + textBox.SelectionLength)..];
92+
93+
textBox.Text = textBefore + converted + textAfter;
94+
textBox.SelectionStart = selectionStart + converted.Length;
95+
textBox.SelectionLength = 0;
96+
97+
e.Handled = true;
98+
}
99+
}

‎Source/NETworkManager.Localization/Resources/StaticStrings.Designer.cs‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Source/NETworkManager.Localization/Resources/StaticStrings.resx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@
145145
<value>SERVER-01 or 10.0.0.10</value>
146146
</data>
147147
<data name="ExampleHostRange" xml:space="preserve">
148-
<value>192.168.178.0/24; 10.0.0.0 - 10.0.0.9; 10.0.[0-9,20].[1-2]; server-01.borntoberoot.net/24</value>
148+
<value>192.168.178.0/24; 10.8.0.0-100; 10.8.[0-9,254].1; server-01.borntoberoot.net/28</value>
149149
</data>
150150
<data name="ExampleIPv4Address" xml:space="preserve">
151151
<value>10.0.0.10</value>

‎Source/NETworkManager.Models/Network/HostRangeHelper.cs‎

Lines changed: 39 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using NETworkManager.Utilities;
2+
using System;
23
using System.Collections.Concurrent;
34
using System.Collections.Generic;
45
using System.Linq;
@@ -17,18 +18,40 @@ namespace NETworkManager.Models.Network;
1718
public static class HostRangeHelper
1819
{
1920
/// <summary>
20-
/// Create a list of hosts from a string input like "10.0.0.1; example.com; 10.0.0.0/24"
21+
/// Create a list of hosts from a string input like "10.0.0.1; example.com; 10.0.0.0/24".
22+
/// Inputs can also be separated by newlines (e.g. pasted from Excel, one host/range per line).
2123
/// </summary>
22-
/// <param name="hosts">Hosts like "10.0.0.1; example.com; 10.0.0.0/24"</param>
24+
/// <param name="hosts">Hosts like "10.0.0.1; example.com; 10.0.0.0/24" or newline-separated lines</param>
2325
/// <returns>List of hosts.</returns>
2426
public static IEnumerable<string> CreateListFromInput(string hosts)
2527
{
26-
return hosts.Replace(" ", "").Split(';')
27-
.Where(x => !string.IsNullOrEmpty(x))
28+
return hosts.Replace(" ", "")
29+
.Split([';', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries)
2830
.Select(x => x.Trim())
2931
.ToArray();
3032
}
3133

34+
/// <summary>
35+
/// Adds every IPv4 address in the inclusive range [<paramref name="start" />, <paramref name="end" />] to
36+
/// <paramref name="hostsBag" />. Iterates using the unsigned IPv4 value widened to <see cref="long" /> so the
37+
/// inclusive upper bound stays representable even for the last address in the 32-bit space
38+
/// (255.255.255.255), which would otherwise overflow <see cref="int" /> arithmetic.
39+
/// </summary>
40+
private static void AddIPv4RangeToBag(IPAddress start, IPAddress end,
41+
ConcurrentBag<(IPAddress ipAddress, string hostname)> hostsBag, CancellationToken ct)
42+
{
43+
var from = (long)unchecked((uint)IPv4Address.ToInt32(start));
44+
var to = (long)unchecked((uint)IPv4Address.ToInt32(end));
45+
46+
Parallel.For(from, to + 1, (i, state) =>
47+
{
48+
if (ct.IsCancellationRequested)
49+
state.Break();
50+
51+
hostsBag.Add((IPv4Address.FromInt32(unchecked((int)i)), string.Empty));
52+
});
53+
}
54+
3255
public static async Task<(List<(IPAddress ipAddress, string hostname)> hosts, List<string> hostnamesNotResolved)>
3356
ResolveAsync(IEnumerable<string> hosts, bool dnsResolveHostnamePreferIPv4, CancellationToken cancellationToken)
3457
{
@@ -54,29 +77,25 @@ public static IEnumerable<string> CreateListFromInput(string hosts)
5477
case var _ when RegexHelper.IPv4AddressSubnetmaskRegex().IsMatch(host):
5578
var network = IPNetwork2.Parse(host);
5679

57-
Parallel.For(IPv4Address.ToInt32(network.Network), IPv4Address.ToInt32(network.Broadcast) + 1,
58-
(i, state) =>
59-
{
60-
if (ct.IsCancellationRequested)
61-
state.Break();
80+
AddIPv4RangeToBag(network.Network, network.Broadcast, hostsBag, ct);
6281

63-
hostsBag.Add((IPv4Address.FromInt32(i), string.Empty));
64-
});
82+
break;
83+
84+
// 192.168.0.1-100
85+
case var _ when RegexHelper.IPv4AddressShortRangeRegex().IsMatch(host):
86+
var shortRange = host.Split('-');
87+
var shortBase = shortRange[0][..shortRange[0].LastIndexOf('.')];
88+
89+
AddIPv4RangeToBag(IPAddress.Parse(shortRange[0]),
90+
IPAddress.Parse($"{shortBase}.{shortRange[1]}"), hostsBag, ct);
6591

6692
break;
6793

6894
// 192.168.0.0 - 192.168.0.100
6995
case var _ when RegexHelper.IPv4AddressRangeRegex().IsMatch(host):
7096
var range = host.Split('-');
7197

72-
Parallel.For(IPv4Address.ToInt32(IPAddress.Parse(range[0])),
73-
IPv4Address.ToInt32(IPAddress.Parse(range[1])) + 1, (i, state) =>
74-
{
75-
if (ct.IsCancellationRequested)
76-
state.Break();
77-
78-
hostsBag.Add((IPv4Address.FromInt32(i), string.Empty));
79-
});
98+
AddIPv4RangeToBag(IPAddress.Parse(range[0]), IPAddress.Parse(range[1]), hostsBag, ct);
8099

81100
break;
82101

@@ -170,14 +189,7 @@ public static IEnumerable<string> CreateListFromInput(string hosts)
170189
network = IPNetwork2.Parse(
171190
$"{dnsResultWithSubnet.Value}/{hostAndSubnet[1]}");
172191

173-
Parallel.For(IPv4Address.ToInt32(network.Network),
174-
IPv4Address.ToInt32(network.Broadcast) + 1, (i, state) =>
175-
{
176-
if (ct.IsCancellationRequested)
177-
state.Break();
178-
179-
hostsBag.Add((IPv4Address.FromInt32(i), string.Empty));
180-
});
192+
AddIPv4RangeToBag(network.Network, network.Broadcast, hostsBag, ct);
181193
}
182194
else
183195
{

‎Source/NETworkManager.Utilities/RegexHelper.cs‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,30 @@ public static partial class RegexHelper
4343
public static partial Regex IPv4AddressExtractRegex();
4444

4545
/// <summary>
46-
/// Provides a compiles regular expression that matches IPv4 address ranges in the format "start-end" like
46+
/// Represents a regular expression pattern that matches valid shorthand IPv4 address ranges like
47+
/// "192.168.178.1-100" (base IP + last octet range).
48+
/// </summary>
49+
private const string IPv4AddressShortRangeValues =
50+
@"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\-(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
51+
52+
/// <summary>
53+
/// Provides a compiled regular expression that matches IPv4 address ranges in the format "start-end" like
4754
/// "192.168.178.0-192.168.178.255".
48-
/// </summary>
55+
/// </summary>
4956
/// <returns>A <see cref="Regex"/> instance that matches strings representing IPv4 address ranges, such as
5057
/// "192.168.1.1-192.168.1.100".</returns>
5158
[GeneratedRegex($"^{IPv4AddressValues}-{IPv4AddressValues}$")]
5259
public static partial Regex IPv4AddressRangeRegex();
5360

61+
/// <summary>
62+
/// Provides a compiled regular expression that matches shorthand IPv4 address ranges like
63+
/// "192.168.178.1-100" (base IP followed by a last-octet range).
64+
/// </summary>
65+
/// <returns>A <see cref="Regex"/> instance that matches strings representing shorthand IPv4 address ranges,
66+
/// such as "192.168.1.1-100" (192.168.1.1 to 192.168.1.100).</returns>
67+
[GeneratedRegex($"^{IPv4AddressShortRangeValues}$")]
68+
public static partial Regex IPv4AddressShortRangeRegex();
69+
5470
/// <summary>
5571
/// Provides a compiled regular expression that matches valid IPv4 subnet mask like "255.255.0.0".
5672
/// </summary>

‎Source/NETworkManager.Validators/MultipleHostsRangeValidator.cs‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using NETworkManager.Localization.Resources;
22
using NETworkManager.Models.Network;
33
using NETworkManager.Utilities;
4+
using System;
45
using System.DirectoryServices.ActiveDirectory;
56
using System.Globalization;
67
using System.Net;
@@ -18,7 +19,9 @@ public override ValidationResult Validate(object value, CultureInfo cultureInfo)
1819
if (value == null)
1920
return new ValidationResult(false, Strings.EnterValidIPScanRange);
2021

21-
foreach (var ipHostOrRange in ((string)value).Replace(" ", "").Split(';'))
22+
foreach (var ipHostOrRange in ((string)value)
23+
.Replace(" ", "")
24+
.Split([';', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries))
2225
{
2326
// 192.168.0.1
2427
if (RegexHelper.IPv4AddressRegex().IsMatch(ipHostOrRange))
@@ -32,6 +35,19 @@ public override ValidationResult Validate(object value, CultureInfo cultureInfo)
3235
if (RegexHelper.IPv4AddressSubnetmaskRegex().IsMatch(ipHostOrRange))
3336
continue;
3437

38+
// 192.168.0.1-100
39+
if (RegexHelper.IPv4AddressShortRangeRegex().IsMatch(ipHostOrRange))
40+
{
41+
var shortRange = ipHostOrRange.Split('-');
42+
var shortBase = shortRange[0][..shortRange[0].LastIndexOf('.')];
43+
44+
if (IPv4Address.ToInt32(IPAddress.Parse(shortRange[0])) >
45+
IPv4Address.ToInt32(IPAddress.Parse($"{shortBase}.{shortRange[1]}")))
46+
isValid = false;
47+
48+
continue;
49+
}
50+
3551
// 192.168.0.0 - 192.168.0.100
3652
if (RegexHelper.IPv4AddressRangeRegex().IsMatch(ipHostOrRange))
3753
{

‎Source/NETworkManager/Views/IPScannerView.xaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
ItemsSource="{Binding Path=HostHistoryView}"
6969
mah:TextBoxHelper.Watermark="{x:Static Member=localization:StaticStrings.ExampleHostRange}"
7070
IsReadOnly="{Binding Path=IsRunning}"
71+
controls:ComboBoxPasteBehavior.ConvertMultilineToSemicolon="True"
7172
Style="{StaticResource ResourceKey=HistoryComboBox}">
7273
<ComboBox.Text>
7374
<Binding Path="Host" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">

‎Source/NETworkManager/Views/PingMonitorHostView.xaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@
9797
ItemsSource="{Binding Path=HostHistoryView}"
9898
mah:TextBoxHelper.Watermark="{x:Static Member=localization:StaticStrings.ExampleHostRange}"
9999
IsReadOnly="{Binding Path=IsRunning}"
100+
controls:ComboBoxPasteBehavior.ConvertMultilineToSemicolon="True"
100101
Style="{StaticResource ResourceKey=HistoryComboBox}">
101102
<ComboBox.Text>
102103
<Binding Path="Host" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">

‎Source/NETworkManager/Views/PortScannerView.xaml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
ItemsSource="{Binding HostHistoryView}"
6161
mah:TextBoxHelper.Watermark="{x:Static localization:StaticStrings.ExampleHostRange}"
6262
IsReadOnly="{Binding Path=IsRunning}"
63+
controls:ComboBoxPasteBehavior.ConvertMultilineToSemicolon="True"
6364
Style="{StaticResource HistoryComboBox}">
6465
<ComboBox.Text>
6566
<Binding Path="Host" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
@@ -79,6 +80,7 @@
7980
ItemsSource="{Binding PortsHistoryView}"
8081
mah:TextBoxHelper.Watermark="{x:Static localization:StaticStrings.ExamplePortScanRange}"
8182
IsReadOnly="{Binding Path=IsRunning}"
83+
controls:ComboBoxPasteBehavior.ConvertMultilineToSemicolon="True"
8284
Style="{StaticResource HistoryComboBox}">
8385
<ComboBox.Text>
8486
<Binding Path="Ports" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">

‎Website/docs/application/ip-scanner.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ With the **IP Scanner** you can scan for active devices based on the hostname or
2525
| -------------------------------- | -------------------------------------------------------------------------------------------- |
2626
| `10.0.0.1` | Single IP address (`10.0.0.1`) |
2727
| `10.0.0.100 - 10.0.0.199` | All IP addresses in a given range (`10.0.0.100`, `10.0.0.101`, ..., `10.0.0.199`) |
28+
| `10.0.0.100-199` | All IP addresses in a given range, shorthand for the last octet (`10.0.0.100`, ..., `10.0.0.199`) |
2829
| `10.0.0.0/23` | All IP addresses in a subnet (`10.0.0.0`, ..., `10.0.1.255`) |
2930
| `10.0.0.0/255.255.254.0` | All IP addresses in a subnet (`10.0.0.0`, ..., `10.0.1.255`) |
3031
| `10.0.[0-9,20].[1-2]` | Multiple IP addresses like (`10.0.0.1`, `10.0.0.2`, `10.0.1.1`, ...,`10.0.9.2`, `10.0.20.1`) |
@@ -34,9 +35,9 @@ With the **IP Scanner** you can scan for active devices based on the hostname or
3435

3536
:::note
3637

37-
Multiple inputs can be combined with a semicolon (`;`).
38+
Multiple inputs can be combined with a semicolon (`;`). A column pasted from Excel (one entry per line) is converted to the semicolon-separated form automatically.
3839

39-
Example: `10.0.0.0/24; 10.0.[10-20]1`
40+
Example: `10.0.0.0/24; 10.0.[10-20].1; 10.0.0.100-199`
4041

4142
:::
4243

0 commit comments

Comments
 (0)