📄 inetaddress.java
字号:
return hostName; } /** * 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. * * <p>If there is a security manager, this method first * calls its <code>checkConnect</code> method * with the hostname and <code>-1</code> * 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. * * @return the fully qualified domain name for this IP address, * or if the operation is not allowed by the security check, * the textual representation of the IP address. * * @see SecurityManager#checkConnect * * @since 1.4 */ public String getCanonicalHostName() { if (canonicalHostName == null) { canonicalHostName = InetAddress.getHostFromNameService(this, true); } return canonicalHostName; } /** * Returns the hostname for this address. * * <p>If there is a security manager, this method first * calls its <code>checkConnect</code> method * with the hostname and <code>-1</code> * 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. * * @return the host name for this IP address, or if the operation * is not allowed by the security check, the textual * representation of the IP address. * * @param check make security check if true * * @see SecurityManager#checkConnect */ private static String getHostFromNameService(InetAddress addr, boolean check) { 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]); } } //NOTE: 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; } /** * Returns the raw IP address of this <code>InetAddress</code> * object. The result is in network byte order: the highest order * byte of the address is in <code>getAddress()[0]</code>. * * @return the raw IP address of this object. */ public byte[] getAddress() { return null; } /** * Returns the IP address string in textual presentation. * * @return the raw IP address in a string format. * @since JDK1.0.2 */ public String getHostAddress() { return null; } /** * Returns a hashcode for this IP address. * * @return a hash code value for this IP address. */ public int hashCode() { return -1; } /** * Compares this object against the specified object. * The result is <code>true</code> if and only if the argument is * not <code>null</code> and it represents the same IP address as * this object. * <p> * Two instances of <code>InetAddress</code> represent the same IP * address if the length of the byte arrays returned by * <code>getAddress</code> is the same for both, and each of the * array components is the same for the byte arrays. * * @param obj the object to compare against. * @return <code>true</code> if the objects are the same; * <code>false</code> otherwise. * @see java.net.InetAddress#getAddress() */ public boolean equals(Object obj) { return false; } /** * Converts this IP address to a <code>String</code>. 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 a string representation of this IP address. */ public String toString() { return ((hostName != null) ? hostName : "") + "/" + getHostAddress(); } /* * Cached addresses - our own litle nis, not! */ private static Cache addressCache = new Cache(InetAddressCachePolicy.get()); private static Cache negativeCache = new Cache(InetAddressCachePolicy.getNegative()); private static boolean addressCacheInit = false; static InetAddress[] unknown_array; // put THIS in cache static InetAddressImpl impl; private static HashMap lookupTable = new HashMap(); /** * Represents a cache entry */ static final class CacheEntry { CacheEntry(Object address, long expiration) { this.address = address; this.expiration = expiration; } Object address; long expiration; } /** * A cache that manages entries based on a policy specified * at creation time. */ static final class Cache { private int policy; private LinkedHashMap cache; /** * Create cache with specific policy */ public Cache(int policy) { this.policy = policy; cache = new LinkedHashMap(); } /** * Add an entry to the cache. If there's already an * entry then for this host then the entry will be * replaced. */ public Cache put(String host, Object address) { if (policy == InetAddressCachePolicy.NEVER) { return this; } // purge any expired entries if (policy != InetAddressCachePolicy.FOREVER) { // As we iterate in insertion order we can // terminate when a non-expired entry is found. LinkedList expired = new LinkedList(); Iterator i = cache.keySet().iterator(); long now = System.currentTimeMillis(); while (i.hasNext()) { String key = (String)i.next(); CacheEntry entry = (CacheEntry)cache.get(key); if (entry.expiration >= 0 && entry.expiration < now) { expired.add(key); } else { break; } } i = expired.iterator(); while (i.hasNext()) { cache.remove(i.next()); } } // create new entry and add it to the cache // -- as a HashMap replaces existing entries we // don't need to explicitly check if there is // already an entry for this host. long expiration; if (policy == InetAddressCachePolicy.FOREVER) { expiration = -1; } else { expiration = System.currentTimeMillis() + (policy * 1000); } CacheEntry entry = new CacheEntry(address, expiration); cache.put(host, entry); return this; } /** * Query the cache for the specific host. If found then * return its CacheEntry, or null if not found. */ public CacheEntry get(String host) { if (policy == InetAddressCachePolicy.NEVER) { return null; } CacheEntry entry = (CacheEntry)cache.get(host); // check if entry has expired if (entry != null && policy != InetAddressCachePolicy.FOREVER) { if (entry.expiration >= 0 && entry.expiration < System.currentTimeMillis()) { cache.remove(host); entry = null; } } return entry; } } /* * Initialize cache and insert anyLocalAddress into the * unknown array with no expiry. */ private static void cacheInitIfNeeded() { // Uncomment this line if assertions are always // turned on for libraries //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; } /* * Cache the given hostname and address. */ private static void cacheAddress(String hostname, Object address, boolean success) { synchronized (addressCache) { cacheInitIfNeeded(); if (success) { addressCache.put(hostname, address); } else { negativeCache.put(hostname, address); } } } /* * Lookup hostname in cache (positive & negative cache). If * found return address, null if not found. */ private static Object getCachedAddress(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; } static { // 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) { } } } /** * Create an InetAddress based on the provided host name and IP address * No name service is checked for the validity of the address. * * <p> The host name can either be a machine name, such as * "<code>java.sun.com</code>", or a textual representation of its IP * address. * * <p> For <code>host</code> specified in literal IPv6 address, * either the form defined in RFC 2732 or the literal IPv6 address * format defined in RFC 2373 is accepted. * * <p> If addr specifies an IPv4 address an instance of Inet4Address * will be returned; otherwise, an instance of Inet6Address * will be returned. * * <p> IPv4 address byte array must be 4 bytes long and IPv6 byte array * must be 16 bytes long * * @param host the specified host * @param addr the raw IP address in network byte order * @return an InetAddress object created from the raw IP address. * @exception UnknownHostException if IP address is of illegal length * @since 1.4 */ public static InetAddress getByAddress(String host, byte[] addr) throws UnknownHostException { 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) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -