blob: 86795aa875885e68f4541463a2d9a08a64e0e74d [file] [log] [blame]
Jonathan Hart23701d12014-04-03 10:45:48 -07001package net.onrc.onos.core.util;
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -08002
Jonathan Hart23701d12014-04-03 10:45:48 -07003import net.onrc.onos.core.util.serializers.IPv4Deserializer;
4import net.onrc.onos.core.util.serializers.IPv4Serializer;
Pavlin Radoslavovad008e02013-02-21 18:42:42 -08005
Pavlin Radoslavov2013cbb2013-02-26 10:15:18 -08006import org.codehaus.jackson.map.annotate.JsonDeserialize;
Pavlin Radoslavovad008e02013-02-21 18:42:42 -08007import org.codehaus.jackson.map.annotate.JsonSerialize;
8
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -08009/**
10 * The class representing an IPv4 address.
11 */
Pavlin Radoslavov2013cbb2013-02-26 10:15:18 -080012@JsonDeserialize(using=IPv4Deserializer.class)
Pavlin Radoslavovad008e02013-02-21 18:42:42 -080013@JsonSerialize(using=IPv4Serializer.class)
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -080014public class IPv4 {
15 private int value;
16
17 /**
18 * Default constructor.
19 */
20 public IPv4() {
21 this.value = 0;
22 }
23
24 /**
Pavlin Radoslavov1bc2c472013-07-17 18:11:37 -070025 * Copy constructor.
26 *
27 * @param other the object to copy from.
28 */
29 public IPv4(IPv4 other) {
30 this.value = other.value;
31 }
32
33 /**
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -080034 * Constructor from an integer value.
35 *
36 * @param value the value to use.
37 */
38 public IPv4(int value) {
39 this.value = value;
40 }
41
42 /**
Pavlin Radoslavov2013cbb2013-02-26 10:15:18 -080043 * Constructor from a string.
44 *
45 * @param value the value to use.
46 */
47 public IPv4(String value) {
48 String[] splits = value.split("\\.");
49 if (splits.length != 4)
50 throw new IllegalArgumentException("Specified IPv4 address must contain four " +
51 "numerical digits separated by '.'");
52
53 int result = 0;
54 for (int i = 0; i < 4; ++i) {
55 result |= Integer.valueOf(splits[i]) << ((3-i)*8);
56 }
57 this.value = result;
58 }
59
60 /**
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -080061 * Get the value of the IPv4 address.
62 *
63 * @return the value of the IPv4 address.
64 */
65 public int value() { return value; }
66
67 /**
68 * Set the value of the IPv4 address.
69 *
70 * @param value the value to set.
71 */
72 public void setValue(int value) {
73 this.value = value;
74 }
75
76 /**
77 * Convert the IPv4 value to a '.' separated string.
78 *
79 * @return the IPv4 value as a '.' separated string.
80 */
81 @Override
82 public String toString() {
Pavlin Radoslavovad008e02013-02-21 18:42:42 -080083 return ((this.value >> 24) & 0xFF) + "." +
84 ((this.value >> 16) & 0xFF) + "." +
85 ((this.value >> 8) & 0xFF) + "." +
86 (this.value & 0xFF);
Pavlin Radoslavov5363c2a2013-02-18 09:55:42 -080087 }
88}