Java Local Address Get getLocalAddress()

Here you can find the source of getLocalAddress()

Description

Get the IP Address by which the rest of the world knows us.

License

Open Source License

Return

The InetAddress representing the host on the network and NOT the loopback address.

Declaration

public static InetAddress getLocalAddress() 

Method Source Code

//package com.java2s;
/*//w ww .ja va  2  s . c om
 * Copyright (c) 2006 Stephan D. Cote' - All rights reserved.
 * 
 * This program and the accompanying materials are made available under the 
 * terms of the MIT License which accompanies this distribution, and is 
 * available at http://creativecommons.org/licenses/MIT/
 *
 * Contributors:
 *   Stephan D. Cote 
 *      - Initial API and implementation
 */

import java.net.InetAddress;

import java.net.UnknownHostException;

public class Main {
    private static InetAddress localAddress = null;

    /**
     * Get the IP Address by which the rest of the world knows us.
     *
     * <p>This is useful in helping insure that we don't accidently start binding
     * to or otherwise using the local loopback address.
     *
     * <p>This requires some type of IP address resolver to be installed, like
     * DNS, NIS or at least hostname lookup.
     *
     * @return The InetAddress representing the host on the network and NOT the
     *         loopback address.
     */
    public static InetAddress getLocalAddress() {
        // If we already looked this up, use the cached result to save time
        if (localAddress != null) {
            return localAddress;
        }

        // No cached result, figure it out and cache it for later
        InetAddress addr = null;

        // Make sure we get the IP Address by which the rest of the world knows us
        // or at least, our host's default network interface
        try {
            // This helps insure that we do not get localhost (127.0.0.1)
            addr = InetAddress.getByName(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            // Aaaaww Phooey! DNS is not working or we are not in it.
            addr = null;
        }

        // If it looks like a unique address, return it, otherwise try again
        if ((addr != null) && !addr.getHostAddress().equals("127.0.0.1")
                && !addr.getHostAddress().equals("0.0.0.0")) {
            localAddress = addr;
            return addr;
        }

        // Try it the way it's supposed to work
        try {
            addr = InetAddress.getLocalHost();
        } catch (Exception ex) {
            addr = null;
        }

        localAddress = addr;

        return addr;
    }
}

Related

  1. getLocalAddress()
  2. getLocalAddress()
  3. getLocalAddress()
  4. getLocalAddress()
  5. getLocalAddress()
  6. getLocalAddress()
  7. getLocalAddress()
  8. getLocalAddress()
  9. getLocalAddress()