Search code examples
c#.net.net-4.5ip-addressipv6

Why .NET does not parse certain IPv6 with embedded IPv4 values?


In my computer, this code:

        var someIps = new[]
        {
            "::1.2.3.4",
            "::0000:1.2.3.4",
            "0:0:0:0:0:0:0000:1.2.3.4",
            "1::0000:1.2.3.4",
            "0000:0000:0000:0000:0000:0000:0000:1.2.3.4",
            "::abcd:1.2.3.4",
            "0:0:0:0:0:0:abcd:1.2.3.4",
            "1::abcd:1.2.3.4",
            "0000:0000:0000:0000:0000:0000:abcd:1.2.3.4",
            "::ffff:1.2.3.4",
            "0:0:0:0:0:0:ffff:1.2.3.4",
            "1::ffff:1.2.3.4",
            "0001:0000:0000:0000:0000:0000:ffff:1.2.3.4",
        };

        foreach ( var ip in someIps )
        {
            if (IPAddress.TryParse( ip, out var parsed ))
                Console.WriteLine( "{0} parses to {1}", ip, parsed );
            else
                Console.WriteLine( "{0} does not parse.", ip, parsed );
        }

Generates this output:

::1.2.3.4 parses to ::1.2.3.4
::0000:1.2.3.4 parses to ::1.2.3.4
0:0:0:0:0:0:0000:1.2.3.4 does not parse.
1::0000:1.2.3.4 parses to 1::102:304
0000:0000:0000:0000:0000:0000:0000:1.2.3.4 does not parse.
::abcd:1.2.3.4 parses to ::abcd:102:304
0:0:0:0:0:0:abcd:1.2.3.4 does not parse.
1::abcd:1.2.3.4 parses to 1::abcd:102:304
0000:0000:0000:0000:0000:0000:abcd:1.2.3.4 does not parse.
::ffff:1.2.3.4 parses to ::ffff:1.2.3.4
0:0:0:0:0:0:ffff:1.2.3.4 does not parse.
1::ffff:1.2.3.4 parses to 1::ffff:102:304
0001:0000:0000:0000:0000:0000:ffff:1.2.3.4 does not parse.

Why does it parse ::ffff:1.2.3.4, but can't parse 0:0:0:0:0:0:ffff:1.2.3.4? Aren't they supposed to be the same address?

Am I missing something in the IPv6 representation that make those strings invalid? Or did I just find a bug in [IPAddress.TryParse][1] ?


Solution

  • You have a mistake in the full written line. It is supposed to be 8 groups of Hex Numbers. 0:0:0:0:0:0:ffff however is only 7 groups - 6 0-groups, 1 f-group

    Indeed numbers like these only have 6 groups: 0001:0000:0000:0000:0000:ffff - 1 01-group, 4 0-groups, 1 f-group.

    Just a classical mistake were repetition seems to have caused you overlooking something.