⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 networkaddressmanager.java

📁 jtapi for telephone
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* ===================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * Portions of this software are based upon public domain software
 * originally written at the National Center for Supercomputing Applications,
 * University of Illinois, Urbana-Champaign.
 */



package net.sourceforge.gjtapi.raw.sipprovider.common;

import net.java.stun4j.client.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import net.java.stun4j.StunAddress;
import java.net.InetSocketAddress;
import net.java.stun4j.*;
import java.net.NetworkInterface;
import java.net.Inet4Address;
import java.net.Inet6Address;

/**
 * The class handles network address selection and firewall support. It
 * implements
 *
 * @todo more extensive NAT support depending on NAT type.
 * @todo firewall mapping lifetime detection.
 * @todo retrive addresses through NetworkInterface.
 *
 * <p>Organisation: Network Research Team (Louis Pasteur University - Strasbourg, France)</p>
 * @author Emil Ivov
 * @version 0.1
 */
public class NetworkAddressManager
{
    private static Console console = Console.getConsole(NetworkAddressManager.class);
    private static NetworkAddressManager manager = null;
    private SimpleAddressDetector detector = null;
    private boolean useStun = true;
    private static final int RANDOM_PORT = 55055;
    private static final String WINDOWS_AUTO_CONFIGURED_ADDRESS_PREFIX = "169";
    private NetworkAddressManager()
    {
    }

    private void init()
    {
        try {
            console.logEntry();
            // init stun
            String stunAddressStr = null;
            int port = -1;
            try {
                stunAddressStr = Utils.getProperty(
                    "net.java.sip.communicator.STUN_SERVER_ADDRESS");
                String portStr = Utils.getProperty(
                    "net.java.sip.communicator.STUN_SERVER_PORT");
                if (stunAddressStr == null || portStr == null) {
                    useStun = false;
                    //don't throw an exception as this is most probably the user that doesn't want stun
                    return;
//                    throw new Exception("STUN address or port were null");
                }
                port = Integer.valueOf(portStr).intValue();
            }
            catch (Throwable ex) {
                console.error(
                    "Failed to init STUN service and it will stay disabled. Error was:",
                    ex);
                useStun = false;
            }
            detector = new SimpleAddressDetector(new StunAddress(stunAddressStr,
                port));
            if (console.isDebugEnabled())
                console.debug(
                    "Created a STUN Address detector for the following STUN server: " +
                    stunAddressStr + ":" + port);
            try {
                detector.start();
                console.debug("STUN server started;");
            }
            catch (StunException ex) {
                console.error(
                    "Failed to start the STUN Address Detector at address:" +
                    stunAddressStr + ":" + port, ex);
                detector = null;
                useStun = false;
            }
        }
        finally {
            console.logExit();
        }
    }

    /**
     * Initializes the address manager and the underlying STUN lib.
     */
    public static void start()
    {
        if (manager != null)
            return;
        manager = new NetworkAddressManager();
        manager.init();
        //Detect and output network configuration (Firewall and NAT type)

        //only used for debugging currently.
        if (manager.useStun)
            new NetworkDiagnostics().start();
    }

    /**
     * Shuts down the address manager and the underlying stun lib and deletes
     * the manager.
     */
    public static void shutDown()
    {
        if (manager == null || manager.detector == null)
            return;
        manager.detector.shutDown();
        manager.detector = null;
        manager = null;
    }

    /**
     * Returns an InetAddress instance representing the local host or null if no
     * IP address for the host could be found
     * @return an InetAddress instance representing the local host or null if no
     * IP address for the host could be found
     */
    public static InetAddress getLocalHost()
    {
        return getLocalHost(true);
    }

    /**
     * Returns a localhostAddress. The method uses the following algorithm to
     * choose among multiple addresses:
     * if stun is enabled - queries STUN server and saves returned address
     * Scans addresses for all network interfaces
     *       if an address that matches the one returned by the STUN server is found - it is returned
     * 	     else
     *       if a non link local (starting with 172.16-31, 10, or 192.168) address is found it is returned
     *       else
     *       if a link local address is found it is returned
     *       else
     *       if the any address is accepted - it is returned
     *       else
     *       returns the InetAddress.getLocalHost()
     *       if the InetAddress.getLocalHost() fails returns
     *       the "any" local address - 0.0.0.0
     *
     * @param anyAddressIsAccepted is 0.0.0.0 accepted as a return value.
     * @return the address that was detected the address of the localhost.
     */
    public static InetAddress getLocalHost(boolean anyAddressIsAccepted)
    {
        try {
            console.logEntry();
            //redetect address each time for mobility reasons

            //(though InetAddress itself is not really mobile but in case it gets fixed).
            InetAddress localHost = null;
            InetAddress mappedAddress = null;
            InetAddress linkLocalAddress = null;
            InetAddress publicAddress = null;
            boolean preferIPv4Stack =
                Utils.getProperty("java.net.preferIPv4Stack") == null ?
                false
                : Boolean.valueOf(Utils.
                                  getProperty("java.net.preferIPv4Stack")).
                booleanValue();
            try {
                //check whether we have a public address that matches one of the local interfaces

                //if not - return the first one that is not the loopback
                if (manager.useStun) { //very important check to avoid recursion
                    mappedAddress = getPublicAddressFor(RANDOM_PORT).getAddress();
                }
                Enumeration localIfaces = NetworkInterface.getNetworkInterfaces();
                interfaces_loop:while (localIfaces.hasMoreElements()) {
                    NetworkInterface iFace = (NetworkInterface) localIfaces.
                        nextElement();
                    Enumeration addresses = iFace.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress address = (InetAddress) addresses.
                            nextElement();
                        if (!address.isAnyLocalAddress()
                            && !address.isLinkLocalAddress()
                            && !address.isLoopbackAddress()
                            && !isWindowsAutoConfiguredIPv4Address(address)) {
                            if (mappedAddress != null
                                && mappedAddress.equals(address)) {
                                if (console.isDebugEnabled())

⌨️ 快捷键说明

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