📄 inetaddress.java
字号:
{ if (hostname_alias != null) return hostname_alias; else return getHostAddress(); } } /** * Returns the IP address of this object as a byte array. * * @return IP address */ public byte[] getAddress() { // An experiment shows that JDK1.2 returns a different byte array each // time. This makes sense, in terms of security. return (byte[]) addr.clone(); } /** * Returns the IP address of this object as a String. The address is in * the dotted octet notation, for example, "127.0.0.1". * * @return The IP address of this object in String form * * @since 1.0.2 */ public String getHostAddress() { StringBuffer sb = new StringBuffer (40); for (int i = 0; i < addr.length; i++) { sb.append (addr [i] & 0xff); if (i < (addr.length - 1)) sb.append ("."); } return sb.toString(); } /** * Returns a hash value for this address. Useful for creating hash * tables. Overrides Object.hashCode() * * @return A hash value for this address. */ public int hashCode() { // There hashing algorithm is not specified, but a simple experiment // shows that it is equal to the address, as a 32-bit big-endian integer. int hash = 0; int len = addr.length; int i = len > 4 ? len - 4 : 0; for ( ; i < len; i++) hash = (hash << 8) | (addr[i] & 0xFF); return hash; } /** * Tests this address for equality against another InetAddress. The two * addresses are considered equal if they contain the exact same octets. * This implementation overrides Object.equals() * * @param obj The address to test for equality * * @return true if the passed in object's address is equal to this one's, * false otherwise */ public boolean equals (Object obj) { if (obj == null || ! (obj instanceof InetAddress)) return false; // "The Java Class Libraries" 2nd edition says "If a machine has // multiple names instances of InetAddress for different name of // that same machine are not equal. This is because they have // different host names." This violates the description in the // JDK 1.2 API documentation. A little experimentation // shows that the latter is correct. byte[] addr2 = ((InetAddress) obj).addr; if (addr.length != addr2.length) return false; for (int i = 0; i < addr.length; i++) if (addr [i] != addr2 [i]) return false; return true; } /** * Converts this address to a String. This string contains the IP in * dotted decimal form. For example: "127.0.0.1" This method is equivalent * to getHostAddress() and overrides Object.toString() * * @return This address in String form */ public String toString() { String host; String address = getHostAddress(); if (hostName != null) host = hostName; else if (hostname_alias != null) host = hostname_alias; else host = address; return host + "/" + address; } /** * 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]. * * @param addr The IP address to create the InetAddress object from * * @exception UnknownHostException If IP address has illegal length * * @since 1.4 */ public static InetAddress getByAddress (byte[] addr) throws UnknownHostException { return getByAddress (null, addr); } /** * Creates an InetAddress based on the provided host name and IP address. * No name service is checked for the validity of the address. * * @param host The hostname of the InetAddress object to create * @param addr The IP address to create the InetAddress object from * * @exception UnknownHostException If IP address is of illegal length * * @since 1.4 */ public static InetAddress getByAddress (String host, byte[] addr) throws UnknownHostException { if (addr.length == 4) return new Inet4Address (addr, host); if (addr.length == 16) return new Inet6Address (addr, host); throw new UnknownHostException ("IP address has illegal length"); } /** * If host is a valid numeric IP address, return the numeric address. * Otherwise, return null. */ private static byte[] aton (String hostname) { StringTokenizer st = new StringTokenizer (hostname, "."); if (st.countTokens() == 4) { int index; byte[] address = new byte [4]; for (index = 0; index < 4; index++) { try { short n = Short.parseShort (st.nextToken()); if ((n < 0) || (n > 255)) break; address [index] = (byte) n; } catch (NumberFormatException e) { break; } } if (index == 4) return address; } return null; } /** * Returns an InetAddress object representing the IP address of the given * hostname. This name can be either a hostname such as "www.urbanophile.com" * or an IP address in dotted decimal format such as "127.0.0.1". If the * hostname is null, the hostname of the local machine is supplied by * default. This method is equivalent to returning the first element in * the InetAddress array returned from GetAllByName. * * @param hostname The name of the desired host, or null for the local machine. * * @return The address of the host as an InetAddress object. * * @exception UnknownHostException If no IP address for the host could * be found * @exception SecurityException If a security manager exists and its * checkConnect method doesn't allow the operation */ public static InetAddress getByName (String hostname) throws UnknownHostException { SecurityManager s = System.getSecurityManager(); if (s != null) s.checkConnect (hostname, -1); // Default to current host if necessary // !!! THIS SHOULD NOT BE LOCAL HOST !!! // LOCALHOST == HOSTNAME and here WE WANT "localhost" if (hostname == null || hostname == "") return getByName(LOCALHOST_NAME); // Assume that the host string is an IP address. byte[] address = aton (hostname); if (address != null) return new InetAddress (address); // Try to resolve the host by DNS InetAddress[] addresses = getAllByName (hostname); return addresses [0]; } /** * Returns an array of InetAddress objects representing all the host/ip * addresses of a given host, given the host's name. This name can be * either a hostname such as "www.urbanophile.com" or an IP address in * dotted decimal format such as "127.0.0.1". If the value is null, the * hostname of the local machine is supplied by default. * * @param @param hostname The name of the desired host, or null for the * local machine. * * @return All addresses of the host as an array of InetAddress objects. * * @exception UnknownHostException If no IP address for the host could * be found * @exception SecurityException If a security manager exists and its * checkConnect method doesn't allow the operation */ public static InetAddress[] getAllByName (String hostname) throws UnknownHostException { SecurityManager s = System.getSecurityManager(); if (s != null) s.checkConnect (hostname, -1); // Default to current host if necessary // !!! SEE getByName FOR THE REMARK !!! if (hostname == null || hostname.equals("")) hostname = LOCALHOST_NAME; // Check the cache for this host before doing a lookup InetAddress[] addresses = checkCacheFor (hostname); if (addresses != null) return addresses; byte[][] iplist; if (hostname.equals(LOCALHOST_NAME)) { iplist = new byte[][] { new byte[] { 127, 0, 0, 1 } }; } else { // Not in cache, try the lookup iplist = impl.getHostByName (hostname); if (iplist.length == 0) throw new UnknownHostException (hostname); } addresses = new InetAddress [iplist.length]; for (int i = 0; i < iplist.length; i++) { if (iplist[i].length != 4 && iplist[i].length != 16) throw new UnknownHostException (hostname); // Don't store the hostname in order to force resolution of the // canonical names of these ip's when the user asks for the hostname // But do specify the host alias so if the IP returned won't // reverse lookup we don't throw an exception. // If the length is equal to 16 this is an IPv6 address. if (iplist[i].length == 16) addresses[i] = new Inet6Address (iplist[i], hostname); else addresses[i] = new InetAddress (iplist[i], null, hostname); } addToCache (hostname, addresses); return addresses; } /** * This method checks the DNS cache to see if we have looked this hostname * up before. If so, we return the cached addresses unless it has been in the * cache too long. * * @param hostname The hostname to check for * * @return The InetAddress for this hostname or null if not available */ private static synchronized InetAddress[] checkCacheFor (String hostname) { InetAddress[]addresses = null; if (cache_size == 0) return (null); Object obj = cache.get (hostname); if (obj == null) return (null); if (obj instanceof InetAddress[]) addresses = (InetAddress[])obj; if (addresses == null) return (null); if (cache_period != -1) if ((System.currentTimeMillis () - addresses[0].lookup_time) > cache_period) { cache.remove (hostname); return (null); } return addresses; } /** * This method adds an InetAddress object to our DNS cache. Note that * if the cache is full, then we run a purge to get rid of old entries. * This will cause a performance hit, thus applications using lots of * lookups should set the cache size to be very large. * * @param hostname The hostname to cache this address under * @param obj The InetAddress or InetAddress array to store */ private static synchronized void addToCache (String hostname, Object obj) { if (cache_size == 0) return; // Check to see if hash table is full if (cache_size != -1) if (cache.size () == cache_size) { // FIXME Add code to purge later. } cache.put (hostname, obj); } /** * Returns the special address INADDR_ANY used for binding to a local * port on all IP addresses hosted by a the local host. * * @return An InetAddress object representing INDADDR_ANY * * @exception UnknownHostException If an error occurs */ static InetAddress getInaddrAny () throws UnknownHostException { if (inaddr_any == null) { byte[]tmp = lookupInaddrAny (); inaddr_any = new InetAddress (tmp); } return (inaddr_any); } /** * This native method looks up the hostname of the local machine * we are on. If the actual hostname cannot be determined, then the * value "localhost" will be used. This native method wrappers the * "gethostname" function. * * @return The local hostname. */ private static native String getLocalHostname(); /** * Returns an InetAddress object representing the address of the current * host. * * @return The local host's address * * @exception UnknownHostException If no IP address for the host could * be found */ public static InetAddress getLocalHost() throws UnknownHostException { String hostname = getLocalHostname(); return getByName (hostname); } /** * Returns the value of the special address INADDR_ANY */ private static native byte[] lookupInaddrAny() throws UnknownHostException; /* * Needed for serialization. */ private void readResolve() throws ObjectStreamException { // FIXME: implement this } private void readObject (ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); addr = new byte [4]; addr [3] = (byte) address; for (int i = 2; i >= 0; --i) addr [i] = (byte) (address >>= 8); family = 2; /* AF_INET */ } private void writeObject (ObjectOutputStream oos) throws IOException { // Build a 32 bit address from the last 4 bytes of a 4 byte IPv4 address // or a 16 byte IPv6 address. int len = addr.length; int i = len - 4; for (; i < len; i++) address = address << 8 | (((int) addr [i]) & 0xFF); oos.defaultWriteObject(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -