Java Local Address Get getLocalAddresses()

Here you can find the source of getLocalAddresses()

Description

Returns list of machine assigned IP addresses

License

Open Source License

Declaration

public static InetAddress[] getLocalAddresses() 

Method Source Code

//package com.java2s;
/**//  w ww .  j  a v a  2 s . com
 * Aptana Studio
 * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
 * Please see the license.html included with this distribution for details.
 * Any modifications to this file must keep this entire header intact.
 */

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

import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class Main {
    /**
     * Returns list of machine assigned IP addresses
     * 
     * @return
     */
    public static InetAddress[] getLocalAddresses() {
        List<InetAddress> addrs = new ArrayList<InetAddress>();
        try {
            for (Enumeration<NetworkInterface> e1 = NetworkInterface.getNetworkInterfaces(); e1
                    .hasMoreElements();) {
                NetworkInterface iface = e1.nextElement();
                for (Enumeration<InetAddress> e2 = iface.getInetAddresses(); e2.hasMoreElements();) {
                    InetAddress inetAddr = e2.nextElement();
                    if (inetAddr instanceof Inet4Address) {
                        if (!addrs.contains(inetAddr)) {
                            if (!inetAddr.isLoopbackAddress()) {
                                addrs.add(0, inetAddr);
                            } else {
                                addrs.add(inetAddr);
                            }
                        }
                    }
                }
            }
        } catch (SocketException ignore) {
        }
        return addrs.toArray(new InetAddress[addrs.size()]);
    }
}

Related

  1. getLocalAddress(int port)
  2. getLocalAddress(String adaptorName)
  3. getLocalAddress(String filter)
  4. getLocalAddress0()
  5. getLocalAddressAsString()
  6. getLocalAddresses()
  7. getLocalAddresses()
  8. getLocalAddresses()
  9. getLocalAddressFromNetworkInterfacesListeningOnPort(int pPort)