Java Host Address Get getHostExternalAddr()

Here you can find the source of getHostExternalAddr()

Description

get Host External Addr

License

Open Source License

Return

The host address

Declaration

public static String getHostExternalAddr() 

Method Source Code


//package com.java2s;
/*//from   ww w.j a v a  2s .co m
 * #%L
 * Active Home :: Tools
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2016 org.active-home
 * %%
 * This program 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 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program 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 this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class Main {
    /**
     * @return The host address
     */
    public static String getHostExternalAddr() {
        try {
            Enumeration e = NetworkInterface.getNetworkInterfaces();

            while (e.hasMoreElements()) {
                NetworkInterface n = (NetworkInterface) e.nextElement();
                Enumeration ee = n.getInetAddresses();
                while (ee.hasMoreElements()) {
                    InetAddress i = (InetAddress) ee.nextElement();
                    if (!i.getHostAddress().startsWith("192") && !i.getHostAddress().startsWith("127")) {
                        if (!i.getHostAddress().contains(":")) {
                            return i.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e1) {
            e1.printStackTrace();
        }
        return "127.0.0.1";
    }
}

Related

  1. getHostAddress(String hostPort)
  2. getHostAddresses()
  3. getHostAddresses()
  4. getHostAddresses()
  5. getHostAddressFromProperty(final String property)
  6. getHostName(String addr)
  7. getHostName(String address)
  8. getHostName(String address)
  9. getHostName(String localAddress)