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