Methods Summary |
---|
static java.net.InetAddress | anyLocalAddress()
return impl.anyLocalAddress();
|
private static void | cacheAddress(java.lang.String hostname, java.lang.Object address, boolean success)
hostname = hostname.toLowerCase();
synchronized (addressCache) {
cacheInitIfNeeded();
if (success) {
addressCache.put(hostname, address);
} else {
negativeCache.put(hostname, address);
}
}
|
private static void | cacheInitIfNeeded()
assert Thread.holdsLock(addressCache);
if (addressCacheInit) {
return;
}
unknown_array = new InetAddress[1];
unknown_array[0] = impl.anyLocalAddress();
addressCache.put(impl.anyLocalAddress().getHostName(),
unknown_array);
addressCacheInit = true;
|
private static java.lang.Object | checkLookupTable(java.lang.String host)
// make sure obj is null.
Object obj = null;
synchronized (lookupTable) {
// If the host isn't in the lookupTable, add it in the
// lookuptable and return null. The caller should do
// the lookup.
if (lookupTable.containsKey(host) == false) {
lookupTable.put(host, null);
return obj;
}
// If the host is in the lookupTable, it means that another
// thread is trying to look up the address of this host.
// This thread should wait.
while (lookupTable.containsKey(host)) {
try {
lookupTable.wait();
} catch (InterruptedException e) {
}
}
}
// The other thread has finished looking up the address of
// the host. This thread should retry to get the address
// from the addressCache. If it doesn't get the address from
// the cache, it will try to look up the address itself.
obj = getCachedAddress(host);
if (obj == null) {
synchronized (lookupTable) {
lookupTable.put(host, null);
}
}
return obj;
|
private static int | checkNumericZone(java.lang.String s)check if the literal address string has %nn appended
returns -1 if not, or the numeric value otherwise.
%nn may also be a string that represents the displayName of
a currently available NetworkInterface.
int percent = s.indexOf ('%");
int slen = s.length();
int digit, zone=0;
if (percent == -1) {
return -1;
}
for (int i=percent+1; i<slen; i++) {
char c = s.charAt(i);
if (c == ']") {
if (i == percent+1) {
/* empty per-cent field */
return -1;
}
break;
}
if ((digit = Character.digit (c, 10)) < 0) {
return -1;
}
zone = (zone * 10) + digit;
}
return zone;
|
public boolean | equals(java.lang.Object obj)Compares this object against the specified object.
The result is true if and only if the argument is
not null and it represents the same IP address as
this object.
Two instances of InetAddress represent the same IP
address if the length of the byte arrays returned by
getAddress is the same for both, and each of the
array components is the same for the byte arrays.
return false;
|
public byte[] | getAddress()Returns the raw IP address of this InetAddress
object. The result is in network byte order: the highest order
byte of the address is in getAddress()[0] .
return null;
|
private static java.lang.Object | getAddressFromNameService(java.lang.String host)
Object obj = null;
boolean success = false;
// Check whether the host is in the lookupTable.
// 1) If the host isn't in the lookupTable when
// checkLookupTable() is called, checkLookupTable()
// would add the host in the lookupTable and
// return null. So we will do the lookup.
// 2) If the host is in the lookupTable when
// checkLookupTable() is called, the current thread
// would be blocked until the host is removed
// from the lookupTable. Then this thread
// should try to look up the addressCache.
// i) if it found the address in the
// addressCache, checkLookupTable() would
// return the address.
// ii) if it didn't find the address in the
// addressCache for any reason,
// it should add the host in the
// lookupTable and return null so the
// following code would do a lookup itself.
if ((obj = checkLookupTable(host)) == null) {
// This is the first thread which looks up the address
// this host or the cache entry for this host has been
// expired so this thread should do the lookup.
try {
/*
* Do not put the call to lookup() inside the
* constructor. if you do you will still be
* allocating space when the lookup fails.
*/
byte[][] byte_array;
byte_array = nameService.lookupAllHostAddr(host);
InetAddress[] addr_array =
new InetAddress[byte_array.length];
for (int i = 0; i < byte_array.length; i++) {
byte addr[] = byte_array[i];
if (addr.length == Inet4Address.INADDRSZ) {
addr_array[i] = new Inet4Address(host, addr);
} else {
addr_array[i] = new Inet6Address(host, addr, -1);
}
}
obj = addr_array;
success = true;
} catch (UnknownHostException uhe) {
obj = unknown_array;
success = false;
throw uhe;
} finally {
// Cache the address.
cacheAddress(host, obj, success);
// Delete the host from the lookupTable, and
// notify all threads waiting for the monitor
// for lookupTable.
updateLookupTable(host);
}
}
return obj;
|
public static java.net.InetAddress[] | getAllByName(java.lang.String host)Given the name of a host, returns an array of its IP addresses,
based on the configured name service on the system.
The host name can either be a machine name, such as
"java.sun.com ", or a textual representation of its IP
address. If a literal IP address is supplied, only the
validity of the address format is checked.
For host specified in literal IPv6 address,
either the form defined in RFC 2732 or the literal IPv6 address
format defined in RFC 2373 is accepted. A literal IPv6 address may
also be qualified by appending a scoped zone identifier or scope_id.
The syntax and usage of scope_ids is described
here.
If the host is null then an InetAddress
representing an address of the loopback interface is returned.
See RFC 3330
section 2 and RFC 2373
section 2.5.3.
If there is a security manager and host is not
null and host.length() is not equal to zero, the
security manager's
checkConnect method is called
with the hostname and -1
as its arguments to see if the operation is allowed.
if (host == null || host.length() == 0) {
InetAddress[] ret = new InetAddress[1];
ret[0] = impl.loopbackAddress();
return ret;
}
boolean ipv6Expected = false;
if (host.charAt(0) == '[") {
// This is supposed to be an IPv6 litteral
if (host.length() > 2 && host.charAt(host.length()-1) == ']") {
host = host.substring(1, host.length() -1);
ipv6Expected = true;
} else {
// This was supposed to be a IPv6 address, but it's not!
throw new UnknownHostException(host);
}
}
// if host is an IP address, we won't do further lookup
if (Character.digit(host.charAt(0), 16) != -1
|| (host.charAt(0) == ':")) {
byte[] addr = null;
int numericZone = -1;
String ifname = null;
// see if it is IPv4 address
addr = IPAddressUtil.textToNumericFormatV4(host);
if (addr == null) {
// see if it is IPv6 address
// Check if a numeric or string zone id is present
int pos;
if ((pos=host.indexOf ("%")) != -1) {
numericZone = checkNumericZone (host);
if (numericZone == -1) { /* remainder of string must be an ifname */
ifname = host.substring (pos+1);
}
}
addr = IPAddressUtil.textToNumericFormatV6(host);
} else if (ipv6Expected) {
// Means an IPv4 litteral between brackets!
throw new UnknownHostException("["+host+"]");
}
InetAddress[] ret = new InetAddress[1];
if(addr != null) {
if (addr.length == Inet4Address.INADDRSZ) {
ret[0] = new Inet4Address(null, addr);
} else {
if (ifname != null) {
ret[0] = new Inet6Address(null, addr, ifname);
} else {
ret[0] = new Inet6Address(null, addr, numericZone);
}
}
return ret;
}
} else if (ipv6Expected) {
// We were expecting an IPv6 Litteral, but got something else
throw new UnknownHostException("["+host+"]");
}
return getAllByName0(host);
|
private static java.net.InetAddress[] | getAllByName0(java.lang.String host)
return getAllByName0(host, true);
|
static java.net.InetAddress[] | getAllByName0(java.lang.String host, boolean check)package private so SocketPermission can call it
/* If it gets here it is presumed to be a hostname */
/* Cache.get can return: null, unknownAddress, or InetAddress[] */
Object obj = null;
Object objcopy = null;
/* make sure the connection to the host is allowed, before we
* give out a hostname
*/
if (check) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkConnect(host, -1);
}
}
obj = getCachedAddress(host);
/* If no entry in cache, then do the host lookup */
if (obj == null) {
try {
obj = getAddressFromNameService(host);
} catch (UnknownHostException uhe) {
throw new UnknownHostException(host + ": " + uhe.getMessage());
}
}
if (obj == unknown_array)
throw new UnknownHostException(host);
/* Make a copy of the InetAddress array */
objcopy = ((InetAddress [])obj).clone();
return (InetAddress [])objcopy;
|
public static java.net.InetAddress | getByAddress(java.lang.String host, byte[] addr)Create an InetAddress based on the provided host name and IP address
No name service is checked for the validity of the address.
The host name can either be a machine name, such as
"java.sun.com ", or a textual representation of its IP
address.
No validity checking is done on the host name either.
If addr specifies an IPv4 address an instance of Inet4Address
will be returned; otherwise, an instance of Inet6Address
will be returned.
IPv4 address byte array must be 4 bytes long and IPv6 byte array
must be 16 bytes long
// create the impl
impl = (new InetAddressImplFactory()).create();
// get name service if provided and requested
String provider = null;;
String propPrefix = "sun.net.spi.nameservice.provider.";
int n = 1;
while (nameService == null) {
provider
= (String)AccessController.doPrivileged(
new GetPropertyAction(propPrefix+n, "default"));
n++;
if (provider.equals("default")) {
// initialize the default name service
nameService = new NameService() {
public byte[][] lookupAllHostAddr(String host)
throws UnknownHostException {
return impl.lookupAllHostAddr(host);
}
public String getHostByAddr(byte[] addr)
throws UnknownHostException {
return impl.getHostByAddr(addr);
}
};
break;
}
final String providerName = provider;
try {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction() {
public Object run() {
Iterator itr
= Service.providers(NameServiceDescriptor.class);
while (itr.hasNext()) {
NameServiceDescriptor nsd
= (NameServiceDescriptor)itr.next();
if (providerName.
equalsIgnoreCase(nsd.getType()+","
+nsd.getProviderName())) {
try {
nameService = nsd.createNameService();
break;
} catch (Exception e) {
e.printStackTrace();
System.err.println(
"Cannot create name service:"
+providerName+": " + e);
}
}
} /* while */
return null;
}
});
} catch (java.security.PrivilegedActionException e) {
}
}
if (host != null && host.length() > 0 && host.charAt(0) == '[") {
if (host.charAt(host.length()-1) == ']") {
host = host.substring(1, host.length() -1);
}
}
if (addr != null) {
if (addr.length == Inet4Address.INADDRSZ) {
return new Inet4Address(host, addr);
} else if (addr.length == Inet6Address.INADDRSZ) {
byte[] newAddr
= IPAddressUtil.convertFromIPv4MappedAddress(addr);
if (newAddr != null) {
return new Inet4Address(host, newAddr);
} else {
return new Inet6Address(host, addr);
}
}
}
throw new UnknownHostException("addr is of illegal length");
|
public static java.net.InetAddress | getByAddress(byte[] addr)Returns an InetAddress object given the raw IP address .
The argument is in network byte order: the highest order
byte of the address is in getAddress()[0] .
This method doesn't block, i.e. no reverse name service lookup
is performed.
IPv4 address byte array must be 4 bytes long and IPv6 byte array
must be 16 bytes long
return getByAddress(null, addr);
|
public static java.net.InetAddress | getByName(java.lang.String host)Determines the IP address of a host, given the host's name.
The host name can either be a machine name, such as
"java.sun.com ", or a textual representation of its
IP address. If a literal IP address is supplied, only the
validity of the address format is checked.
For host specified in literal IPv6 address,
either the form defined in RFC 2732 or the literal IPv6 address
format defined in RFC 2373 is accepted. IPv6 scoped addresses are also
supported. See here for a description of IPv6
scoped addresses.
If the host is null then an InetAddress
representing an address of the loopback interface is returned.
See RFC 3330
section 2 and RFC 2373
section 2.5.3.
return InetAddress.getAllByName(host)[0];
|
private static java.lang.Object | getCachedAddress(java.lang.String hostname)
hostname = hostname.toLowerCase();
// search both positive & negative caches
synchronized (addressCache) {
CacheEntry entry;
cacheInitIfNeeded();
entry = (CacheEntry)addressCache.get(hostname);
if (entry == null) {
entry = (CacheEntry)negativeCache.get(hostname);
}
if (entry != null) {
return entry.address;
}
}
// not found
return null;
|
public java.lang.String | getCanonicalHostName()Gets the fully qualified domain name for this IP address.
Best effort method, meaning we may not be able to return
the FQDN depending on the underlying system configuration.
If there is a security manager, this method first
calls its checkConnect method
with the hostname and -1
as its arguments to see if the calling code is allowed to know
the hostname for this IP address, i.e., to connect to the host.
If the operation is not allowed, it will return
the textual representation of the IP address.
if (canonicalHostName == null) {
canonicalHostName =
InetAddress.getHostFromNameService(this, true);
}
return canonicalHostName;
|
public java.lang.String | getHostAddress()Returns the IP address string in textual presentation.
return null;
|
private static java.lang.String | getHostFromNameService(java.net.InetAddress addr, boolean check)Returns the hostname for this address.
If there is a security manager, this method first
calls its checkConnect method
with the hostname and -1
as its arguments to see if the calling code is allowed to know
the hostname for this IP address, i.e., to connect to the host.
If the operation is not allowed, it will return
the textual representation of the IP address.
String host;
try {
// first lookup the hostname
host = nameService.getHostByAddr(addr.getAddress());
/* check to see if calling code is allowed to know
* the hostname for this IP address, ie, connect to the host
*/
if (check) {
SecurityManager sec = System.getSecurityManager();
if (sec != null) {
sec.checkConnect(host, -1);
}
}
/* now get all the IP addresses for this hostname,
* and make sure one of them matches the original IP
* address. We do this to try and prevent spoofing.
*/
InetAddress[] arr = InetAddress.getAllByName0(host, check);
boolean ok = false;
if(arr != null) {
for(int i = 0; !ok && i < arr.length; i++) {
ok = addr.equals(arr[i]);
}
}
//XXX: if it looks a spoof just return the address?
if (!ok) {
host = addr.getHostAddress();
return host;
}
} catch (SecurityException e) {
host = addr.getHostAddress();
} catch (UnknownHostException e) {
host = addr.getHostAddress();
}
return host;
|
public java.lang.String | getHostName()Gets the host name for this IP address.
If this InetAddress was created with a host name,
this host name will be remembered and returned;
otherwise, a reverse name lookup will be performed
and the result will be returned based on the system
configured name lookup service. If a lookup of the name service
is required, call
{@link #getCanonicalHostName() getCanonicalHostName}.
If there is a security manager, its
checkConnect method is first called
with the hostname and -1
as its arguments to see if the operation is allowed.
If the operation is not allowed, it will return
the textual representation of the IP address.
return getHostName(true);
|
java.lang.String | getHostName(boolean check)Returns the hostname for this address.
If the host is equal to null, then this address refers to any
of the local machine's available network addresses.
this is package private so SocketPermission can make calls into
here without a security check.
If there is a security manager, this method first
calls its checkConnect method
with the hostname and -1
as its arguments to see if the calling code is allowed to know
the hostname for this IP address, i.e., to connect to the host.
If the operation is not allowed, it will return
the textual representation of the IP address.
if (hostName == null) {
hostName = InetAddress.getHostFromNameService(this, check);
}
return hostName;
|
public static java.net.InetAddress | getLocalHost()Returns the local host.
If there is a security manager, its
checkConnect method is called
with the local host name and -1
as its arguments to see if the operation is allowed.
If the operation is not allowed, an InetAddress representing
the loopback address is returned.
SecurityManager security = System.getSecurityManager();
try {
String local = impl.getLocalHostName();
if (security != null) {
security.checkConnect(local, -1);
}
// we are calling getAddressFromNameService directly
// to avoid getting localHost from cache
InetAddress[] localAddrs;
try {
localAddrs =
(InetAddress[]) InetAddress.getAddressFromNameService(local);
} catch (UnknownHostException uhe) {
throw new UnknownHostException(local + ": " + uhe.getMessage());
}
return localAddrs[0];
} catch (java.lang.SecurityException e) {
return impl.loopbackAddress();
}
|
public int | hashCode()Returns a hashcode for this IP address.
return -1;
|
private static native void | init()Perform class load-time initializations.
|
public boolean | isAnyLocalAddress()Utility routine to check if the InetAddress in a wildcard address.
return false;
|
public boolean | isLinkLocalAddress()Utility routine to check if the InetAddress is an link local address.
return false;
|
public boolean | isLoopbackAddress()Utility routine to check if the InetAddress is a loopback address.
return false;
|
public boolean | isMCGlobal()Utility routine to check if the multicast address has global scope.
return false;
|
public boolean | isMCLinkLocal()Utility routine to check if the multicast address has link scope.
return false;
|
public boolean | isMCNodeLocal()Utility routine to check if the multicast address has node scope.
return false;
|
public boolean | isMCOrgLocal()Utility routine to check if the multicast address has organization scope.
return false;
|
public boolean | isMCSiteLocal()Utility routine to check if the multicast address has site scope.
return false;
|
public boolean | isMulticastAddress()Utility routine to check if the InetAddress is an
IP multicast address.
return false;
|
public boolean | isReachable(int timeout)Test whether that address is reachable. Best effort is made by the
implementation to try to reach the host, but firewalls and server
configuration may block requests resulting in a unreachable status
while some specific ports may be accessible.
A typical implementation will use ICMP ECHO REQUESTs if the
privilege can be obtained, otherwise it will try to establish
a TCP connection on port 7 (Echo) of the destination host.
The timeout value, in milliseconds, indicates the maximum amount of time
the try should take. If the operation times out before getting an
answer, the host is deemed unreachable. A negative value will result
in an IllegalArgumentException being thrown.
return isReachable(null, 0 , timeout);
|
public boolean | isReachable(java.net.NetworkInterface netif, int ttl, int timeout)Test whether that address is reachable. Best effort is made by the
implementation to try to reach the host, but firewalls and server
configuration may block requests resulting in a unreachable status
while some specific ports may be accessible.
A typical implementation will use ICMP ECHO REQUESTs if the
privilege can be obtained, otherwise it will try to establish
a TCP connection on port 7 (Echo) of the destination host.
The network interface and ttl parameters
let the caller specify which network interface the test will go through
and the maximum number of hops the packets should go through.
A negative value for the ttl will result in an
IllegalArgumentException being thrown.
The timeout value, in milliseconds, indicates the maximum amount of time
the try should take. If the operation times out before getting an
answer, the host is deemed unreachable. A negative value will result
in an IllegalArgumentException being thrown.
if (ttl < 0)
throw new IllegalArgumentException("ttl can't be negative");
if (timeout < 0)
throw new IllegalArgumentException("timeout can't be negative");
return impl.isReachable(this, timeout, netif, ttl);
|
public boolean | isSiteLocalAddress()Utility routine to check if the InetAddress is a site local address.
return false;
|
static java.lang.Object | loadImpl(java.lang.String implName)
Object impl;
/*
* Property "impl.prefix" will be prepended to the classname
* of the implementation object we instantiate, to which we
* delegate the real work (like native methods). This
* property can vary across implementations of the java.
* classes. The default is an empty String "".
*/
String prefix = (String)AccessController.doPrivileged(
new GetPropertyAction("impl.prefix", ""));
impl = null;
try {
impl = Class.forName("java.net." + prefix + implName).newInstance();
} catch (ClassNotFoundException e) {
System.err.println("Class not found: java.net." + prefix +
implName + ":\ncheck impl.prefix property " +
"in your properties file.");
} catch (InstantiationException e) {
System.err.println("Could not instantiate: java.net." + prefix +
implName + ":\ncheck impl.prefix property " +
"in your properties file.");
} catch (IllegalAccessException e) {
System.err.println("Cannot access class: java.net." + prefix +
implName + ":\ncheck impl.prefix property " +
"in your properties file.");
}
if (impl == null) {
try {
impl = Class.forName(implName).newInstance();
} catch (Exception e) {
throw new Error("System property impl.prefix incorrect");
}
}
return impl;
|
private java.lang.Object | readResolve()Replaces the de-serialized object with an Inet4Address object.
// will replace the deserialized 'this' object
return new Inet4Address(this.hostName, this.address);
|
public java.lang.String | toString()Converts this IP address to a String . The
string returned is of the form: hostname / literal IP
address.
If the host name is unresolved, no reverse name service loopup
is performed. The hostname part will be represented by an empty string.
return ((hostName != null) ? hostName : "")
+ "/" + getHostAddress();
|
private static void | updateLookupTable(java.lang.String host)
synchronized (lookupTable) {
lookupTable.remove(host);
lookupTable.notifyAll();
}
|