Skip to content

Commit 6d7ac55

Browse files
feat: Use IPNetwork.TryParse() for CIDR parsing (#1122)
## Motivation The CIDR parsing logic was implemented with a custom helper that manually split strings, parsed integers, and validated prefix lengths. The .NET framework provides a built-in and thoroughly validated `IPNetwork.TryParse()` API that handles all of this, eliminating the need for custom parsing code. ## Changes - Removed the `TryParseCidr()` wrapper method entirely - Inlined CIDR validation directly in the loop using `IPNetwork.TryParse()` - Removed unused `System.Net.Sockets` import This eliminates unnecessary indirection while maintaining identical behavior and improving maintainability by relying on framework-tested APIs.
1 parent 80585d8 commit 6d7ac55

1 file changed

Lines changed: 1 addition & 28 deletions

File tree

EssentialCSharp.Web/Extensions/IServiceCollectionExtensions.cs

Lines changed: 1 addition & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System.Net;
2-
using System.Net.Sockets;
32
using EssentialCSharp.Web.Services;
43
using Microsoft.AspNetCore.HttpOverrides;
54

@@ -48,7 +47,7 @@ public static void AddTrustedForwardedHeaders(this IServiceCollection services,
4847

4948
foreach (var cidr in trustedProxyCidrs)
5049
{
51-
if (!TryParseCidr(cidr, out var network))
50+
if (string.IsNullOrWhiteSpace(cidr) || !System.Net.IPNetwork.TryParse(cidr.Trim(), out var network))
5251
throw new InvalidOperationException($"Invalid ForwardedHeaders:TrustedProxyCidrs entry '{cidr}'. Use CIDR notation, e.g. '10.0.0.0/8'.");
5352

5453
options.KnownIPNetworks.Add(network);
@@ -63,30 +62,4 @@ public static void AddTrustedForwardedHeaders(this IServiceCollection services,
6362
}
6463
});
6564
}
66-
67-
private static bool TryParseCidr(string cidr, out System.Net.IPNetwork network)
68-
{
69-
network = default!;
70-
if (string.IsNullOrWhiteSpace(cidr))
71-
return false;
72-
73-
string[] parts = cidr.Split('/', 2, StringSplitOptions.TrimEntries);
74-
if (parts.Length != 2
75-
|| !IPAddress.TryParse(parts[0], out var networkAddress)
76-
|| !int.TryParse(parts[1], out var prefixLength))
77-
return false;
78-
79-
int maxPrefixLength = networkAddress.AddressFamily switch
80-
{
81-
AddressFamily.InterNetwork => 32,
82-
AddressFamily.InterNetworkV6 => 128,
83-
_ => -1
84-
};
85-
86-
if (maxPrefixLength < 0 || prefixLength < 0 || prefixLength > maxPrefixLength)
87-
return false;
88-
89-
network = new System.Net.IPNetwork(networkAddress, prefixLength);
90-
return true;
91-
}
9265
}

0 commit comments

Comments
 (0)