inetaddress.java

来自「纯java操作系统jnode,安装简单和操作简单的个人使用的Java操作系统」· Java 代码 · 共 679 行 · 第 1/2 页

JAVA
679
字号
/* InetAddress.java -- Class to model an Internet address
 Copyright (C) 1998, 1999, 2002 Free Software Foundation, Inc.

 This file is part of GNU Classpath.

 GNU Classpath is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2, or (at your option)
 any later version.
 
 GNU Classpath is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GNU Classpath; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 02111-1307 USA.

 Linking this library statically or dynamically with other modules is
 making a combined work based on this library.  Thus, the terms and
 conditions of the GNU General Public License cover the whole
 combination.

 As a special exception, the copyright holders of this library give you
 permission to link this library with independent modules to produce an
 executable, regardless of the license terms of these independent
 modules, and to copy and distribute the resulting executable under
 terms of your choice, provided that you also meet, for each linked
 independent module, the terms and conditions of the license of that
 module.  An independent module is a module which is not derived from
 or based on this library.  If you modify this library, you may extend
 this exception to your version of the library, but you are not
 obligated to do so.  If you do not wish to do so, delete this
 exception statement from your version. */

package java.net;

import java.io.Serializable;
import java.util.HashMap;
import java.util.StringTokenizer;

/**
 * This class models an Internet address. It does not have a public
 * constructor. Instead, new instances of this objects are created using the
 * static methods getLocalHost(), getByName(), and getAllByName().
 * <p>
 * This class fulfills the function of the C style functions gethostname(),
 * gethostbyname(), and gethostbyaddr(). It resolves Internet DNS names into
 * their corresponding numeric addresses and vice versa.
 * 
 * @version 0.5
 * 
 * @author Aaron M. Renn (arenn@urbanophile.com)
 */
public class InetAddress implements Serializable {

    /** ********************************************************************** */

    /*
     * Static Variables
     */

    private static final long serialVersionUID = 3286316764910316507L;

    /**
     * The default DNS hash table size, use a prime number happy with hash
     * table
     */
    private static final int DEFAULT_CACHE_SIZE = 89;

    /**
     * The default caching period in minutes
     */
    private static final int DEFAULT_CACHE_PERIOD = (4 * 60);

    /**
     * Percentage of cache entries to purge when the table gets full
     */
    private static final int DEFAULT_CACHE_PURGE_PCT = 30;

    /**
     * The special IP address INADDR_ANY
     */
    private static InetAddress inaddr_any;

    /** dummy InetAddress, used to bind socket to any (all) network interfaces */
    static InetAddress ANY_IF;

    /**
     * The size of the cache
     */
    private static int cache_size = 0;

    /**
     * The length of time we will continue to read the address from cache
     * before forcing another lookup
     */
    private static int cache_period = 0;

    /**
     * What percentage of the cache we will purge if it gets full
     */
    private static int cache_purge_pct = 0;

    /**
     * HashMap to use as DNS lookup cachem use HashMap because all accesses to
     * cache are already synchronized
     */
    private static HashMap cache;

    // Static initializer for the cache
    static {
        // Look for properties that override default caching behavior
        cache_size = Integer.getInteger("gnu.java.net.dns_cache_size",
                DEFAULT_CACHE_SIZE).intValue();
        cache_period = Integer.getInteger("gnu.java.net.dns_cache_period",
                DEFAULT_CACHE_PERIOD * 60 * 1000).intValue();

        cache_purge_pct = Integer.getInteger(
                "gnu.java.net.dns_cache_purge_pct", DEFAULT_CACHE_PURGE_PCT)
                .intValue();

        // Fallback to defaults if necessary
        if ((cache_purge_pct < 1) || (cache_purge_pct > 100))
                cache_purge_pct = DEFAULT_CACHE_PURGE_PCT;

        // Create the cache
        if (cache_size != 0) cache = new HashMap(cache_size);

        // precompute the ANY_IF address
        try {
            ANY_IF = getInaddrAny();
        } catch (UnknownHostException uhe) {
            // Hmmm, make one up and hope that it works.
            byte[] zeros = { 0, 0, 0, 0};
            ANY_IF = new InetAddress(zeros);
        }
    }

    /** ********************************************************************** */

    /*
     * Instance variables
     */

    /**
     * An array of octets representing an IP address
     */
    transient byte[] addr;

    /**
     * The name of the host for this address
     */
    String hostName;

    /**
     * Backup hostname alias for this address.
     */
    transient String hostname_alias;

    /**
     * The time this address was looked up
     */
    transient long lookup_time;

    /**
     * Required for serialized form
     */
    int address;

    int family;

    /** ********************************************************************** */

    /*
     * Class Methods
     */

    /**
     * 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) {
            //*** 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 = new byte[] { 0, 0, 0, 0};
            inaddr_any = new InetAddress(tmp);
        }

        return (inaddr_any);
    }

    /** ********************************************************************** */

    /**
     * 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 hostname
     *            The name of the desired host, or null for the local machine
     * 
     * @return All addresses of the host as an array of InetAddress's
     * 
     * @exception UnknownHostException
     *                If no IP address can be found for the given hostname
     */
    public static InetAddress[] getAllByName(String hostname)
            throws UnknownHostException {
        // Default to current host if necessary
        if (hostname == null) {
            InetAddress local = getLocalHost();
            return getAllByName(local.getHostName());
        }

        // Check the cache for this host before doing a lookup
        InetAddress[] addresses = checkCacheFor(hostname);
        if (addresses != null) return (addresses);

        // Not in cache, try the lookup
        addresses = getHostByName(hostname);
        if ((addresses == null) || (addresses.length == 0)) { throw new UnknownHostException(
                hostname); }

        addToCache(hostname, addresses);

        return addresses;
    }

    /** ********************************************************************** */

    /**
     * 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
     * 
     * @exception UnknownHostException
     *                If no IP address can be found for the given hostname
     */
    public static InetAddress getByName(String hostname)
            throws UnknownHostException {
        // Default to current host if necessary
        if (hostname == null) return getLocalHost();

        // First, check to see if it is an IP address. If so, then don't
        // do a DNS lookup.
        StringTokenizer st = new StringTokenizer(hostname, ".");
        if (st.countTokens() == 4) {
            int i;
            byte[] ip = new byte[ 4];
            for (i = 0; i < 4; i++) {
                try {
                    ip[ i] = Byte.parseByte(st.nextToken());
                    if ((ip[ i] < 0) || (ip[ 1] > 255)) break;
                } catch (NumberFormatException e) {
                    break;
                }
            }
            if (i == 4) { return (new InetAddress(ip)); }
        }

        // Wasn't an IP, so try the lookup
        InetAddress[] addresses = getAllByName(hostname);

        return addresses[ 0];
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?