Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/net/InetAddress.java
38829 views
1
/*
2
* Copyright (c) 1995, 2018, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.net;
27
28
import java.util.HashMap;
29
import java.util.LinkedHashMap;
30
import java.util.Random;
31
import java.util.Iterator;
32
import java.util.LinkedList;
33
import java.util.List;
34
import java.util.ArrayList;
35
import java.util.ServiceLoader;
36
import java.security.AccessController;
37
import java.io.ObjectStreamException;
38
import java.io.ObjectStreamField;
39
import java.io.IOException;
40
import java.io.InvalidObjectException;
41
import java.io.ObjectInputStream;
42
import java.io.ObjectInputStream.GetField;
43
import java.io.ObjectOutputStream;
44
import java.io.ObjectOutputStream.PutField;
45
import sun.security.action.*;
46
import sun.net.InetAddressCachePolicy;
47
import sun.net.util.IPAddressUtil;
48
import sun.net.spi.nameservice.*;
49
50
/**
51
* This class represents an Internet Protocol (IP) address.
52
*
53
* <p> An IP address is either a 32-bit or 128-bit unsigned number
54
* used by IP, a lower-level protocol on which protocols like UDP and
55
* TCP are built. The IP address architecture is defined by <a
56
* href="http://www.ietf.org/rfc/rfc790.txt"><i>RFC&nbsp;790:
57
* Assigned Numbers</i></a>, <a
58
* href="http://www.ietf.org/rfc/rfc1918.txt"> <i>RFC&nbsp;1918:
59
* Address Allocation for Private Internets</i></a>, <a
60
* href="http://www.ietf.org/rfc/rfc2365.txt"><i>RFC&nbsp;2365:
61
* Administratively Scoped IP Multicast</i></a>, and <a
62
* href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IP
63
* Version 6 Addressing Architecture</i></a>. An instance of an
64
* InetAddress consists of an IP address and possibly its
65
* corresponding host name (depending on whether it is constructed
66
* with a host name or whether it has already done reverse host name
67
* resolution).
68
*
69
* <h3> Address types </h3>
70
*
71
* <blockquote><table cellspacing=2 summary="Description of unicast and multicast address types">
72
* <tr><th valign=top><i>unicast</i></th>
73
* <td>An identifier for a single interface. A packet sent to
74
* a unicast address is delivered to the interface identified by
75
* that address.
76
*
77
* <p> The Unspecified Address -- Also called anylocal or wildcard
78
* address. It must never be assigned to any node. It indicates the
79
* absence of an address. One example of its use is as the target of
80
* bind, which allows a server to accept a client connection on any
81
* interface, in case the server host has multiple interfaces.
82
*
83
* <p> The <i>unspecified</i> address must not be used as
84
* the destination address of an IP packet.
85
*
86
* <p> The <i>Loopback</i> Addresses -- This is the address
87
* assigned to the loopback interface. Anything sent to this
88
* IP address loops around and becomes IP input on the local
89
* host. This address is often used when testing a
90
* client.</td></tr>
91
* <tr><th valign=top><i>multicast</i></th>
92
* <td>An identifier for a set of interfaces (typically belonging
93
* to different nodes). A packet sent to a multicast address is
94
* delivered to all interfaces identified by that address.</td></tr>
95
* </table></blockquote>
96
*
97
* <h4> IP address scope </h4>
98
*
99
* <p> <i>Link-local</i> addresses are designed to be used for addressing
100
* on a single link for purposes such as auto-address configuration,
101
* neighbor discovery, or when no routers are present.
102
*
103
* <p> <i>Site-local</i> addresses are designed to be used for addressing
104
* inside of a site without the need for a global prefix.
105
*
106
* <p> <i>Global</i> addresses are unique across the internet.
107
*
108
* <h4> Textual representation of IP addresses </h4>
109
*
110
* The textual representation of an IP address is address family specific.
111
*
112
* <p>
113
*
114
* For IPv4 address format, please refer to <A
115
* HREF="Inet4Address.html#format">Inet4Address#format</A>; For IPv6
116
* address format, please refer to <A
117
* HREF="Inet6Address.html#format">Inet6Address#format</A>.
118
*
119
* <P>There is a <a href="doc-files/net-properties.html#Ipv4IPv6">couple of
120
* System Properties</a> affecting how IPv4 and IPv6 addresses are used.</P>
121
*
122
* <h4> Host Name Resolution </h4>
123
*
124
* Host name-to-IP address <i>resolution</i> is accomplished through
125
* the use of a combination of local machine configuration information
126
* and network naming services such as the Domain Name System (DNS)
127
* and Network Information Service(NIS). The particular naming
128
* services(s) being used is by default the local machine configured
129
* one. For any host name, its corresponding IP address is returned.
130
*
131
* <p> <i>Reverse name resolution</i> means that for any IP address,
132
* the host associated with the IP address is returned.
133
*
134
* <p> The InetAddress class provides methods to resolve host names to
135
* their IP addresses and vice versa.
136
*
137
* <h4> InetAddress Caching </h4>
138
*
139
* The InetAddress class has a cache to store successful as well as
140
* unsuccessful host name resolutions.
141
*
142
* <p> By default, when a security manager is installed, in order to
143
* protect against DNS spoofing attacks,
144
* the result of positive host name resolutions are
145
* cached forever. When a security manager is not installed, the default
146
* behavior is to cache entries for a finite (implementation dependent)
147
* period of time. The result of unsuccessful host
148
* name resolution is cached for a very short period of time (10
149
* seconds) to improve performance.
150
*
151
* <p> If the default behavior is not desired, then a Java security property
152
* can be set to a different Time-to-live (TTL) value for positive
153
* caching. Likewise, a system admin can configure a different
154
* negative caching TTL value when needed.
155
*
156
* <p> Two Java security properties control the TTL values used for
157
* positive and negative host name resolution caching:
158
*
159
* <blockquote>
160
* <dl>
161
* <dt><b>networkaddress.cache.ttl</b></dt>
162
* <dd>Indicates the caching policy for successful name lookups from
163
* the name service. The value is specified as as integer to indicate
164
* the number of seconds to cache the successful lookup. The default
165
* setting is to cache for an implementation specific period of time.
166
* <p>
167
* A value of -1 indicates "cache forever".
168
* </dd>
169
* <dt><b>networkaddress.cache.negative.ttl</b> (default: 10)</dt>
170
* <dd>Indicates the caching policy for un-successful name lookups
171
* from the name service. The value is specified as as integer to
172
* indicate the number of seconds to cache the failure for
173
* un-successful lookups.
174
* <p>
175
* A value of 0 indicates "never cache".
176
* A value of -1 indicates "cache forever".
177
* </dd>
178
* </dl>
179
* </blockquote>
180
*
181
* @author Chris Warth
182
* @see java.net.InetAddress#getByAddress(byte[])
183
* @see java.net.InetAddress#getByAddress(java.lang.String, byte[])
184
* @see java.net.InetAddress#getAllByName(java.lang.String)
185
* @see java.net.InetAddress#getByName(java.lang.String)
186
* @see java.net.InetAddress#getLocalHost()
187
* @since JDK1.0
188
*/
189
public
190
class InetAddress implements java.io.Serializable {
191
/**
192
* Specify the address family: Internet Protocol, Version 4
193
* @since 1.4
194
*/
195
static final int IPv4 = 1;
196
197
/**
198
* Specify the address family: Internet Protocol, Version 6
199
* @since 1.4
200
*/
201
static final int IPv6 = 2;
202
203
/* Specify address family preference */
204
static transient boolean preferIPv6Address = false;
205
206
static class InetAddressHolder {
207
/**
208
* Reserve the original application specified hostname.
209
*
210
* The original hostname is useful for domain-based endpoint
211
* identification (see RFC 2818 and RFC 6125). If an address
212
* was created with a raw IP address, a reverse name lookup
213
* may introduce endpoint identification security issue via
214
* DNS forging.
215
*
216
* Oracle JSSE provider is using this original hostname, via
217
* sun.misc.JavaNetAccess, for SSL/TLS endpoint identification.
218
*
219
* Note: May define a new public method in the future if necessary.
220
*/
221
String originalHostName;
222
223
InetAddressHolder() {}
224
225
InetAddressHolder(String hostName, int address, int family) {
226
this.originalHostName = hostName;
227
this.hostName = hostName;
228
this.address = address;
229
this.family = family;
230
}
231
232
void init(String hostName, int family) {
233
this.originalHostName = hostName;
234
this.hostName = hostName;
235
if (family != -1) {
236
this.family = family;
237
}
238
}
239
240
String hostName;
241
242
String getHostName() {
243
return hostName;
244
}
245
246
String getOriginalHostName() {
247
return originalHostName;
248
}
249
250
/**
251
* Holds a 32-bit IPv4 address.
252
*/
253
int address;
254
255
int getAddress() {
256
return address;
257
}
258
259
/**
260
* Specifies the address family type, for instance, '1' for IPv4
261
* addresses, and '2' for IPv6 addresses.
262
*/
263
int family;
264
265
int getFamily() {
266
return family;
267
}
268
}
269
270
/* Used to store the serializable fields of InetAddress */
271
final transient InetAddressHolder holder;
272
273
InetAddressHolder holder() {
274
return holder;
275
}
276
277
/* Used to store the name service provider */
278
private static List<NameService> nameServices = null;
279
280
/* Used to store the best available hostname */
281
private transient String canonicalHostName = null;
282
283
/** use serialVersionUID from JDK 1.0.2 for interoperability */
284
private static final long serialVersionUID = 3286316764910316507L;
285
286
/*
287
* Load net library into runtime, and perform initializations.
288
*/
289
static {
290
preferIPv6Address = java.security.AccessController.doPrivileged(
291
new GetBooleanAction("java.net.preferIPv6Addresses")).booleanValue();
292
AccessController.doPrivileged(
293
new java.security.PrivilegedAction<Void>() {
294
public Void run() {
295
System.loadLibrary("net");
296
return null;
297
}
298
});
299
init();
300
}
301
302
/**
303
* Constructor for the Socket.accept() method.
304
* This creates an empty InetAddress, which is filled in by
305
* the accept() method. This InetAddress, however, is not
306
* put in the address cache, since it is not created by name.
307
*/
308
InetAddress() {
309
holder = new InetAddressHolder();
310
}
311
312
/**
313
* Replaces the de-serialized object with an Inet4Address object.
314
*
315
* @return the alternate object to the de-serialized object.
316
*
317
* @throws ObjectStreamException if a new object replacing this
318
* object could not be created
319
*/
320
private Object readResolve() throws ObjectStreamException {
321
// will replace the deserialized 'this' object
322
return new Inet4Address(holder().getHostName(), holder().getAddress());
323
}
324
325
/**
326
* Utility routine to check if the InetAddress is an
327
* IP multicast address.
328
* @return a {@code boolean} indicating if the InetAddress is
329
* an IP multicast address
330
* @since JDK1.1
331
*/
332
public boolean isMulticastAddress() {
333
return false;
334
}
335
336
/**
337
* Utility routine to check if the InetAddress in a wildcard address.
338
* @return a {@code boolean} indicating if the Inetaddress is
339
* a wildcard address.
340
* @since 1.4
341
*/
342
public boolean isAnyLocalAddress() {
343
return false;
344
}
345
346
/**
347
* Utility routine to check if the InetAddress is a loopback address.
348
*
349
* @return a {@code boolean} indicating if the InetAddress is
350
* a loopback address; or false otherwise.
351
* @since 1.4
352
*/
353
public boolean isLoopbackAddress() {
354
return false;
355
}
356
357
/**
358
* Utility routine to check if the InetAddress is an link local address.
359
*
360
* @return a {@code boolean} indicating if the InetAddress is
361
* a link local address; or false if address is not a link local unicast address.
362
* @since 1.4
363
*/
364
public boolean isLinkLocalAddress() {
365
return false;
366
}
367
368
/**
369
* Utility routine to check if the InetAddress is a site local address.
370
*
371
* @return a {@code boolean} indicating if the InetAddress is
372
* a site local address; or false if address is not a site local unicast address.
373
* @since 1.4
374
*/
375
public boolean isSiteLocalAddress() {
376
return false;
377
}
378
379
/**
380
* Utility routine to check if the multicast address has global scope.
381
*
382
* @return a {@code boolean} indicating if the address has
383
* is a multicast address of global scope, false if it is not
384
* of global scope or it is not a multicast address
385
* @since 1.4
386
*/
387
public boolean isMCGlobal() {
388
return false;
389
}
390
391
/**
392
* Utility routine to check if the multicast address has node scope.
393
*
394
* @return a {@code boolean} indicating if the address has
395
* is a multicast address of node-local scope, false if it is not
396
* of node-local scope or it is not a multicast address
397
* @since 1.4
398
*/
399
public boolean isMCNodeLocal() {
400
return false;
401
}
402
403
/**
404
* Utility routine to check if the multicast address has link scope.
405
*
406
* @return a {@code boolean} indicating if the address has
407
* is a multicast address of link-local scope, false if it is not
408
* of link-local scope or it is not a multicast address
409
* @since 1.4
410
*/
411
public boolean isMCLinkLocal() {
412
return false;
413
}
414
415
/**
416
* Utility routine to check if the multicast address has site scope.
417
*
418
* @return a {@code boolean} indicating if the address has
419
* is a multicast address of site-local scope, false if it is not
420
* of site-local scope or it is not a multicast address
421
* @since 1.4
422
*/
423
public boolean isMCSiteLocal() {
424
return false;
425
}
426
427
/**
428
* Utility routine to check if the multicast address has organization scope.
429
*
430
* @return a {@code boolean} indicating if the address has
431
* is a multicast address of organization-local scope,
432
* false if it is not of organization-local scope
433
* or it is not a multicast address
434
* @since 1.4
435
*/
436
public boolean isMCOrgLocal() {
437
return false;
438
}
439
440
441
/**
442
* Test whether that address is reachable. Best effort is made by the
443
* implementation to try to reach the host, but firewalls and server
444
* configuration may block requests resulting in a unreachable status
445
* while some specific ports may be accessible.
446
* A typical implementation will use ICMP ECHO REQUESTs if the
447
* privilege can be obtained, otherwise it will try to establish
448
* a TCP connection on port 7 (Echo) of the destination host.
449
* <p>
450
* The timeout value, in milliseconds, indicates the maximum amount of time
451
* the try should take. If the operation times out before getting an
452
* answer, the host is deemed unreachable. A negative value will result
453
* in an IllegalArgumentException being thrown.
454
*
455
* @param timeout the time, in milliseconds, before the call aborts
456
* @return a {@code boolean} indicating if the address is reachable.
457
* @throws IOException if a network error occurs
458
* @throws IllegalArgumentException if {@code timeout} is negative.
459
* @since 1.5
460
*/
461
public boolean isReachable(int timeout) throws IOException {
462
return isReachable(null, 0 , timeout);
463
}
464
465
/**
466
* Test whether that address is reachable. Best effort is made by the
467
* implementation to try to reach the host, but firewalls and server
468
* configuration may block requests resulting in a unreachable status
469
* while some specific ports may be accessible.
470
* A typical implementation will use ICMP ECHO REQUESTs if the
471
* privilege can be obtained, otherwise it will try to establish
472
* a TCP connection on port 7 (Echo) of the destination host.
473
* <p>
474
* The {@code network interface} and {@code ttl} parameters
475
* let the caller specify which network interface the test will go through
476
* and the maximum number of hops the packets should go through.
477
* A negative value for the {@code ttl} will result in an
478
* IllegalArgumentException being thrown.
479
* <p>
480
* The timeout value, in milliseconds, indicates the maximum amount of time
481
* the try should take. If the operation times out before getting an
482
* answer, the host is deemed unreachable. A negative value will result
483
* in an IllegalArgumentException being thrown.
484
*
485
* @param netif the NetworkInterface through which the
486
* test will be done, or null for any interface
487
* @param ttl the maximum numbers of hops to try or 0 for the
488
* default
489
* @param timeout the time, in milliseconds, before the call aborts
490
* @throws IllegalArgumentException if either {@code timeout}
491
* or {@code ttl} are negative.
492
* @return a {@code boolean}indicating if the address is reachable.
493
* @throws IOException if a network error occurs
494
* @since 1.5
495
*/
496
public boolean isReachable(NetworkInterface netif, int ttl,
497
int timeout) throws IOException {
498
if (ttl < 0)
499
throw new IllegalArgumentException("ttl can't be negative");
500
if (timeout < 0)
501
throw new IllegalArgumentException("timeout can't be negative");
502
503
return impl.isReachable(this, timeout, netif, ttl);
504
}
505
506
/**
507
* Gets the host name for this IP address.
508
*
509
* <p>If this InetAddress was created with a host name,
510
* this host name will be remembered and returned;
511
* otherwise, a reverse name lookup will be performed
512
* and the result will be returned based on the system
513
* configured name lookup service. If a lookup of the name service
514
* is required, call
515
* {@link #getCanonicalHostName() getCanonicalHostName}.
516
*
517
* <p>If there is a security manager, its
518
* {@code checkConnect} method is first called
519
* with the hostname and {@code -1}
520
* as its arguments to see if the operation is allowed.
521
* If the operation is not allowed, it will return
522
* the textual representation of the IP address.
523
*
524
* @return the host name for this IP address, or if the operation
525
* is not allowed by the security check, the textual
526
* representation of the IP address.
527
*
528
* @see InetAddress#getCanonicalHostName
529
* @see SecurityManager#checkConnect
530
*/
531
public String getHostName() {
532
return getHostName(true);
533
}
534
535
/**
536
* Returns the hostname for this address.
537
* If the host is equal to null, then this address refers to any
538
* of the local machine's available network addresses.
539
* this is package private so SocketPermission can make calls into
540
* here without a security check.
541
*
542
* <p>If there is a security manager, this method first
543
* calls its {@code checkConnect} method
544
* with the hostname and {@code -1}
545
* as its arguments to see if the calling code is allowed to know
546
* the hostname for this IP address, i.e., to connect to the host.
547
* If the operation is not allowed, it will return
548
* the textual representation of the IP address.
549
*
550
* @return the host name for this IP address, or if the operation
551
* is not allowed by the security check, the textual
552
* representation of the IP address.
553
*
554
* @param check make security check if true
555
*
556
* @see SecurityManager#checkConnect
557
*/
558
String getHostName(boolean check) {
559
if (holder().getHostName() == null) {
560
holder().hostName = InetAddress.getHostFromNameService(this, check);
561
}
562
return holder().getHostName();
563
}
564
565
/**
566
* Gets the fully qualified domain name for this IP address.
567
* Best effort method, meaning we may not be able to return
568
* the FQDN depending on the underlying system configuration.
569
*
570
* <p>If there is a security manager, this method first
571
* calls its {@code checkConnect} method
572
* with the hostname and {@code -1}
573
* as its arguments to see if the calling code is allowed to know
574
* the hostname for this IP address, i.e., to connect to the host.
575
* If the operation is not allowed, it will return
576
* the textual representation of the IP address.
577
*
578
* @return the fully qualified domain name for this IP address,
579
* or if the operation is not allowed by the security check,
580
* the textual representation of the IP address.
581
*
582
* @see SecurityManager#checkConnect
583
*
584
* @since 1.4
585
*/
586
public String getCanonicalHostName() {
587
if (canonicalHostName == null) {
588
canonicalHostName =
589
InetAddress.getHostFromNameService(this, true);
590
}
591
return canonicalHostName;
592
}
593
594
/**
595
* Returns the hostname for this address.
596
*
597
* <p>If there is a security manager, this method first
598
* calls its {@code checkConnect} method
599
* with the hostname and {@code -1}
600
* as its arguments to see if the calling code is allowed to know
601
* the hostname for this IP address, i.e., to connect to the host.
602
* If the operation is not allowed, it will return
603
* the textual representation of the IP address.
604
*
605
* @return the host name for this IP address, or if the operation
606
* is not allowed by the security check, the textual
607
* representation of the IP address.
608
*
609
* @param check make security check if true
610
*
611
* @see SecurityManager#checkConnect
612
*/
613
private static String getHostFromNameService(InetAddress addr, boolean check) {
614
String host = null;
615
for (NameService nameService : nameServices) {
616
try {
617
// first lookup the hostname
618
host = nameService.getHostByAddr(addr.getAddress());
619
620
/* check to see if calling code is allowed to know
621
* the hostname for this IP address, ie, connect to the host
622
*/
623
if (check) {
624
SecurityManager sec = System.getSecurityManager();
625
if (sec != null) {
626
sec.checkConnect(host, -1);
627
}
628
}
629
630
/* now get all the IP addresses for this hostname,
631
* and make sure one of them matches the original IP
632
* address. We do this to try and prevent spoofing.
633
*/
634
635
InetAddress[] arr = InetAddress.getAllByName0(host, check);
636
boolean ok = false;
637
638
if(arr != null) {
639
for(int i = 0; !ok && i < arr.length; i++) {
640
ok = addr.equals(arr[i]);
641
}
642
}
643
644
//XXX: if it looks a spoof just return the address?
645
if (!ok) {
646
host = addr.getHostAddress();
647
return host;
648
}
649
650
break;
651
652
} catch (SecurityException e) {
653
host = addr.getHostAddress();
654
break;
655
} catch (UnknownHostException e) {
656
host = addr.getHostAddress();
657
// let next provider resolve the hostname
658
}
659
}
660
661
return host;
662
}
663
664
/**
665
* Returns the raw IP address of this {@code InetAddress}
666
* object. The result is in network byte order: the highest order
667
* byte of the address is in {@code getAddress()[0]}.
668
*
669
* @return the raw IP address of this object.
670
*/
671
public byte[] getAddress() {
672
return null;
673
}
674
675
/**
676
* Returns the IP address string in textual presentation.
677
*
678
* @return the raw IP address in a string format.
679
* @since JDK1.0.2
680
*/
681
public String getHostAddress() {
682
return null;
683
}
684
685
/**
686
* Returns a hashcode for this IP address.
687
*
688
* @return a hash code value for this IP address.
689
*/
690
public int hashCode() {
691
return -1;
692
}
693
694
/**
695
* Compares this object against the specified object.
696
* The result is {@code true} if and only if the argument is
697
* not {@code null} and it represents the same IP address as
698
* this object.
699
* <p>
700
* Two instances of {@code InetAddress} represent the same IP
701
* address if the length of the byte arrays returned by
702
* {@code getAddress} is the same for both, and each of the
703
* array components is the same for the byte arrays.
704
*
705
* @param obj the object to compare against.
706
* @return {@code true} if the objects are the same;
707
* {@code false} otherwise.
708
* @see java.net.InetAddress#getAddress()
709
*/
710
public boolean equals(Object obj) {
711
return false;
712
}
713
714
/**
715
* Converts this IP address to a {@code String}. The
716
* string returned is of the form: hostname / literal IP
717
* address.
718
*
719
* If the host name is unresolved, no reverse name service lookup
720
* is performed. The hostname part will be represented by an empty string.
721
*
722
* @return a string representation of this IP address.
723
*/
724
public String toString() {
725
String hostName = holder().getHostName();
726
return ((hostName != null) ? hostName : "")
727
+ "/" + getHostAddress();
728
}
729
730
/*
731
* Cached addresses - our own litle nis, not!
732
*/
733
private static Cache addressCache = new Cache(Cache.Type.Positive);
734
735
private static Cache negativeCache = new Cache(Cache.Type.Negative);
736
737
private static boolean addressCacheInit = false;
738
739
static InetAddress[] unknown_array; // put THIS in cache
740
741
static InetAddressImpl impl;
742
743
private static final HashMap<String, Void> lookupTable = new HashMap<>();
744
745
/**
746
* Represents a cache entry
747
*/
748
static final class CacheEntry {
749
750
CacheEntry(InetAddress[] addresses, long expiration) {
751
this.addresses = addresses;
752
this.expiration = expiration;
753
}
754
755
InetAddress[] addresses;
756
long expiration;
757
}
758
759
/**
760
* A cache that manages entries based on a policy specified
761
* at creation time.
762
*/
763
static final class Cache {
764
private LinkedHashMap<String, CacheEntry> cache;
765
private Type type;
766
767
enum Type {Positive, Negative};
768
769
/**
770
* Create cache
771
*/
772
public Cache(Type type) {
773
this.type = type;
774
cache = new LinkedHashMap<String, CacheEntry>();
775
}
776
777
private int getPolicy() {
778
if (type == Type.Positive) {
779
return InetAddressCachePolicy.get();
780
} else {
781
return InetAddressCachePolicy.getNegative();
782
}
783
}
784
785
/**
786
* Add an entry to the cache. If there's already an
787
* entry then for this host then the entry will be
788
* replaced.
789
*/
790
public Cache put(String host, InetAddress[] addresses) {
791
int policy = getPolicy();
792
if (policy == InetAddressCachePolicy.NEVER) {
793
return this;
794
}
795
796
// purge any expired entries
797
798
if (policy != InetAddressCachePolicy.FOREVER) {
799
800
// As we iterate in insertion order we can
801
// terminate when a non-expired entry is found.
802
LinkedList<String> expired = new LinkedList<>();
803
long now = System.currentTimeMillis();
804
for (String key : cache.keySet()) {
805
CacheEntry entry = cache.get(key);
806
807
if (entry.expiration >= 0 && entry.expiration < now) {
808
expired.add(key);
809
} else {
810
break;
811
}
812
}
813
814
for (String key : expired) {
815
cache.remove(key);
816
}
817
}
818
819
// create new entry and add it to the cache
820
// -- as a HashMap replaces existing entries we
821
// don't need to explicitly check if there is
822
// already an entry for this host.
823
long expiration;
824
if (policy == InetAddressCachePolicy.FOREVER) {
825
expiration = -1;
826
} else {
827
expiration = System.currentTimeMillis() + (policy * 1000);
828
}
829
CacheEntry entry = new CacheEntry(addresses, expiration);
830
cache.put(host, entry);
831
return this;
832
}
833
834
/**
835
* Query the cache for the specific host. If found then
836
* return its CacheEntry, or null if not found.
837
*/
838
public CacheEntry get(String host) {
839
int policy = getPolicy();
840
if (policy == InetAddressCachePolicy.NEVER) {
841
return null;
842
}
843
CacheEntry entry = cache.get(host);
844
845
// check if entry has expired
846
if (entry != null && policy != InetAddressCachePolicy.FOREVER) {
847
if (entry.expiration >= 0 &&
848
entry.expiration < System.currentTimeMillis()) {
849
cache.remove(host);
850
entry = null;
851
}
852
}
853
854
return entry;
855
}
856
}
857
858
/*
859
* Initialize cache and insert anyLocalAddress into the
860
* unknown array with no expiry.
861
*/
862
private static void cacheInitIfNeeded() {
863
assert Thread.holdsLock(addressCache);
864
if (addressCacheInit) {
865
return;
866
}
867
unknown_array = new InetAddress[1];
868
unknown_array[0] = impl.anyLocalAddress();
869
870
addressCache.put(impl.anyLocalAddress().getHostName(),
871
unknown_array);
872
873
addressCacheInit = true;
874
}
875
876
/*
877
* Cache the given hostname and addresses.
878
*/
879
private static void cacheAddresses(String hostname,
880
InetAddress[] addresses,
881
boolean success) {
882
hostname = hostname.toLowerCase();
883
synchronized (addressCache) {
884
cacheInitIfNeeded();
885
if (success) {
886
addressCache.put(hostname, addresses);
887
} else {
888
negativeCache.put(hostname, addresses);
889
}
890
}
891
}
892
893
/*
894
* Lookup hostname in cache (positive & negative cache). If
895
* found return addresses, null if not found.
896
*/
897
private static InetAddress[] getCachedAddresses(String hostname) {
898
hostname = hostname.toLowerCase();
899
900
// search both positive & negative caches
901
902
synchronized (addressCache) {
903
cacheInitIfNeeded();
904
905
CacheEntry entry = addressCache.get(hostname);
906
if (entry == null) {
907
entry = negativeCache.get(hostname);
908
}
909
910
if (entry != null) {
911
return entry.addresses;
912
}
913
}
914
915
// not found
916
return null;
917
}
918
919
private static NameService createNSProvider(String provider) {
920
if (provider == null)
921
return null;
922
923
NameService nameService = null;
924
if (provider.equals("default")) {
925
// initialize the default name service
926
nameService = new NameService() {
927
public InetAddress[] lookupAllHostAddr(String host)
928
throws UnknownHostException {
929
return impl.lookupAllHostAddr(host);
930
}
931
public String getHostByAddr(byte[] addr)
932
throws UnknownHostException {
933
return impl.getHostByAddr(addr);
934
}
935
};
936
} else {
937
final String providerName = provider;
938
try {
939
nameService = java.security.AccessController.doPrivileged(
940
new java.security.PrivilegedExceptionAction<NameService>() {
941
public NameService run() {
942
Iterator<NameServiceDescriptor> itr =
943
ServiceLoader.load(NameServiceDescriptor.class)
944
.iterator();
945
while (itr.hasNext()) {
946
NameServiceDescriptor nsd = itr.next();
947
if (providerName.
948
equalsIgnoreCase(nsd.getType()+","
949
+nsd.getProviderName())) {
950
try {
951
return nsd.createNameService();
952
} catch (Exception e) {
953
e.printStackTrace();
954
System.err.println(
955
"Cannot create name service:"
956
+providerName+": " + e);
957
}
958
}
959
}
960
961
return null;
962
}
963
}
964
);
965
} catch (java.security.PrivilegedActionException e) {
966
}
967
}
968
969
return nameService;
970
}
971
972
static {
973
// create the impl
974
impl = InetAddressImplFactory.create();
975
976
// get name service if provided and requested
977
String provider = null;;
978
String propPrefix = "sun.net.spi.nameservice.provider.";
979
int n = 1;
980
nameServices = new ArrayList<NameService>();
981
provider = AccessController.doPrivileged(
982
new GetPropertyAction(propPrefix + n));
983
while (provider != null) {
984
NameService ns = createNSProvider(provider);
985
if (ns != null)
986
nameServices.add(ns);
987
988
n++;
989
provider = AccessController.doPrivileged(
990
new GetPropertyAction(propPrefix + n));
991
}
992
993
// if not designate any name services provider,
994
// create a default one
995
if (nameServices.size() == 0) {
996
NameService ns = createNSProvider("default");
997
nameServices.add(ns);
998
}
999
}
1000
1001
/**
1002
* Creates an InetAddress based on the provided host name and IP address.
1003
* No name service is checked for the validity of the address.
1004
*
1005
* <p> The host name can either be a machine name, such as
1006
* "{@code java.sun.com}", or a textual representation of its IP
1007
* address.
1008
* <p> No validity checking is done on the host name either.
1009
*
1010
* <p> If addr specifies an IPv4 address an instance of Inet4Address
1011
* will be returned; otherwise, an instance of Inet6Address
1012
* will be returned.
1013
*
1014
* <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1015
* must be 16 bytes long
1016
*
1017
* @param host the specified host
1018
* @param addr the raw IP address in network byte order
1019
* @return an InetAddress object created from the raw IP address.
1020
* @exception UnknownHostException if IP address is of illegal length
1021
* @since 1.4
1022
*/
1023
public static InetAddress getByAddress(String host, byte[] addr)
1024
throws UnknownHostException {
1025
if (host != null && host.length() > 0 && host.charAt(0) == '[') {
1026
if (host.charAt(host.length()-1) == ']') {
1027
host = host.substring(1, host.length() -1);
1028
}
1029
}
1030
if (addr != null) {
1031
if (addr.length == Inet4Address.INADDRSZ) {
1032
return new Inet4Address(host, addr);
1033
} else if (addr.length == Inet6Address.INADDRSZ) {
1034
byte[] newAddr
1035
= IPAddressUtil.convertFromIPv4MappedAddress(addr);
1036
if (newAddr != null) {
1037
return new Inet4Address(host, newAddr);
1038
} else {
1039
return new Inet6Address(host, addr);
1040
}
1041
}
1042
}
1043
throw new UnknownHostException("addr is of illegal length");
1044
}
1045
1046
1047
/**
1048
* Determines the IP address of a host, given the host's name.
1049
*
1050
* <p> The host name can either be a machine name, such as
1051
* "{@code java.sun.com}", or a textual representation of its
1052
* IP address. If a literal IP address is supplied, only the
1053
* validity of the address format is checked.
1054
*
1055
* <p> For {@code host} specified in literal IPv6 address,
1056
* either the form defined in RFC 2732 or the literal IPv6 address
1057
* format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
1058
* supported. See <a href="Inet6Address.html#scoped">here</a> for a description of IPv6
1059
* scoped addresses.
1060
*
1061
* <p> If the host is {@code null} then an {@code InetAddress}
1062
* representing an address of the loopback interface is returned.
1063
* See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
1064
* section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
1065
* section&nbsp;2.5.3. </p>
1066
*
1067
* @param host the specified host, or {@code null}.
1068
* @return an IP address for the given host name.
1069
* @exception UnknownHostException if no IP address for the
1070
* {@code host} could be found, or if a scope_id was specified
1071
* for a global IPv6 address.
1072
* @exception SecurityException if a security manager exists
1073
* and its checkConnect method doesn't allow the operation
1074
*/
1075
public static InetAddress getByName(String host)
1076
throws UnknownHostException {
1077
return InetAddress.getAllByName(host)[0];
1078
}
1079
1080
// called from deployment cache manager
1081
private static InetAddress getByName(String host, InetAddress reqAddr)
1082
throws UnknownHostException {
1083
return InetAddress.getAllByName(host, reqAddr)[0];
1084
}
1085
1086
/**
1087
* Given the name of a host, returns an array of its IP addresses,
1088
* based on the configured name service on the system.
1089
*
1090
* <p> The host name can either be a machine name, such as
1091
* "{@code java.sun.com}", or a textual representation of its IP
1092
* address. If a literal IP address is supplied, only the
1093
* validity of the address format is checked.
1094
*
1095
* <p> For {@code host} specified in <i>literal IPv6 address</i>,
1096
* either the form defined in RFC 2732 or the literal IPv6 address
1097
* format defined in RFC 2373 is accepted. A literal IPv6 address may
1098
* also be qualified by appending a scoped zone identifier or scope_id.
1099
* The syntax and usage of scope_ids is described
1100
* <a href="Inet6Address.html#scoped">here</a>.
1101
* <p> If the host is {@code null} then an {@code InetAddress}
1102
* representing an address of the loopback interface is returned.
1103
* See <a href="http://www.ietf.org/rfc/rfc3330.txt">RFC&nbsp;3330</a>
1104
* section&nbsp;2 and <a href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>
1105
* section&nbsp;2.5.3. </p>
1106
*
1107
* <p> If there is a security manager and {@code host} is not
1108
* null and {@code host.length() } is not equal to zero, the
1109
* security manager's
1110
* {@code checkConnect} method is called
1111
* with the hostname and {@code -1}
1112
* as its arguments to see if the operation is allowed.
1113
*
1114
* @param host the name of the host, or {@code null}.
1115
* @return an array of all the IP addresses for a given host name.
1116
*
1117
* @exception UnknownHostException if no IP address for the
1118
* {@code host} could be found, or if a scope_id was specified
1119
* for a global IPv6 address.
1120
* @exception SecurityException if a security manager exists and its
1121
* {@code checkConnect} method doesn't allow the operation.
1122
*
1123
* @see SecurityManager#checkConnect
1124
*/
1125
public static InetAddress[] getAllByName(String host)
1126
throws UnknownHostException {
1127
return getAllByName(host, null);
1128
}
1129
1130
private static InetAddress[] getAllByName(String host, InetAddress reqAddr)
1131
throws UnknownHostException {
1132
1133
if (host == null || host.length() == 0) {
1134
InetAddress[] ret = new InetAddress[1];
1135
ret[0] = impl.loopbackAddress();
1136
return ret;
1137
}
1138
1139
boolean ipv6Expected = false;
1140
if (host.charAt(0) == '[') {
1141
// This is supposed to be an IPv6 literal
1142
if (host.length() > 2 && host.charAt(host.length()-1) == ']') {
1143
host = host.substring(1, host.length() -1);
1144
ipv6Expected = true;
1145
} else {
1146
// This was supposed to be a IPv6 address, but it's not!
1147
throw new UnknownHostException(host + ": invalid IPv6 address");
1148
}
1149
}
1150
1151
// if host is an IP address, we won't do further lookup
1152
if (Character.digit(host.charAt(0), 16) != -1
1153
|| (host.charAt(0) == ':')) {
1154
byte[] addr = null;
1155
int numericZone = -1;
1156
String ifname = null;
1157
// see if it is IPv4 address
1158
addr = IPAddressUtil.textToNumericFormatV4(host);
1159
if (addr == null) {
1160
// This is supposed to be an IPv6 literal
1161
// Check if a numeric or string zone id is present
1162
int pos;
1163
if ((pos=host.indexOf ("%")) != -1) {
1164
numericZone = checkNumericZone (host);
1165
if (numericZone == -1) { /* remainder of string must be an ifname */
1166
ifname = host.substring (pos+1);
1167
}
1168
}
1169
if ((addr = IPAddressUtil.textToNumericFormatV6(host)) == null && host.contains(":")) {
1170
throw new UnknownHostException(host + ": invalid IPv6 address");
1171
}
1172
} else if (ipv6Expected) {
1173
// Means an IPv4 litteral between brackets!
1174
throw new UnknownHostException("["+host+"]");
1175
}
1176
InetAddress[] ret = new InetAddress[1];
1177
if(addr != null) {
1178
if (addr.length == Inet4Address.INADDRSZ) {
1179
ret[0] = new Inet4Address(null, addr);
1180
} else {
1181
if (ifname != null) {
1182
ret[0] = new Inet6Address(null, addr, ifname);
1183
} else {
1184
ret[0] = new Inet6Address(null, addr, numericZone);
1185
}
1186
}
1187
return ret;
1188
}
1189
} else if (ipv6Expected) {
1190
// We were expecting an IPv6 Litteral, but got something else
1191
throw new UnknownHostException("["+host+"]");
1192
}
1193
return getAllByName0(host, reqAddr, true);
1194
}
1195
1196
/**
1197
* Returns the loopback address.
1198
* <p>
1199
* The InetAddress returned will represent the IPv4
1200
* loopback address, 127.0.0.1, or the IPv6 loopback
1201
* address, ::1. The IPv4 loopback address returned
1202
* is only one of many in the form 127.*.*.*
1203
*
1204
* @return the InetAddress loopback instance.
1205
* @since 1.7
1206
*/
1207
public static InetAddress getLoopbackAddress() {
1208
return impl.loopbackAddress();
1209
}
1210
1211
1212
/**
1213
* check if the literal address string has %nn appended
1214
* returns -1 if not, or the numeric value otherwise.
1215
*
1216
* %nn may also be a string that represents the displayName of
1217
* a currently available NetworkInterface.
1218
*/
1219
private static int checkNumericZone (String s) throws UnknownHostException {
1220
int percent = s.indexOf ('%');
1221
int slen = s.length();
1222
int digit, zone=0;
1223
if (percent == -1) {
1224
return -1;
1225
}
1226
for (int i=percent+1; i<slen; i++) {
1227
char c = s.charAt(i);
1228
if (c == ']') {
1229
if (i == percent+1) {
1230
/* empty per-cent field */
1231
return -1;
1232
}
1233
break;
1234
}
1235
if ((digit = Character.digit (c, 10)) < 0) {
1236
return -1;
1237
}
1238
zone = (zone * 10) + digit;
1239
}
1240
return zone;
1241
}
1242
1243
private static InetAddress[] getAllByName0 (String host)
1244
throws UnknownHostException
1245
{
1246
return getAllByName0(host, true);
1247
}
1248
1249
/**
1250
* package private so SocketPermission can call it
1251
*/
1252
static InetAddress[] getAllByName0 (String host, boolean check)
1253
throws UnknownHostException {
1254
return getAllByName0 (host, null, check);
1255
}
1256
1257
private static InetAddress[] getAllByName0 (String host, InetAddress reqAddr, boolean check)
1258
throws UnknownHostException {
1259
1260
/* If it gets here it is presumed to be a hostname */
1261
/* Cache.get can return: null, unknownAddress, or InetAddress[] */
1262
1263
/* make sure the connection to the host is allowed, before we
1264
* give out a hostname
1265
*/
1266
if (check) {
1267
SecurityManager security = System.getSecurityManager();
1268
if (security != null) {
1269
security.checkConnect(host, -1);
1270
}
1271
}
1272
1273
InetAddress[] addresses = getCachedAddresses(host);
1274
1275
/* If no entry in cache, then do the host lookup */
1276
if (addresses == null) {
1277
addresses = getAddressesFromNameService(host, reqAddr);
1278
}
1279
1280
if (addresses == unknown_array)
1281
throw new UnknownHostException(host);
1282
1283
return addresses.clone();
1284
}
1285
1286
private static InetAddress[] getAddressesFromNameService(String host, InetAddress reqAddr)
1287
throws UnknownHostException
1288
{
1289
InetAddress[] addresses = null;
1290
boolean success = false;
1291
UnknownHostException ex = null;
1292
1293
// Check whether the host is in the lookupTable.
1294
// 1) If the host isn't in the lookupTable when
1295
// checkLookupTable() is called, checkLookupTable()
1296
// would add the host in the lookupTable and
1297
// return null. So we will do the lookup.
1298
// 2) If the host is in the lookupTable when
1299
// checkLookupTable() is called, the current thread
1300
// would be blocked until the host is removed
1301
// from the lookupTable. Then this thread
1302
// should try to look up the addressCache.
1303
// i) if it found the addresses in the
1304
// addressCache, checkLookupTable() would
1305
// return the addresses.
1306
// ii) if it didn't find the addresses in the
1307
// addressCache for any reason,
1308
// it should add the host in the
1309
// lookupTable and return null so the
1310
// following code would do a lookup itself.
1311
if ((addresses = checkLookupTable(host)) == null) {
1312
try {
1313
// This is the first thread which looks up the addresses
1314
// this host or the cache entry for this host has been
1315
// expired so this thread should do the lookup.
1316
for (NameService nameService : nameServices) {
1317
try {
1318
/*
1319
* Do not put the call to lookup() inside the
1320
* constructor. if you do you will still be
1321
* allocating space when the lookup fails.
1322
*/
1323
1324
addresses = nameService.lookupAllHostAddr(host);
1325
success = true;
1326
break;
1327
} catch (UnknownHostException uhe) {
1328
if (host.equalsIgnoreCase("localhost")) {
1329
InetAddress[] local = new InetAddress[] { impl.loopbackAddress() };
1330
addresses = local;
1331
success = true;
1332
break;
1333
}
1334
else {
1335
addresses = unknown_array;
1336
success = false;
1337
ex = uhe;
1338
}
1339
}
1340
}
1341
1342
// More to do?
1343
if (reqAddr != null && addresses.length > 1 && !addresses[0].equals(reqAddr)) {
1344
// Find it?
1345
int i = 1;
1346
for (; i < addresses.length; i++) {
1347
if (addresses[i].equals(reqAddr)) {
1348
break;
1349
}
1350
}
1351
// Rotate
1352
if (i < addresses.length) {
1353
InetAddress tmp, tmp2 = reqAddr;
1354
for (int j = 0; j < i; j++) {
1355
tmp = addresses[j];
1356
addresses[j] = tmp2;
1357
tmp2 = tmp;
1358
}
1359
addresses[i] = tmp2;
1360
}
1361
}
1362
// Cache the address.
1363
cacheAddresses(host, addresses, success);
1364
1365
if (!success && ex != null)
1366
throw ex;
1367
1368
} finally {
1369
// Delete host from the lookupTable and notify
1370
// all threads waiting on the lookupTable monitor.
1371
updateLookupTable(host);
1372
}
1373
}
1374
1375
return addresses;
1376
}
1377
1378
1379
private static InetAddress[] checkLookupTable(String host) {
1380
synchronized (lookupTable) {
1381
// If the host isn't in the lookupTable, add it in the
1382
// lookuptable and return null. The caller should do
1383
// the lookup.
1384
if (lookupTable.containsKey(host) == false) {
1385
lookupTable.put(host, null);
1386
return null;
1387
}
1388
1389
// If the host is in the lookupTable, it means that another
1390
// thread is trying to look up the addresses of this host.
1391
// This thread should wait.
1392
while (lookupTable.containsKey(host)) {
1393
try {
1394
lookupTable.wait();
1395
} catch (InterruptedException e) {
1396
}
1397
}
1398
}
1399
1400
// The other thread has finished looking up the addresses of
1401
// the host. This thread should retry to get the addresses
1402
// from the addressCache. If it doesn't get the addresses from
1403
// the cache, it will try to look up the addresses itself.
1404
InetAddress[] addresses = getCachedAddresses(host);
1405
if (addresses == null) {
1406
synchronized (lookupTable) {
1407
lookupTable.put(host, null);
1408
return null;
1409
}
1410
}
1411
1412
return addresses;
1413
}
1414
1415
private static void updateLookupTable(String host) {
1416
synchronized (lookupTable) {
1417
lookupTable.remove(host);
1418
lookupTable.notifyAll();
1419
}
1420
}
1421
1422
/**
1423
* Returns an {@code InetAddress} object given the raw IP address .
1424
* The argument is in network byte order: the highest order
1425
* byte of the address is in {@code getAddress()[0]}.
1426
*
1427
* <p> This method doesn't block, i.e. no reverse name service lookup
1428
* is performed.
1429
*
1430
* <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array
1431
* must be 16 bytes long
1432
*
1433
* @param addr the raw IP address in network byte order
1434
* @return an InetAddress object created from the raw IP address.
1435
* @exception UnknownHostException if IP address is of illegal length
1436
* @since 1.4
1437
*/
1438
public static InetAddress getByAddress(byte[] addr)
1439
throws UnknownHostException {
1440
return getByAddress(null, addr);
1441
}
1442
1443
private static InetAddress cachedLocalHost = null;
1444
private static long cacheTime = 0;
1445
private static final long maxCacheTime = 5000L;
1446
private static final Object cacheLock = new Object();
1447
1448
/**
1449
* Returns the address of the local host. This is achieved by retrieving
1450
* the name of the host from the system, then resolving that name into
1451
* an {@code InetAddress}.
1452
*
1453
* <P>Note: The resolved address may be cached for a short period of time.
1454
* </P>
1455
*
1456
* <p>If there is a security manager, its
1457
* {@code checkConnect} method is called
1458
* with the local host name and {@code -1}
1459
* as its arguments to see if the operation is allowed.
1460
* If the operation is not allowed, an InetAddress representing
1461
* the loopback address is returned.
1462
*
1463
* @return the address of the local host.
1464
*
1465
* @exception UnknownHostException if the local host name could not
1466
* be resolved into an address.
1467
*
1468
* @see SecurityManager#checkConnect
1469
* @see java.net.InetAddress#getByName(java.lang.String)
1470
*/
1471
public static InetAddress getLocalHost() throws UnknownHostException {
1472
1473
SecurityManager security = System.getSecurityManager();
1474
try {
1475
String local = impl.getLocalHostName();
1476
1477
if (security != null) {
1478
security.checkConnect(local, -1);
1479
}
1480
1481
if (local.equals("localhost")) {
1482
return impl.loopbackAddress();
1483
}
1484
1485
InetAddress ret = null;
1486
synchronized (cacheLock) {
1487
long now = System.currentTimeMillis();
1488
if (cachedLocalHost != null) {
1489
if ((now - cacheTime) < maxCacheTime) // Less than 5s old?
1490
ret = cachedLocalHost;
1491
else
1492
cachedLocalHost = null;
1493
}
1494
1495
// we are calling getAddressesFromNameService directly
1496
// to avoid getting localHost from cache
1497
if (ret == null) {
1498
InetAddress[] localAddrs;
1499
try {
1500
localAddrs =
1501
InetAddress.getAddressesFromNameService(local, null);
1502
} catch (UnknownHostException uhe) {
1503
// Rethrow with a more informative error message.
1504
UnknownHostException uhe2 =
1505
new UnknownHostException(local + ": " +
1506
uhe.getMessage());
1507
uhe2.initCause(uhe);
1508
throw uhe2;
1509
}
1510
cachedLocalHost = localAddrs[0];
1511
cacheTime = now;
1512
ret = localAddrs[0];
1513
}
1514
}
1515
return ret;
1516
} catch (java.lang.SecurityException e) {
1517
return impl.loopbackAddress();
1518
}
1519
}
1520
1521
/**
1522
* Perform class load-time initializations.
1523
*/
1524
private static native void init();
1525
1526
1527
/*
1528
* Returns the InetAddress representing anyLocalAddress
1529
* (typically 0.0.0.0 or ::0)
1530
*/
1531
static InetAddress anyLocalAddress() {
1532
return impl.anyLocalAddress();
1533
}
1534
1535
/*
1536
* Load and instantiate an underlying impl class
1537
*/
1538
static InetAddressImpl loadImpl(String implName) {
1539
Object impl = null;
1540
1541
/*
1542
* Property "impl.prefix" will be prepended to the classname
1543
* of the implementation object we instantiate, to which we
1544
* delegate the real work (like native methods). This
1545
* property can vary across implementations of the java.
1546
* classes. The default is an empty String "".
1547
*/
1548
String prefix = AccessController.doPrivileged(
1549
new GetPropertyAction("impl.prefix", ""));
1550
try {
1551
impl = Class.forName("java.net." + prefix + implName).newInstance();
1552
} catch (ClassNotFoundException e) {
1553
System.err.println("Class not found: java.net." + prefix +
1554
implName + ":\ncheck impl.prefix property " +
1555
"in your properties file.");
1556
} catch (InstantiationException e) {
1557
System.err.println("Could not instantiate: java.net." + prefix +
1558
implName + ":\ncheck impl.prefix property " +
1559
"in your properties file.");
1560
} catch (IllegalAccessException e) {
1561
System.err.println("Cannot access class: java.net." + prefix +
1562
implName + ":\ncheck impl.prefix property " +
1563
"in your properties file.");
1564
}
1565
1566
if (impl == null) {
1567
try {
1568
impl = Class.forName(implName).newInstance();
1569
} catch (Exception e) {
1570
throw new Error("System property impl.prefix incorrect");
1571
}
1572
}
1573
1574
return (InetAddressImpl) impl;
1575
}
1576
1577
private void readObjectNoData (ObjectInputStream s) throws
1578
IOException, ClassNotFoundException {
1579
if (getClass().getClassLoader() != null) {
1580
throw new SecurityException ("invalid address type");
1581
}
1582
}
1583
1584
private static final long FIELDS_OFFSET;
1585
private static final sun.misc.Unsafe UNSAFE;
1586
1587
static {
1588
try {
1589
sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
1590
FIELDS_OFFSET = unsafe.objectFieldOffset(
1591
InetAddress.class.getDeclaredField("holder")
1592
);
1593
UNSAFE = unsafe;
1594
} catch (ReflectiveOperationException e) {
1595
throw new Error(e);
1596
}
1597
}
1598
1599
private void readObject (ObjectInputStream s) throws
1600
IOException, ClassNotFoundException {
1601
if (getClass().getClassLoader() != null) {
1602
throw new SecurityException ("invalid address type");
1603
}
1604
GetField gf = s.readFields();
1605
String host = (String)gf.get("hostName", null);
1606
int address = gf.get("address", 0);
1607
int family = gf.get("family", 0);
1608
if (family != IPv4 && family != IPv6) {
1609
throw new InvalidObjectException("invalid address family type: " + family);
1610
}
1611
InetAddressHolder h = new InetAddressHolder(host, address, family);
1612
UNSAFE.putObject(this, FIELDS_OFFSET, h);
1613
}
1614
1615
/* needed because the serializable fields no longer exist */
1616
1617
/**
1618
* @serialField hostName String
1619
* @serialField address int
1620
* @serialField family int
1621
*/
1622
private static final ObjectStreamField[] serialPersistentFields = {
1623
new ObjectStreamField("hostName", String.class),
1624
new ObjectStreamField("address", int.class),
1625
new ObjectStreamField("family", int.class),
1626
};
1627
1628
private void writeObject (ObjectOutputStream s) throws
1629
IOException {
1630
if (getClass().getClassLoader() != null) {
1631
throw new SecurityException ("invalid address type");
1632
}
1633
PutField pf = s.putFields();
1634
pf.put("hostName", holder().getHostName());
1635
pf.put("address", holder().getAddress());
1636
pf.put("family", holder().getFamily());
1637
s.writeFields();
1638
}
1639
}
1640
1641
/*
1642
* Simple factory to create the impl
1643
*/
1644
class InetAddressImplFactory {
1645
1646
static InetAddressImpl create() {
1647
return InetAddress.loadImpl(isIPv6Supported() ?
1648
"Inet6AddressImpl" : "Inet4AddressImpl");
1649
}
1650
1651
static native boolean isIPv6Supported();
1652
}
1653
1654