ipnetwork icon indicating copy to clipboard operation
ipnetwork copied to clipboard

TryParse does not return `false` on all invalid IPv6 addresses

Open stujfiter opened this issue 4 years ago • 6 comments

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

stujfiter avatar Feb 12 '21 15:02 stujfiter

Do you know the convention of Parse and TryParse in C#?

GF-Huang avatar May 31 '21 11:05 GF-Huang

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

stujfiter avatar Jun 01 '21 12:06 stujfiter

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 avatar Aug 16 '21 14:08 lduchosal

@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.

stujfiter avatar Aug 16 '21 15:08 stujfiter

"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 avatar Sep 13 '21 11:09 RobThree

@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.

lduchosal avatar Sep 14 '21 06:09 lduchosal