ipnetwork
ipnetwork copied to clipboard
TryParse does not return `false` on all invalid IPv6 addresses
I have run into an issue where TryParse() does not throw an exception when given an invalid IPv6 address.
Sample Code:
IPNetwork network; IPNetwork.TryParse("g001:02b8::/64", out network)
I have validated this bug against version 2.5.247
Do you know the convention of Parse and TryParse in C#?
Poor name for the bug. I will attempt to rename.
Consider this:
[Fact]
public void IpNetworkTest()
{
Assert.False(IPNetwork.TryParse("g001:02b8::/64", out _));
}
This test fails as TryParse fails to detect the invalid 'g' character
IPNetwork library sanitanize its input before trying to parse it as an IPNetwork. It removes invalid chars beforehand and returns the parsed IPNetwork.
I would say, this is intended behaviour. We could add behaviour with additional method TryExactParse... or something. PR Welcome.
@lduchosal, can this be documented as the intended behavior so others know that they will need to check for invalid characters before sending to TryParse? I'm happy to make a PR to document it, but I did not see any documentation on TryParse so do not know where to put such documentation other than as comments in the code.
"IPNetwork library sanitanize its input before trying to parse it as an IPNetwork."
Which is a design decision that you made (not arguing good or bad) and in the end it's all up to you ofcourse. However:
var result = IPAddress.TryParse("g001:02b8::", out var ip);
This will return false
; I would argue that for the least surprise the 'sanitization' shouldn't be done and false
should simply be returned.
@RobThree thanks for your insight. I do agree with the least surprise principle. I will increment version number and add a note about this change of behaviour into the release note.