/** * Returns the address of the local host. This is achieved by retrieving the name of the host from * the system, then resolving that name into an <code>InetAddress</code>. * * <p>Note: The resolved address may be cached for a short period of time. * * <p>If there is a security manager, its <code>checkConnect</code> method is called with the * local host name and <code>-1</code> as its arguments to see if the operation is allowed. If the * operation is not allowed, an InetAddress representing the loopback address is returned. * * @return the address of the local host. * @exception UnknownHostException if the local host name could not be resolved into an address. * @see SecurityManager#checkConnect * @see java.net.InetAddress#getByName(java.lang.String) */ public static InetAddress getLocalHost() throws UnknownHostException { SecurityManager security = System.getSecurityManager(); try { String local = impl.getLocalHostName(); if (security != null) { security.checkConnect(local, -1); } if (local.equals("localhost")) { return impl.loopbackAddress(); } InetAddress ret = null; synchronized (cacheLock) { long now = System.currentTimeMillis(); if (cachedLocalHost != null) { if ((now - cacheTime) < maxCacheTime) // Less than 5s old? ret = cachedLocalHost; else cachedLocalHost = null; } // we are calling getAddressFromNameService directly // to avoid getting localHost from cache if (ret == null) { InetAddress[] localAddrs; try { localAddrs = (InetAddress[]) InetAddress.getAddressFromNameService(local, null); } catch (UnknownHostException uhe) { throw new UnknownHostException(local + ": " + uhe.getMessage()); } cachedLocalHost = localAddrs[0]; cacheTime = now; ret = localAddrs[0]; } } return ret; } catch (java.lang.SecurityException e) { return impl.loopbackAddress(); } }