Skip to content

Commit 1ac7dfd

Browse files
authored
Add support for IPAddress and IPEndpoint arguments (#1735)
* Add support of IPAddress and IPEndpoint arguments * IPEndPoint.TryParse isn't supported until .Net 7 * TryParse should work from .Net Core >= 3.1 * Add missing [Fact] attributes * Remove nullable IPAddress/IPEndPoint tests
1 parent 55dbf39 commit 1ac7dfd

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

src/System.CommandLine.Tests/Binding/TypeConversionTests.cs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using FluentAssertions;
99
using System.Linq;
1010
using Xunit;
11+
using System.Net;
1112

1213
namespace System.CommandLine.Tests.Binding
1314
{
@@ -708,7 +709,29 @@ public void Values_can_be_correctly_converted_to_nullable_sbyte_without_the_pars
708709

709710
value.Should().Be(123);
710711
}
711-
712+
713+
[Fact]
714+
public void Values_can_be_correctly_converted_to_ipaddress_without_the_parser_specifying_a_custom_converter()
715+
{
716+
var option = new Option<IPAddress>("-us");
717+
718+
var value = option.Parse("-us 1.2.3.4").GetValueForOption(option);
719+
720+
value.Should().Be(IPAddress.Parse("1.2.3.4"));
721+
}
722+
723+
#if NETCOREAPP3_0_OR_GREATER
724+
[Fact]
725+
public void Values_can_be_correctly_converted_to_ipendpoint_without_the_parser_specifying_a_custom_converter()
726+
{
727+
var option = new Option<IPEndPoint>("-us");
728+
729+
var value = option.Parse("-us 1.2.3.4:56").GetValueForOption(option);
730+
731+
value.Should().Be(IPEndPoint.Parse("1.2.3.4:56"));
732+
}
733+
#endif
734+
712735
[Fact]
713736
public void Values_can_be_correctly_converted_to_byte_without_the_parser_specifying_a_custom_converter()
714737
{

src/System.CommandLine/Binding/ArgumentConverter.StringConverters.cs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System.Collections.Generic;
55
using System.IO;
6+
using System.Net;
67

78
namespace System.CommandLine.Binding;
89

@@ -154,6 +155,32 @@ internal static partial class ArgumentConverter
154155
return false;
155156
},
156157

158+
[typeof(IPAddress)] = (string token, out object? value) =>
159+
{
160+
if (IPAddress.TryParse(token, out var ip))
161+
{
162+
value = ip;
163+
return true;
164+
}
165+
166+
value = default;
167+
return false;
168+
},
169+
170+
#if NETCOREAPP3_0_OR_GREATER
171+
[typeof(IPEndPoint)] = (string token, out object? value) =>
172+
{
173+
if (IPEndPoint.TryParse(token, out var ipendpoint))
174+
{
175+
value = ipendpoint;
176+
return true;
177+
}
178+
179+
value = default;
180+
return false;
181+
},
182+
#endif
183+
157184
[typeof(long)] = (string token, out object? value) =>
158185
{
159186
if (long.TryParse(token, out var longValue))

0 commit comments

Comments
 (0)