Java Local Address Get getLocalAddress()

Here you can find the source of getLocalAddress()

Description

get Local Address

License

Open Source License

Exception

Parameter Description
UnknownHostException an exception

Return

A non-loopback IPv4 address of a network interface on the local host.

Declaration

public static InetAddress getLocalAddress() throws UnknownHostException 

Method Source Code


//package com.java2s;
/*//from  ww  w.  j  ava 2 s  .com
 * 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/>.
 */

import java.net.*;
import java.util.Enumeration;

public class Main {
    /**
     * @return A non-loopback IPv4 address of a network interface on the local
     *         host.
     * @throws UnknownHostException
     */
    public static InetAddress getLocalAddress() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();

        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
            return addr;
        }

        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    Enumeration<InetAddress> addresses = interfaces.nextElement().getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            return addr;
                        }
                    }
                }
            }
        } catch (SocketException se) {
        }

        throw new UnknownHostException("localhost has no interface with a non-loopback IPv4 address");
    }
}

Related

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