fernacolo
fernacolo

Reputation: 7439

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] ?

Upvotes: 4

Views: 156

Answers (2)

Christopher
Christopher

Reputation: 9804

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.

Upvotes: 4

fernacolo
fernacolo

Reputation: 7439

I found my mistake. The problem is that the IPv4 in the end takes 2 groups of hex digits in the IPv6 notation, and I intuitively thought it was just one group.

Therefore, terms like 0:0:0:0:0:0:0:1.2.3.4, with 7 groups before the IPv4, would not parse. However, terms like 0:0:0:0:0:0:1.2.3.4, with just 6 groups parses just fine.

Upvotes: 2

Related Questions