Repository navigation
Expand file tree
/
Copy pathHostName.java
More file actions
399 lines (352 loc) · 11.5 KB
/
Copy pathHostName.java
File metadata and controls
399 lines (352 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
* Copyright 2017 Sean C Foley
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* or at
* https://github.com/seancfoley/IPAddress/blob/master/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package inet.ipaddr;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import inet.ipaddr.IPAddress.IPVersion;
import inet.ipaddr.format.validate.AddressProvider;
import inet.ipaddr.format.validate.HostIdentifierStringValidator;
import inet.ipaddr.format.validate.ParsedHost;
import inet.ipaddr.format.validate.Validator;
/**
* An internet host name. Can be a fully qualified domain name, a simple host name, or an ip address string.
* <p>
* <h2>Supported formats</h2>
* You can use all host or address formats supported by nmap and all address formats supported by {@link IPAddressString}.
* All manners of domain names are supported. You can add a prefix length to denote the subnet of the resolved address.
* <p>
* Validation is done separately from DNS resolution to avoid unnecessary lookups.
* <p>
* See rfc 3513, 2181, 952, 1035, 1034, 1123, 5890 or the list of rfcs for IPAddress. For IPv6 addresses in host, see rfc 2732 specifying [] notation
* and 4038 (combining IPv6 [] with prefix or zone) and SMTP rfc 2821 for alternative uses of [] for both IPv4 and IPv6
* <p>
*
* @custom.core
* @author sfoley
*/
public class HostName implements HostIdentifierString, Comparable<HostName>, Serializable {
private static final long serialVersionUID = 1L;
public static final char LABEL_SEPARATOR = '.';
public static final char IPV6_START_BRACKET = '[', IPV6_END_BRACKET = ']';
/* Generally permissive, settings are the default constants in HostNameParameters */
private static final HostNameParameters DEFAULT_BASIC_VALIDATION_OPTIONS = new HostNameParameters.Builder().toOptions();
/* the original host in string format */
private final String host;
/* a normalized string representing the host, in practice the only normalization needed is lowercase */
private transient String normalizedString;
/* the host broken into its parsed components */
private ParsedHost parsedHost;
private HostNameException validationException;
/* The address if this host represents an ip address, or the address obtained when this host is resolved. */
IPAddress resolvedAddress;
/* validation options */
private final HostNameParameters validationOptions;
public HostName(IPAddress addr) {
normalizedString = host = addr.toNormalizedString();
parsedHost = new ParsedHost(host, AddressProvider.getProviderFor(addr));
validationOptions = null;
}
public HostName(InetAddress inetAddr) {
this(IPAddress.from(inetAddr));
}
HostName(String host, ParsedHost parsed) {
this.host = host;
parsedHost = parsed;
validationOptions = null;
}
public HostName(String host) {
this(host, DEFAULT_BASIC_VALIDATION_OPTIONS);
}
public HostName(String host, HostNameParameters options) {
if(options == null) {
throw new NullPointerException();
}
this.validationOptions = options;
this.host = (host == null) ? "" : host.trim();;
}
void cacheAddress(IPAddress addr) {
if(parsedHost == null) {
parsedHost = new ParsedHost(host, AddressProvider.getProviderFor(addr));
normalizedString = addr.toNormalizedString();
} else if(normalizedString == null) {
normalizedString = addr.toNormalizedString();
}
}
public HostNameParameters getValidationOptions() {
return validationOptions;
}
public void validate() throws HostNameException {
if(parsedHost != null) {
return;
}
if(validationException != null) {
throw validationException;
}
synchronized(this) {
if(parsedHost != null) {
return;
}
if(validationException != null) {
throw validationException;
}
try {
parsedHost = getValidator().validateHost(this);
} catch(HostNameException e) {
validationException = e;
throw e;
}
}
}
protected HostIdentifierStringValidator getValidator() {
return Validator.VALIDATOR;
}
public boolean isValid() {
if(parsedHost != null) {
return true;
}
if(validationException != null) {
return false;
}
try {
validate();
return true;
} catch(HostNameException e) {
return false;
}
}
public boolean resolvesToSelf() {
return isSelf() || (resolve() != null && resolvedAddress.isLoopback());
}
public boolean isSelf() {
return isLocalHost() || isLoopback();
}
public boolean isLocalHost() {
return isValid() && host.equalsIgnoreCase("localhost");
}
/*
* [::1] (aka [0:0:0:0:0:0:0:1]) or 127.0.0.1
*/
public boolean isLoopback() {
return isAddress() && asAddress().isLoopback();
}
public InetAddress toInetAddress() throws HostNameException, UnknownHostException {
validate();
return toResolvedAddress().toInetAddress();
}
@Override
public String toNormalizedString() {
String result = normalizedString;
if(result == null) {
try {
validate();
if(isAddressString()) {
result = IPAddressString.toNormalizedString(parsedHost.addressProvider);
} else {
result = parsedHost.getHost();
}
} catch(HostNameException e) {
//for invalid hosts, don't normalize, just return it as is
result = host;
}
normalizedString = result;
}
return result;
}
@Override
public String toString() {
return host;
}
@Override
public boolean equals(Object o) {
return o instanceof HostName && matches((HostName) o);
}
public boolean matches(HostName host) {
if(this == host) {
return true;
}
if(isAddressString()) {//address strings match
return host.isValid() && parsedHost.addressProvider.equals(host.parsedHost.addressProvider);
}
return toNormalizedString().equals(host.toNormalizedString());
}
@Override
public int hashCode() {
if(isValid() && parsedHost.addressProvider != null) {
IPAddress val = parsedHost.addressProvider.getAddress();
if(val != null) {
return val.hashCode();
}
return parsedHost.asGenericAddressString().hashCode();
}
return toNormalizedString().hashCode();
}
public String[] getNormalizedLabels() {
if(isValid()) {
return parsedHost.getNormalizedLabels();
}
if(host.length() == 0) {
return new String[0];
}
return new String[] {host};
}
@Override
public int compareTo(HostName other) {
if(isAddress()) {
if(other.isAddress()) {
return asAddress().compareTo(other.asAddress());
} else {
return -1;
}
} else {
if(other.isAddress()) {
return 1;
} else {
String normalizedLabels[] = parsedHost.getNormalizedLabels();
if(normalizedLabels != null) {
String otherNormalizedLabels[] = other.parsedHost.getNormalizedLabels();
if(otherNormalizedLabels != null) {
for(int i=1, max = Math.min(normalizedLabels.length, otherNormalizedLabels.length); i>=max; i--) {
String one = normalizedLabels[normalizedLabels.length - i];
String two = otherNormalizedLabels[otherNormalizedLabels.length - i];
int result = one.compareTo(two);
if(result != 0) {
return result;
}
}
return normalizedLabels.length - otherNormalizedLabels.length;
}
}
}
}
return toNormalizedString().compareTo(other.toNormalizedString());
}
public boolean isAddress(IPVersion version) {
return isValid() && parsedHost.addressProvider != null && parsedHost.addressProvider.getAddress(version) != null;
}
public boolean isAddress() {
return isAddressString() && parsedHost.addressProvider.getAddress() != null;
}
public boolean isAddressString() {
return isValid() && parsedHost.addressProvider != null;
}
/**
* @return whether the address represents the set all all valid IP addresses (as opposed to an empty string, a specific address, a prefix length, or an invalid format).
*/
public boolean isAllAddresses() {
return isAddressString() && parsedHost.addressProvider.isAllAddresses();
}
/**
* @return whether the address represents a valid IP address network prefix (as opposed to an empty string, an address with or without a prefix, or an invalid format).
*/
public boolean isPrefixOnly() {
return isAddressString() && parsedHost.addressProvider.isPrefixOnly();
}
/**
* Returns true if the address is empty (zero-length).
* @return
*/
public boolean isEmpty() {
return isAddressString() && parsedHost.addressProvider.isEmpty();
}
/**
* If this represents an address that was not bracketed as a host, then it returns the bracketed address as a host.
* This is the standard for IPv6 in URLs.
* Otherwise, it returns the original string.
*/
public String toURLString() {
if(isAddress()) {
IPAddress addr = asAddress();
if(addr.isPrefixed()) {//prefix needs to be outside the brackets
int bits = addr.getNetworkPrefixLength();
IPAddress addrNoPrefix = addr.toSubnet(addr.getNetwork().getNetworkMask(bits));//either we mask it or we grab the lowest value of the range to get rid of prefix
return IPV6_START_BRACKET + addrNoPrefix.toNormalizedString() + IPV6_END_BRACKET + IPAddress.PREFIX_LEN_SEPARATOR + bits;
} else {
return IPV6_START_BRACKET + addr.toNormalizedString() + IPV6_END_BRACKET;
}
}
return toNormalizedString();
}
/**
* If this represents an ip address or represents a valid IPAddressString, returns the corresponding address string.
* Otherwise, returns null. Call toResolvedAddress or resolve to get the resolved address.
* @return
*/
public IPAddressString asAddressString() {
if(isAddressString()) {
IPAddress val = parsedHost.addressProvider.getAddress();
if(val != null) {
return val.toAddressString();
}
return parsedHost.asGenericAddressString();
}
return null;
}
/**
* If this represents an ip address, returns that address.
* Otherwise, returns null. Call toResolvedAddress or resolve to get the resolved address, which is different.
*
* @return
*/
public IPAddress asAddress() {
if(isAddress()) {
return parsedHost.addressProvider.getAddress();
}
return null;
}
/**
* If this represents an ip address, returns that address.
* Otherwise, returns null. Call toResolvedAddress or resolve to get the resolved address, which is different.
*
* @return
*/
public IPAddress asAddress(IPVersion version) {
if(isAddress(version)) {
return parsedHost.addressProvider.getAddress(version);
}
return null;
}
public IPAddress toResolvedAddress() throws UnknownHostException, HostNameException {
IPAddress addr = resolvedAddress;
if(addr == null) {
//note that validation handles empty address resolution
validate();
synchronized(this) {
addr = resolvedAddress;
if(addr == null) {
resolvedAddress = addr = parsedHost.resolveAddress(this, validationOptions);
}
}
}
return addr;
}
/**
* If this represents an ip address, returns that address.
* If this represents a host, returns the resolved ip address of that host.
* Otherwise, returns null.
* @return
*/
public IPAddress resolve() {
try {
return toResolvedAddress();
} catch(HostNameException | UnknownHostException e) {
//call toResolvedAddress if you wish to see this exception
}
return null;
}
}