blob: ef3a1e5e8a182b954ce7a580c88c4330809e2a18 [file] [log] [blame]
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -08001package net.floodlightcontroller.util;
2
Pavlin Radoslavov2013cbb2013-02-26 10:15:18 -08003import net.floodlightcontroller.util.serializers.IPv4Deserializer;
Pavlin Radoslavovad008e02013-02-21 18:42:42 -08004import net.floodlightcontroller.util.serializers.IPv4Serializer;
5
6import org.codehaus.jackson.annotate.JsonProperty;
Pavlin Radoslavov2013cbb2013-02-26 10:15:18 -08007import org.codehaus.jackson.map.annotate.JsonDeserialize;
Pavlin Radoslavovad008e02013-02-21 18:42:42 -08008import org.codehaus.jackson.map.annotate.JsonSerialize;
9
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -080010/**
11 * The class representing an IPv4 address.
12 */
Pavlin Radoslavov2013cbb2013-02-26 10:15:18 -080013@JsonDeserialize(using=IPv4Deserializer.class)
Pavlin Radoslavovad008e02013-02-21 18:42:42 -080014@JsonSerialize(using=IPv4Serializer.class)
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -080015public class IPv4 {
16 private int value;
17
18 /**
19 * Default constructor.
20 */
21 public IPv4() {
22 this.value = 0;
23 }
24
25 /**
26 * Constructor from an integer value.
27 *
28 * @param value the value to use.
29 */
30 public IPv4(int value) {
31 this.value = value;
32 }
33
34 /**
Pavlin Radoslavov2013cbb2013-02-26 10:15:18 -080035 * Constructor from a string.
36 *
37 * @param value the value to use.
38 */
39 public IPv4(String value) {
40 String[] splits = value.split("\\.");
41 if (splits.length != 4)
42 throw new IllegalArgumentException("Specified IPv4 address must contain four " +
43 "numerical digits separated by '.'");
44
45 int result = 0;
46 for (int i = 0; i < 4; ++i) {
47 result |= Integer.valueOf(splits[i]) << ((3-i)*8);
48 }
49 this.value = result;
50 }
51
52 /**
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -080053 * Get the value of the IPv4 address.
54 *
55 * @return the value of the IPv4 address.
56 */
57 public int value() { return value; }
58
59 /**
60 * Set the value of the IPv4 address.
61 *
62 * @param value the value to set.
63 */
64 public void setValue(int value) {
65 this.value = value;
66 }
67
68 /**
69 * Convert the IPv4 value to a '.' separated string.
70 *
71 * @return the IPv4 value as a '.' separated string.
72 */
73 @Override
74 public String toString() {
Pavlin Radoslavovad008e02013-02-21 18:42:42 -080075 return ((this.value >> 24) & 0xFF) + "." +
76 ((this.value >> 16) & 0xFF) + "." +
77 ((this.value >> 8) & 0xFF) + "." +
78 (this.value & 0xFF);
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -080079 }
80}