Here you can find the source of getAllLocalIpv4Addresses()
Parameter | Description |
---|---|
IOException | if there's an error |
NullPointerException | if any argument is null |
public static Set<InetAddress> getAllLocalIpv4Addresses() throws IOException
//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; } }