Java Local Address Get getLocalAddressWithMulticast()

Here you can find the source of getLocalAddressWithMulticast()

Description

Get a local address which supports multicast.

License

Apache License

Exception

Parameter Description
UnknownHostException an exception
SocketException an exception

Return

a multicast enabled address of null if none could be found

Declaration

public static InetAddress getLocalAddressWithMulticast() throws UnknownHostException, SocketException 

Method Source Code

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

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.*;
import java.util.*;

public class Main {
    private static Method isUp;
    private static Method supportsMulticast;

    /**//from   w w  w  .  j  a va2 s.  c  o m
     * Get a local address which supports multicast. A loopback adress is returned, but only if not
     * another is available
     *
     * @return a multicast enabled address of null if none could be found
     * @throws UnknownHostException
     * @throws SocketException
     */
    public static InetAddress getLocalAddressWithMulticast() throws UnknownHostException, SocketException {
        InetAddress addr = InetAddress.getLocalHost();
        NetworkInterface nif = NetworkInterface.getByInetAddress(addr);
        if (addr.isLoopbackAddress() || addr instanceof Inet6Address || !isMulticastSupported(nif)) {
            // Find local address that isn't a loopback address
            InetAddress lookedUpAddr = findLocalAddressViaNetworkInterface();
            // If a local, multicast enabled address can be found, use it. Otherwise
            // we are using the local address, which might not be what you want
            if (lookedUpAddr != null) {
                return lookedUpAddr;
            }
            addr = InetAddress.getByName("127.0.0.1");
        }
        if (isMulticastSupported(addr)) {
            return addr;
        } else {
            throw new UnknownHostException("Cannot find address of local host which can be used for multicasting");
        }
    }

    /**
     * Check, whether multicast is supported at all by at least one interface
     *
     * @return true if at least one network interface supports multicast
     */
    public static boolean isMulticastSupported() throws SocketException {
        return getMulticastAddresses().size() != 0;
    }

    /**
     * Check whether the given interface supports multicast and is up
     *
     * @param pNif check whether the given interface supports multicast
     * @return true if multicast is supported and the interface is up
     */
    public static boolean isMulticastSupported(NetworkInterface pNif) {
        return pNif != null && checkMethod(pNif, isUp) && checkMethod(pNif, supportsMulticast);
    }

    /**
     * Check whether the given address' interface supports multicast
     *
     * @param pAddr address to check
     * @return true if the underlying networkinterface is up and supports multicast
     * @throws SocketException
     */
    public static boolean isMulticastSupported(InetAddress pAddr) throws SocketException {
        return isMulticastSupported(NetworkInterface.getByInetAddress(pAddr));
    }

    public static InetAddress findLocalAddressViaNetworkInterface() {
        Enumeration<NetworkInterface> networkInterfaces;
        try {
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            return null;
        }

        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface nif = networkInterfaces.nextElement();
            for (Enumeration<InetAddress> addrEnum = nif.getInetAddresses(); addrEnum.hasMoreElements();) {
                InetAddress interfaceAddress = addrEnum.nextElement();
                if (useInetAddress(nif, interfaceAddress)) {
                    return interfaceAddress;
                }
            }
        }
        return null;
    }

    /**
     * Get all local addresses on which a multicast can be send
     *
     * @return list of all multi cast capable addresses
     */
    public static List<InetAddress> getMulticastAddresses() throws SocketException {
        Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
        List<InetAddress> ret = new ArrayList<InetAddress>();
        while (nifs.hasMoreElements()) {
            NetworkInterface nif = nifs.nextElement();
            if (checkMethod(nif, supportsMulticast) && checkMethod(nif, isUp)) {
                Enumeration<InetAddress> addresses = nif.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    // TODO: IpV6 support
                    if (!(addr instanceof Inet6Address)) {
                        ret.add(addr);
                    }
                }
            }
        }
        return ret;
    }

    private static Boolean checkMethod(NetworkInterface iface, Method toCheck) {
        if (toCheck != null) {
            try {
                return (Boolean) toCheck.invoke(iface, (Object[]) null);
            } catch (IllegalAccessException e) {
                return false;
            } catch (InvocationTargetException e) {
                return false;
            }
        }
        // Cannot check, hence we assume that is true
        return true;
    }

    private static boolean useInetAddress(NetworkInterface networkInterface, InetAddress interfaceAddress) {
        return checkMethod(networkInterface, isUp) && checkMethod(networkInterface, supportsMulticast) &&
        // TODO: IpV6 support
                !(interfaceAddress instanceof Inet6Address) && !interfaceAddress.isLoopbackAddress();
    }
}

Related

  1. getLocalAddresses()
  2. getLocalAddresses()
  3. getLocalAddresses()
  4. getLocalAddressFromNetworkInterfacesListeningOnPort(int pPort)
  5. getLocalAddressStrings()
  6. getLocalAddrs()
  7. getLocalInet4Address()
  8. getLocalInet4Address()
  9. getLocalInternetProtocolAddress()