1
2
3
4
5 package net.sourceforge.jsdp.util;
6
7 import java.io.Serializable;
8 import java.net.Inet4Address;
9 import java.net.InetAddress;
10 import java.net.UnknownHostException;
11 import java.util.regex.Pattern;
12
13 import net.sourceforge.jsdp.SDPException;
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 public class Address implements Cloneable, Serializable {
30
31
32 private static final long serialVersionUID = -3442566371424669052L;
33
34
35
36
37
38
39
40
41 private static final Pattern fqdnPattern = Pattern.compile("([a-zA-Z]+(([\\w-]+)*[\\w]+)*)+(\\.[a-zA-Z]+(([\\w-]+)*[\\w]+)*)*");
42
43
44 public static final String IN = "IN";
45
46
47 private static final String FQDN = "FQDN";
48
49
50 public static final String IP4 = "IP4";
51
52
53 public static final String IP6 = "IP6";
54
55
56 protected String address;
57
58
59 protected String addressType;
60
61
62
63
64
65 protected Address() {
66
67 super();
68
69 try {
70 setAddress(InetAddress.getLocalHost().getHostAddress());
71 }
72 catch (Exception someException) {
73
74 }
75 }
76
77
78
79
80
81
82
83
84 public Address(final String address) throws SDPException {
85
86 super();
87
88 if (address == null) {
89 throw new SDPException("Invalid host name");
90 }
91
92 setAddress(address);
93 }
94
95
96
97
98
99
100
101
102
103
104 public static boolean isFQDN(final String address) {
105
106 return fqdnPattern.matcher(address).matches();
107 }
108
109
110
111
112
113
114 public Object clone() {
115
116 Address host = new Address();
117
118 host.addressType = this.addressType;
119 host.address = new String(this.address);
120
121 return host;
122 }
123
124
125
126
127
128
129
130
131
132
133 public boolean equals(final Object object) {
134
135 if (!(object instanceof Address)) {
136 return false;
137 }
138
139 Address otherHost = (Address) object;
140 return otherHost.address.equalsIgnoreCase(this.address);
141 }
142
143
144
145
146
147
148 public String getAddress() {
149
150 return address;
151 }
152
153
154
155
156
157
158
159
160
161
162
163 public String getAddressType() {
164
165 return addressType;
166 }
167
168
169
170
171
172
173
174
175 public boolean isFQDN() {
176
177 return addressType.compareTo(FQDN) == 0;
178 }
179
180
181
182
183
184
185
186 public boolean isIPAddress() {
187
188 return addressType.compareTo(FQDN) != 0;
189 }
190
191
192
193
194
195
196
197
198 public void setAddress(final String address) throws SDPException {
199
200 if (isFQDN(address)) {
201 this.address = address;
202
203
204
205
206 this.addressType = IP4;
207 }
208 else {
209 try {
210 InetAddress ip = InetAddress.getByName(address);
211 this.addressType = (ip instanceof Inet4Address) ? IP4 : IP6;
212
213
214
215
216 this.address = address;
217 }
218 catch (UnknownHostException invalidIP) {
219 throw new SDPException("Not IP4 or IP6 address: " + address);
220 }
221 }
222 }
223
224
225
226
227
228
229 public String toString() {
230
231 return addressType + " " + address;
232 }
233 }