Thursday, July 23, 2020

C# .NET How to convert IPv4 mapped to IPv6 CIDR address

Converting IPv4 addresses that have been mapped into the IPv6 address as follows; 


Source: http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding-2.htm

Here's how to convert the IPv4 mapped to IPv6 address CIDR value 

Example:   222.1.41.90/23  maps to  ::FFFF:222.1.41.90/119

C# Code to convert CIDR from IPv4 to mapped IPv6 address


        public static byte ConvertIPv4toIPv6CIDR(this byte CIDRIPv4)
        {
            //IPv4 CIDR - https://www.keycdn.com/support/what-is-cidr
            //IPv6 range for IPv4 conversion, startfrom bottom
            //https://www.easycalculation.com/other/cidr-blocks-table.php

            if (CIDRIPv4 < 1 || CIDRIPv4 > 32) return 0; // /1-32 range accepted for ipv4

            int CIDRipv6 = 128 - (32 - CIDRIPv4); //lower is 96
            
            return (byte)CIDRipv6;
        }

No comments:

Post a Comment