Java IP Address Get getAllUsableIPAddresses()

Here you can find the source of getAllUsableIPAddresses()

Description

Returns a list of IP addresses that can be used to communicate with a peer on a different machine.

License

Apache License

Declaration

public static List<String> getAllUsableIPAddresses() 

Method Source Code


//package com.java2s;
/*/*from   ww  w.  j a v a 2  s. c  o  m*/
* Copyright 2014 Christopher Mann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    /**
     * Returns a list of IP addresses that can be used to communicate with a peer on a
     * different machine. The IP addresses are in CIDR notation (e.g. 192.168.2.1/24).
     * @return
     */
    public static List<String> getAllUsableIPAddresses() {
        List<String> output = new ArrayList<String>();
        try {
            for (NetworkInterface ni : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                for (InterfaceAddress address : ni.getInterfaceAddresses()) {
                    if (!address.getAddress().isMulticastAddress() && !address.getAddress().isLinkLocalAddress()
                            && !address.getAddress().isLoopbackAddress()) {
                        output.add(address.getAddress().getHostAddress() + "/" + address.getNetworkPrefixLength());
                    }
                }
            }
        } catch (SocketException e) {

        }
        return output;
    }
}

Related

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