blob: 7259c7f7a04b1fbaa98d63c395bd6b970393037b [file] [log] [blame]
alshabib1f44e8e2014-08-14 15:19:57 -07001package org.projectfloodlight.openflow.types;
2
3import java.math.BigInteger;
4import java.util.Arrays;
5
6public class IPv6AddressWithMask extends IPAddressWithMask<IPv6Address> {
7 public final static IPv6AddressWithMask NONE = of(IPv6Address.NONE, IPv6Address.NONE);
8
9 private IPv6AddressWithMask(IPv6Address value, IPv6Address mask) {
10 super(value, mask);
11 }
12
13 @Override
14 public IPVersion getIpVersion() {
15 return IPVersion.IPv6;
16 }
17
18 public static IPv6AddressWithMask of(IPv6Address value, IPv6Address mask) {
19 if (value == null) {
20 throw new NullPointerException("Value must not be null");
21 }
22 if (mask == null) {
23 throw new NullPointerException("Mask must not be null");
24 }
25 return new IPv6AddressWithMask(value, mask);
26 }
27
28
29 public static IPv6AddressWithMask of(final String string) {
30 if (string == null) {
31 throw new NullPointerException("String must not be null");
32 }
33 int slashPos;
34 String ip = string;
35 int maskBits = 128;
36 IPv6Address maskAddress = null;
37
38 // Read mask suffix
39 if ((slashPos = string.indexOf('/')) != -1) {
40 ip = string.substring(0, slashPos);
41 try {
42 String suffix = string.substring(slashPos + 1);
43 if (suffix.length() == 0)
44 throw new IllegalArgumentException("IPv6 Address not well formed: " + string);
45 if (suffix.indexOf(':') != -1) {
46 // Full mask
47 maskAddress = IPv6Address.of(suffix);
48 } else {
49 // CIDR Suffix
50 maskBits = Integer.parseInt(suffix);
51 }
52 } catch (NumberFormatException e) {
53 throw new IllegalArgumentException("IPv6 Address not well formed: " + string);
54 }
55 if (maskBits < 0 || maskBits > 128) {
56 throw new IllegalArgumentException("IPv6 Address not well formed: " + string);
57 }
58 }
59
60 // Read IP
61 IPv6Address ipv6 = IPv6Address.of(ip);
62
63 if (maskAddress != null) {
64 // Full address mask
65 return IPv6AddressWithMask.of(ipv6, maskAddress);
66 } else if (maskBits == 128) {
67 // No mask
68 return IPv6AddressWithMask.of(ipv6, IPv6Address.NO_MASK);
69 } else if (maskBits == 0) {
70 // Entirely masked out
71 return IPv6AddressWithMask.of(ipv6, IPv6Address.FULL_MASK);
72 }else {
73 // With mask
74 BigInteger mask = BigInteger.ONE.negate().shiftLeft(128 - maskBits);
75 byte[] maskBytesTemp = mask.toByteArray();
76 byte[] maskBytes;
77 if (maskBytesTemp.length < 16) {
78 maskBytes = new byte[16];
79 System.arraycopy(maskBytesTemp, 0, maskBytes, 16 - maskBytesTemp.length, maskBytesTemp.length);
80 Arrays.fill(maskBytes, 0, 16 - maskBytesTemp.length, (byte)(0xFF));
81 } else if (maskBytesTemp.length > 16) {
82 maskBytes = new byte[16];
83 System.arraycopy(maskBytesTemp, 0, maskBytes, 0, maskBytes.length);
84 } else {
85 maskBytes = maskBytesTemp;
86 }
87 return IPv6AddressWithMask.of(ipv6, IPv6Address.of(maskBytes));
88 }
89 }
90
91
92}