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