Java IP Address Get getAllLocalIpv4Addresses()

Here you can find the source of getAllLocalIpv4Addresses()

Description

Get IP addresses for all interfaces on this machine that are IPv4.

License

Open Source License

Exception

Parameter Description
IOException if there's an error
NullPointerException if any argument is null

Return

IPv4 addresses assigned to this machine

Declaration

public static Set<InetAddress> getAllLocalIpv4Addresses() throws IOException 

Method Source Code


//package com.java2s;
/*/*  w w  w .  jav  a 2s  . c o m*/
 * Copyright (c) 2013-2014, Kasra Faghihi, All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License, or (at your option) any later version.
 * 
 * This library 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
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 */

import java.io.IOException;
import java.net.Inet4Address;

import java.net.InetAddress;
import java.net.NetworkInterface;

import java.util.Enumeration;
import java.util.HashSet;

import java.util.Set;

public class Main {
    /**
     * Get IP addresses for all interfaces on this machine that are IPv4.
     * @return IPv4 addresses assigned to this machine
     * @throws IOException if there's an error
     * @throws NullPointerException if any argument is {@code null}
     */
    public static Set<InetAddress> getAllLocalIpv4Addresses() throws IOException {
        Set<InetAddress> ret = new HashSet<>();

        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
            while (addrs.hasMoreElements()) { // make sure atleast 1 ipv4 addr bound to interface
                InetAddress addr = addrs.nextElement();

                if (addr instanceof Inet4Address && !addr.isAnyLocalAddress()) {
                    ret.add(addr);
                }
            }
        }

        return ret;
    }
}

Related

  1. getAllIPsAndAssignedBroadcastAddresses()
  2. getALLLocalHostIP()
  3. getAllLocalIP()
  4. getAllLocalIP()
  5. getAllLocalIPs()
  6. getAllMyHostIPV4Adresses()
  7. getAllUsableIPAddresses()
  8. getExternalIP()
  9. getExternalIp()