Class InetAddress
- All Implemented Interfaces:
Serializable
- Direct Known Subclasses:
Inet4Address,Inet6Address,InetUnixAddress
public class InetAddress extends Object implements Serializable
Inet4Address or Inet6Address (this
class cannot be instantiated directly). Most code does not need to distinguish between the two
families, and should use InetAddress.
An InetAddress may have a hostname (accessible via getHostName), but may not,
depending on how the InetAddress was created.
IPv4 numeric address formats
The getAllByName method accepts IPv4 addresses in the "decimal-dotted-quad" form only:
"1.2.3.4"- 1.2.3.4
IPv6 numeric address formats
The getAllByName method accepts IPv6 addresses in the following forms (this text
comes from RFC 2373, which you should consult
for full details of IPv6 addressing):
The preferred form is
x:x:x:x:x:x:x:x, where the 'x's are the hexadecimal values of the eight 16-bit pieces of the address. Note that it is not necessary to write the leading zeros in an individual field, but there must be at least one numeral in every field (except for the case described in the next bullet). Examples:FEDC:BA98:7654:3210:FEDC:BA98:7654:3210 1080:0:0:0:8:800:200C:417A- Due to some methods of allocating certain styles of IPv6
addresses, it will be common for addresses to contain long strings
of zero bits. In order to make writing addresses containing zero
bits easier a special syntax is available to compress the zeros.
The use of "::" indicates multiple groups of 16-bits of zeros.
The "::" can only appear once in an address. The "::" can also be
used to compress the leading and/or trailing zeros in an address.
For example the following addresses:
1080:0:0:0:8:800:200C:417A a unicast address FF01:0:0:0:0:0:0:101 a multicast address 0:0:0:0:0:0:0:1 the loopback address 0:0:0:0:0:0:0:0 the unspecified addressesmay be represented as:1080::8:800:200C:417A a unicast address FF01::101 a multicast address ::1 the loopback address :: the unspecified addresses An alternative form that is sometimes more convenient when dealing with a mixed environment of IPv4 and IPv6 nodes is
x:x:x:x:x:x:d.d.d.d, where the 'x's are the hexadecimal values of the six high-order 16-bit pieces of the address, and the 'd's are the decimal values of the four low-order 8-bit pieces of the address (standard IPv4 representation). Examples:0:0:0:0:0:0:13.1.68.3 0:0:0:0:0:FFFF:129.144.52.38or in compressed form:::13.1.68.3 ::FFFF:129.144.52.38
Scopes are given using a trailing % followed by the scope id, as in
1080::8:800:200C:417A%2 or 1080::8:800:200C:417A%en0.
See RFC 4007 for more on IPv6's scoped
address architecture.
Additionally, for backwards compatibility, IPv6 addresses may be surrounded by square brackets.
DNS caching
In Android 4.0 (Ice Cream Sandwich) and earlier, DNS caching was performed both by InetAddress and by the C library, which meant that DNS TTLs could not be honored correctly. In later releases, caching is done solely by the C library and DNS TTLs are honored.
- See Also:
Inet4Address,Inet6Address, Serialized Form
-
Field Summary
Fields Modifier and Type Field Description static InetAddressUNSPECIFIEDUsed by the DatagramSocket.disconnect implementation. -
Method Summary
Modifier and Type Method Description static voidclearDnsCache()Removes all entries from the VM's DNS cache.booleanequals(Object obj)Compares thisInetAddressinstance against the specified address inobj.byte[]getAddress()Returns the IP address represented by thisInetAddressinstance as a byte array.static InetAddress[]getAllByName(String host)Gets all IP addresses associated with the givenhostidentified by name or literal IP address.static InetAddressgetByAddress(byte[] ipAddress)Equivalent togetByAddress(null, ipAddress).static InetAddressgetByAddress(String hostName, byte[] ipAddress)Returns anInetAddresscorresponding to the given network-order bytesipAddressandscopeId.static InetAddressgetByName(String host)Returns the address of a host according to the given host string namehost.StringgetCanonicalHostName()Returns the fully qualified hostname corresponding to this IP address.StringgetHostAddress()Returns the numeric representation of this IP address (such as "127.0.0.1").StringgetHostName()Returns the host name corresponding to this IP address.static InetAddressgetLocalHost()Returns anInetAddressfor the local host if possible, or the loopback address otherwise.static InetAddressgetLoopbackAddress()Returns the IPv6 loopback address::1or the IPv4 loopback address127.0.0.1.inthashCode()Gets the hashcode of the represented IP address.booleanisAnyLocalAddress()Returns whether this is the IPv6 unspecified wildcard address::or the IPv4 "any" address,0.0.0.0.booleanisLinkLocalAddress()Returns whether this address is a link-local address or not.booleanisLoopbackAddress()Returns whether this address is a loopback address or not.booleanisMCGlobal()Returns whether this address is a global multicast address or not.booleanisMCLinkLocal()Returns whether this address is a link-local multicast address or not.booleanisMCNodeLocal()Returns whether this address is a node-local multicast address or not.booleanisMCOrgLocal()Returns whether this address is a organization-local multicast address or not.booleanisMCSiteLocal()Returns whether this address is a site-local multicast address or not.booleanisMulticastAddress()Returns whether this address is a multicast address or not.static booleanisNumeric(String address)Returns true if the string is a valid numeric IPv4 or IPv6 address (such as "192.168.0.1").booleanisReachable(int timeout)Tries to reach thisInetAddress.booleanisReachable(NetworkInterface networkInterface, int ttl, int timeout)Tries to reach thisInetAddress.booleanisSiteLocalAddress()Returns whether this address is a site-local address or not.static InetAddressparseNumericAddress(String numericAddress)Returns an InetAddress corresponding to the given numeric address (such as"192.168.0.1"or"2001:4860:800d::68").StringtoString()Returns a string containing the host name (if available) and host address.
-
Field Details
-
UNSPECIFIED
Used by the DatagramSocket.disconnect implementation.
-
-
Method Details
-
equals
Compares thisInetAddressinstance against the specified address inobj. Two addresses are equal if their address byte arrays have the same length and if the bytes in the arrays are equal.- Overrides:
equalsin classObject- Parameters:
obj- the object to be tested for equality.- Returns:
trueif both objects are equal,falseotherwise.- See Also:
Object.hashCode()
-
getAddress
public byte[] getAddress()Returns the IP address represented by thisInetAddressinstance as a byte array. The elements are in network order (the highest order address byte is in the zeroth element).- Returns:
- the address in form of a byte array.
-
getAllByName
Gets all IP addresses associated with the givenhostidentified by name or literal IP address. The IP address is resolved by the configured name service. If the host name is empty ornullanUnknownHostExceptionis thrown. If the host name is a literal IP address string an array with the corresponding singleInetAddressis returned.- Parameters:
host- the hostname or literal IP string to be resolved.- Returns:
- the array of addresses associated with the specified host.
- Throws:
UnknownHostException- if the address lookup fails.
-
getByName
Returns the address of a host according to the given host string namehost. The host string may be either a machine name or a dotted string IP address. If the latter, thehostNamefield is determined upon demand.hostcan benullwhich means that an address of the loopback interface is returned.- Parameters:
host- the hostName to be resolved to an address ornull.- Returns:
- the
InetAddressinstance representing the host. - Throws:
UnknownHostException- if the address lookup fails.
-
getHostAddress
Returns the numeric representation of this IP address (such as "127.0.0.1"). -
getHostName
Returns the host name corresponding to this IP address. This may or may not be a fully-qualified name. If the IP address could not be resolved, the numeric representation is returned instead (seegetHostAddress()). -
getCanonicalHostName
Returns the fully qualified hostname corresponding to this IP address. -
getLocalHost
Returns anInetAddressfor the local host if possible, or the loopback address otherwise. This method works by getting the hostname, performing a DNS lookup, and then taking the first returned address. For devices with multiple network interfaces and/or multiple addresses per interface, this does not necessarily return theInetAddressyou want.Multiple interface/address configurations were relatively rare when this API was designed, but multiple interfaces are the default for modern mobile devices (with separate wifi and radio interfaces), and the need to support both IPv4 and IPv6 has made multiple addresses commonplace. New code should thus avoid this method except where it's basically being used to get a loopback address or equivalent.
There are two main ways to get a more specific answer:
- If you have a connected socket, you should probably use
Socket.getLocalAddress()instead: that will give you the address that's actually in use for that connection. (It's not possible to ask the question "what local address would a connection to a given remote address use?"; you have to actually make the connection and see.) - For other use cases, see
NetworkInterface, which lets you enumerate all available network interfaces and their addresses.
Note that if the host doesn't have a hostname set – as Android devices typically don't – this method will effectively return the loopback address, albeit by getting the name
localhostand then doing a lookup to translate that to127.0.0.1.- Returns:
- an
InetAddressrepresenting the local host, or the loopback address. - Throws:
UnknownHostException- if the address lookup fails.
- If you have a connected socket, you should probably use
-
hashCode
public int hashCode()Gets the hashcode of the represented IP address.- Overrides:
hashCodein classObject- Returns:
- the appropriate hashcode value.
- See Also:
Object.equals(java.lang.Object)
-
clearDnsCache
public static void clearDnsCache()Removes all entries from the VM's DNS cache. This does not affect the C library's DNS cache, nor any caching DNS servers between you and the canonical server. -
toString
Returns a string containing the host name (if available) and host address. For example:"www.google.com/74.125.224.115"or"/127.0.0.1".IPv6 addresses may additionally include an interface name or scope id. For example:
"www.google.com/2001:4860:4001:803::1013%eth0"or"/2001:4860:4001:803::1013%2". -
isNumeric
Returns true if the string is a valid numeric IPv4 or IPv6 address (such as "192.168.0.1"). This copes with all forms of address that Java supports, detailed in theInetAddressclass documentation. -
parseNumericAddress
Returns an InetAddress corresponding to the given numeric address (such as"192.168.0.1"or"2001:4860:800d::68"). This method will never do a DNS lookup. Non-numeric addresses are errors.- Throws:
IllegalArgumentException- ifnumericAddressis not a numeric address
-
getLoopbackAddress
Returns the IPv6 loopback address::1or the IPv4 loopback address127.0.0.1.- Since:
- 1.7
-
isAnyLocalAddress
public boolean isAnyLocalAddress()Returns whether this is the IPv6 unspecified wildcard address::or the IPv4 "any" address,0.0.0.0. -
isLinkLocalAddress
public boolean isLinkLocalAddress()Returns whether this address is a link-local address or not.Valid IPv6 link-local addresses have the prefix
fe80::/10.RFC 3484 "Default Address Selection for Internet Protocol Version 6 (IPv6)" states that both IPv4 auto-configuration addresses (prefix
169.254/16) and IPv4 loopback addresses (prefix127/8) have link-local scope, butInet4Addressonly considers the auto-configuration addresses to have link-local scope. That is: the IPv4 loopback address returns false. -
isLoopbackAddress
public boolean isLoopbackAddress()Returns whether this address is a loopback address or not.Valid IPv4 loopback addresses have the prefix
127/8.The only valid IPv6 loopback address is
::1. -
isMCGlobal
public boolean isMCGlobal()Returns whether this address is a global multicast address or not.Valid IPv6 global multicast addresses have the prefix
ffxe::/16, wherexis a set of flags and the additional 112 bits make up the global multicast address space.Valid IPv4 global multicast addresses are the range of addresses from
224.0.1.0to238.255.255.255. -
isMCLinkLocal
public boolean isMCLinkLocal()Returns whether this address is a link-local multicast address or not.Valid IPv6 link-local multicast addresses have the prefix
ffx2::/16, where x is a set of flags and the additional 112 bits make up the link-local multicast address space.Valid IPv4 link-local multicast addresses have the prefix
224.0.0/24. -
isMCNodeLocal
public boolean isMCNodeLocal()Returns whether this address is a node-local multicast address or not.Valid IPv6 node-local multicast addresses have the prefix
ffx1::/16, where x is a set of flags and the additional 112 bits make up the link-local multicast address space.There are no valid IPv4 node-local multicast addresses.
-
isMCOrgLocal
public boolean isMCOrgLocal()Returns whether this address is a organization-local multicast address or not.Valid IPv6 organization-local multicast addresses have the prefix
ffx8::/16, where x is a set of flags and the additional 112 bits make up the link-local multicast address space.Valid IPv4 organization-local multicast addresses have the prefix
239.192/14. -
isMCSiteLocal
public boolean isMCSiteLocal()Returns whether this address is a site-local multicast address or not.Valid IPv6 site-local multicast addresses have the prefix
ffx5::/16, where x is a set of flags and the additional 112 bits make up the link-local multicast address space.Valid IPv4 site-local multicast addresses have the prefix
239.255/16. -
isMulticastAddress
public boolean isMulticastAddress()Returns whether this address is a multicast address or not.Valid IPv6 multicast addresses have the prefix
ff::/8.Valid IPv4 multicast addresses have the prefix
224/4. -
isSiteLocalAddress
public boolean isSiteLocalAddress()Returns whether this address is a site-local address or not.For the purposes of this method, valid IPv6 site-local addresses have the deprecated prefix
fec0::/10from RFC 1884, not the modern prefixfc00::/7from RFC 4193.RFC 3484 "Default Address Selection for Internet Protocol Version 6 (IPv6)" states that IPv4 private addresses have the prefix
10/8,172.16/12, or192.168/16.- Returns:
trueif this instance represents a site-local address,falseotherwise.
-
isReachable
Tries to reach thisInetAddress. This method first tries to use ICMP (ICMP ECHO REQUEST), falling back to a TCP connection on port 7 (Echo) of the remote host.- Parameters:
timeout- timeout in milliseconds before the test fails if no connection could be established.- Returns:
trueif this address is reachable,falseotherwise.- Throws:
IOException- if an error occurs during an I/O operation.IllegalArgumentException- if timeout is less than zero.
-
isReachable
public boolean isReachable(NetworkInterface networkInterface, int ttl, int timeout) throws IOExceptionTries to reach thisInetAddress. This method first tries to use ICMP (ICMP ECHO REQUEST), falling back to a TCP connection on port 7 (Echo) of the remote host.- Parameters:
networkInterface- the network interface on which to connection should be established.ttl- the maximum count of hops (time-to-live).timeout- timeout in milliseconds before the test fails if no connection could be established.- Returns:
trueif this address is reachable,falseotherwise.- Throws:
IOException- if an error occurs during an I/O operation.IllegalArgumentException- if ttl or timeout is less than zero.
-
getByAddress
Equivalent togetByAddress(null, ipAddress). Handy for addresses with no associated hostname.- Throws:
UnknownHostException
-
getByAddress
public static InetAddress getByAddress(String hostName, byte[] ipAddress) throws UnknownHostExceptionReturns anInetAddresscorresponding to the given network-order bytesipAddressandscopeId.For an IPv4 address, the byte array must be of length 4. For IPv6, the byte array must be of length 16. Any other length will cause an
UnknownHostException.No reverse lookup is performed. The given
hostName(which may be null) is associated with the newInetAddresswith no validation done.(Note that numeric addresses such as
"127.0.0.1"are names for the purposes of this API. Most callers probably wantgetAllByName(java.lang.String)instead.)- Throws:
UnknownHostException- ifipAddressis null or the wrong length.
-