0

My IPv6 knowledge is very limited, could help me solve this question? As known, for IPv4, if the netmask is 25, the mapping address should be 255.255.255.128. Codes of arithmetic is like:

public static String getNetmaskFromBits( int bits )
    {
        StringBuilder b = new StringBuilder( 15 );
        int tempBits = 0xFFFFFFFF;
        tempBits = tempBits << 32 - bits;
        b.append( ( tempBits & 0xFF000000 ) >>> 24 ).append( '.' );
        b.append( ( tempBits & 0x00FF0000 ) >>> 16 ).append( '.' );
        b.append( ( tempBits & 0x0000FF00 ) >>> 8 ).append( '.' );
        b.append( tempBits & 0x000000FF );
        return b.toString();
    }

How about IPv6? It can be 128 bits. How to map it to IPv6 address? Codes should be like:

public static String getIpv6NetmaskFromBits( int bits )
    {
        StringBuilder b = new StringBuilder( 15 );
        ...
        return b.toString();
    }
l0b0
  • 55,365
  • 30
  • 138
  • 223
etianQQ
  • 167
  • 2
  • 9
  • This question refers to a binary packed netmask rather than text form: http://stackoverflow.com/q/7158528/175849 – Steve-o Feb 01 '13 at 14:25

1 Answers1

1

You don't do that kind of masking anymore with IPv6. Prefixes are always displayed using CIDR notation, like 2001:db8::/32.

If you really want to do this then the easiest way is to divide the prefix length by 4. Start with that many f characters, which is hexadecimal for the binary value 1111. If there is a remainder then add the next character based on the remainder. If the remainder is 1 then the next character is 8, if the remainder is 2 then the next character is c, and if the remainder is 3 then the next character is e. Then add as many 0's as necessary to get a total of 32 characters. Then add a : separator after every fourth character.

Apply address notation compression if you like :-)

Example:

A /32:

Divide: 32 / 4 = 8
8 * f = 'ffffffff'
Add 0's: 'ffffffff000000000000000000000000'
Add separators: 'ffff:ffff:0000:0000:0000:0000:0000:0000'
Compress notation: 'ffff:ffff::'

A /33:

Divide: 33 / 4 = 8, remainder: 1
8 * f = 'ffffffff'
Add for remainder: 'ffffffff8'
Add 0's: 'ffffffff800000000000000000000000'
Add separators: 'ffff:ffff:8000:0000:0000:0000:0000:0000'
Compress notation: 'ffff:ffff:8000::'

A /34:

Divide: 34 / 4 = 8, remainder: 2
8 * f = 'ffffffff'
Add for remainder: 'ffffffffc'
Add 0's: 'ffffffffc00000000000000000000000'
Add separators: 'ffff:ffff:c000:0000:0000:0000:0000:0000'
Compress notation: 'ffff:ffff:c000::'

A /35:

Divide: 35 / 4 = 8, remainder: 3
8 * f = 'ffffffff'
Add for remainder: 'ffffffffe'
Add 0's: 'ffffffffe00000000000000000000000'
Add separators: 'ffff:ffff:e000:0000:0000:0000:0000:0000'
Compress notation: 'ffff:ffff:e000::'

A /36:

Divide: 36 / 4 = 9
9 * f = 'fffffffff'
Add 0's: 'fffffffff00000000000000000000000'
Add separators: 'ffff:ffff:f000:0000:0000:0000:0000:0000'
Compress notation: 'ffff:ffff:f000::'

Etc.

Sander Steffann
  • 9,509
  • 35
  • 40