Java InetAddress Create getSpecificAddresses(@Nonnull InetAddress in)

Here you can find the source of getSpecificAddresses(@Nonnull InetAddress in)

Description

get Specific Addresses

License

Apache License

Declaration

@Nonnull
    public static Iterable<? extends InetAddress> getSpecificAddresses(@Nonnull InetAddress in)
            throws SocketException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import com.google.common.base.Function;

import com.google.common.collect.Iterables;

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

import java.net.SocketException;

import java.util.ArrayList;

import java.util.Collections;
import java.util.List;

import javax.annotation.Nonnull;

public class Main {
    @Nonnull
    public static Iterable<? extends InetAddress> getSpecificAddresses(@Nonnull InetAddress in)
            throws SocketException {
        if (!in.isAnyLocalAddress())
            return Collections.singleton(in);
        List<InetAddress> out = new ArrayList<InetAddress>();
        for (NetworkInterface iface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
            if (iface.isLoopback())
                continue;
            if (!iface.isUp())
                continue;
            for (InetAddress ifaddr : Collections.list(iface.getInetAddresses())) {
                // LOG.info("ifaddr=" + ifaddr + " iftype=" + ifaddr.getClass() + " atype=" + addr.getClass());
                if (ifaddr.isLoopbackAddress())
                    continue;
                // If we prefer the IPv6 stack, then addr.getClass() is Inet6Address, but listens on IPv4 as well.
                // if (!ifaddr.getClass().equals(addr.getClass())) continue;
                out.add(ifaddr);/*from w  ww. ja  v a  2  s. c  o  m*/
            }
        }
        if (out.isEmpty())
            out.add(InetAddress.getLoopbackAddress());
        return out;
    }

    @Nonnull
    public static Iterable<? extends InetSocketAddress> getSpecificAddresses(@Nonnull final InetSocketAddress in)
            throws SocketException {
        return Iterables.transform(getSpecificAddresses(in.getAddress()),
                new Function<InetAddress, InetSocketAddress>() {
                    @Override
                    public InetSocketAddress apply(InetAddress input) {
                        return new InetSocketAddress(input, in.getPort());
                    }
                });
    }
}

Related

  1. getPing(InetAddress address, long timeout)
  2. getPrivateInetInetAddress()
  3. getProtocolFamily(InetAddress address)
  4. getSafeInetAddress(String name, JSONObject json)
  5. getSourceAddressForDestination(InetAddress destination)
  6. getSubnetPrefix(InetAddress ip, int maskLen)
  7. getURI(String protocol, InetAddress host, int port)