Example usage for java.net InterfaceAddress getAddress

List of usage examples for java.net InterfaceAddress getAddress

Introduction

In this page you can find the example usage for java.net InterfaceAddress getAddress.

Prototype

public InetAddress getAddress() 

Source Link

Document

Returns an InetAddress for this address.

Usage

From source file:fr.inria.ucn.collectors.NetworkStateCollector.java

private JSONArray getIfconfig(Map<String, JSONObject> stats) throws JSONException {
    JSONArray ifaces = new JSONArray();

    // make sure the stats is read
    networkStats();//from  www  . j a v a 2 s  . co  m

    Enumeration<NetworkInterface> en = null;
    try {
        en = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        Log.d(Constants.LOGTAG, "failed to list interfaces", e);
    }

    if (en != null) {
        while (en.hasMoreElements()) {
            NetworkInterface intf = en.nextElement();

            JSONObject iface = new JSONObject();
            iface.put("display_name", intf.getDisplayName());
            iface.put("name", intf.getName());
            iface.put("is_virtual", intf.isVirtual());
            iface.put("stats", stats.get(intf.getName()));

            try {
                iface.put("mtu", intf.getMTU());
                iface.put("is_loopback", intf.isLoopback());
                iface.put("is_ptop", intf.isPointToPoint());
                iface.put("is_up", intf.isUp());
            } catch (SocketException e) {
                Log.d(Constants.LOGTAG, "failed to read interface data", e);
            }

            JSONArray ips = new JSONArray();
            List<InterfaceAddress> ilist = intf.getInterfaceAddresses();
            for (InterfaceAddress ia : ilist) {
                ips.put(ia.getAddress().getHostAddress());
            }
            iface.put("addresses", ips);

            ifaces.put(iface);
        }
    } else {
        for (String name : stats.keySet()) {
            JSONObject iface = new JSONObject();
            iface.put("name", name);
            iface.put("stats", stats.get(name));
            ifaces.put(iface);
        }
    }

    return ifaces;
}

From source file:com.jagornet.dhcpv6.server.DhcpV6Server.java

/**
 * Gets the IPv6 network interfaces for the supplied interface names.
 * //  ww  w .j av  a  2  s  . co  m
 * @param ifnames the interface names to locate NetworkInterfaces by
 * 
 * @return the list of NetworkInterfaces that are up, support multicast,
 * and have at least one IPv6 address configured
 * 
 * @throws SocketException the socket exception
 */
private List<NetworkInterface> getIPv6NetIfs(String[] ifnames) throws SocketException {
    List<NetworkInterface> netIfs = new ArrayList<NetworkInterface>();
    for (String ifname : ifnames) {
        if (ifname.equals("*")) {
            return getAllIPv6NetIfs();
        }
        NetworkInterface netIf = NetworkInterface.getByName(ifname);
        if (netIf == null) {
            // if not found by name, see if the name is actually an address
            try {
                InetAddress ipaddr = InetAddress.getByName(ifname);
                netIf = NetworkInterface.getByInetAddress(ipaddr);
            } catch (UnknownHostException ex) {
                log.warn("Unknown interface: " + ifname + ": " + ex);
            }
        }
        if (netIf != null) {
            if (netIf.isUp()) {
                // for multicast, the loopback interface is excluded
                if (netIf.supportsMulticast() && !netIf.isLoopback()) {
                    boolean isV6 = false;
                    List<InterfaceAddress> ifAddrs = netIf.getInterfaceAddresses();
                    for (InterfaceAddress ifAddr : ifAddrs) {
                        if (ifAddr.getAddress() instanceof Inet6Address) {
                            netIfs.add(netIf);
                            isV6 = true;
                            break;
                        }
                    }
                    if (!isV6) {
                        System.err.println("Interface is not configured for IPv6: " + netIf.getDisplayName());
                        return null;
                    }
                } else {
                    System.err.println("Interface does not support multicast: " + netIf.getDisplayName());
                    return null;
                }
            } else {
                System.err.println("Interface is not up: " + netIf.getDisplayName());
                return null;
            }
        } else {
            System.err.println("Interface not found or inactive: " + ifname);
            return null;
        }
    }
    return netIfs;
}

From source file:gov.nrel.bacnet.consumer.BACnet.java

private void initialize(Config config) throws IOException {
    LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(1000);
    RejectedExecutionHandler rejectedExec = new RejectedExecHandler();
    // schedule polling on single threaded service because local device instance is not threadsafe
    execSvc = Executors.newFixedThreadPool(config.getNumThreads());
    //give databus recording 2 threads to match old code
    recorderSvc = new ThreadPoolExecutor(20, 20, 120, TimeUnit.SECONDS, queue, rejectedExec);
    schedSvc = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(config.getNumThreads());
    exec = new OurExecutor(schedSvc, execSvc, recorderSvc);
    String devname = config.getNetworkDevice();
    int device_id = config.getDeviceId();
    NetworkInterface networkinterface = null;

    try {/*from  ww  w.  j  av  a 2s  . c  om*/
        networkinterface = java.net.NetworkInterface.getByName(devname);
    } catch (Exception ex) {
        System.out.println("Unable to open device: " + devname);
        System.exit(-1);
    }

    if (networkinterface == null) {
        System.out.println("Unable to open device: " + devname);
        System.exit(-1);
    }

    List<InterfaceAddress> addresses = networkinterface.getInterfaceAddresses();

    String sbroadcast = null;
    String saddress = null;
    //InterfaceAddress ifaceaddr = null;

    for (InterfaceAddress address : addresses) {
        logger.fine("Evaluating address: " + address.toString());
        if (address.getAddress().getAddress().length == 4) {
            logger.info("Address is ipv4, selecting: " + address.toString());
            sbroadcast = address.getBroadcast().toString().substring(1);
            saddress = address.getAddress().toString().substring(1);
            //ifaceaddr = address;
            break;
        } else {
            logger.info("Address is not ipv4, not selecting: " + address.toString());
        }
    }

    logger.info("Binding to: " + saddress + " " + sbroadcast);

    localDevice = new LocalDevice(device_id, sbroadcast);
    localDevice.setPort(LocalDevice.DEFAULT_PORT);
    localDevice.setTimeout(localDevice.getTimeout() * 3);
    localDevice.setSegTimeout(localDevice.getSegTimeout() * 3);
    try {
        localDevice.initialize();
        localDevice.setRetries(0); //don't retry as it seems to really be a waste.
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    if (config.getSlaveDeviceEnabled()) {
        slaveDeviceTimer = new Timer();
        slaveDeviceTimer.schedule(new gov.nrel.bacnet.SlaveDevice(localDevice, config), 1000,
                config.getSlaveDeviceUpdateInterval() * 1000);
    }

    int counter = 0;

    String username = config.getDatabusUserName();
    String key = config.getDatabusKey();

    logger.info("user=" + username + " key=" + key);

    DatabusSender sender = null;

    if (config.getDatabusEnabled()) {
        sender = new DatabusSender(username, key, execSvc, config.getDatabusUrl(), config.getDatabusPort(),
                true);
    }
    logger.info("databus sender: " + sender);
    writer = new DatabusDataWriter(new DataPointWriter(sender));
    logger.info("databus writer" + writer);
}

From source file:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java

@Override
protected void activate(Map<String, Object> configProperties) {
    super.activate(configProperties);

    broadcastAddresses = new ArrayList<InetSocketAddress>();
    interfaceAddresses = new ArrayList<InetAddress>();

    Enumeration<NetworkInterface> networkInterfaces = null;
    try {/*from ww w .j a  va  2  s.  c o  m*/
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage());
    }
    if (networkInterfaces != null) {
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface iface = networkInterfaces.nextElement();
            try {
                if (iface.isUp() && !iface.isLoopback()) {
                    for (InterfaceAddress ifaceAddr : iface.getInterfaceAddresses()) {
                        if (ifaceAddr.getAddress() instanceof Inet4Address) {
                            logger.debug("Adding '{}' as interface address with MTU {}", ifaceAddr.getAddress(),
                                    iface.getMTU());
                            if (iface.getMTU() > bufferSize) {
                                bufferSize = iface.getMTU();
                            }
                            interfaceAddresses.add(ifaceAddr.getAddress());
                            if (ifaceAddr.getBroadcast() != null) {
                                logger.debug("Adding '{}' as broadcast address", ifaceAddr.getBroadcast());
                                broadcastAddresses
                                        .add(new InetSocketAddress(ifaceAddr.getBroadcast(), BROADCAST_PORT));
                            }
                        }
                    }
                }
            } catch (SocketException e) {
                logger.debug("An exception occurred while discovering LIFX lights : '{}'", e.getMessage());
            }
        }
    }
}

From source file:com.cloud.utils.net.NetUtils.java

public static String[] getNetworkParams(final NetworkInterface nic) {
    final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
        return null;
    }//from   w  w w . j  a v  a 2s  .  c  om
    InterfaceAddress addr = null;
    for (final InterfaceAddress iaddr : addrs) {
        final InetAddress inet = iaddr.getAddress();
        if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress()
                && inet.getAddress().length == 4) {
            addr = iaddr;
            break;
        }
    }
    if (addr == null) {
        return null;
    }
    final String[] result = new String[3];
    result[0] = addr.getAddress().getHostAddress();
    try {
        final byte[] mac = nic.getHardwareAddress();
        result[1] = byte2Mac(mac);
    } catch (final SocketException e) {
        s_logger.debug("Caught exception when trying to get the mac address ", e);
    }

    result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
    return result;
}

From source file:com.cloud.utils.net.NetUtils.java

public static String[] getLocalCidrs() {
    final String defaultHostIp = getDefaultHostIp();

    final List<String> cidrList = new ArrayList<String>();
    try {//from   w w  w  .java2  s.  c  om
        for (final NetworkInterface ifc : IteratorUtil
                .enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
                for (final InterfaceAddress address : ifc.getInterfaceAddresses()) {
                    final InetAddress addr = address.getAddress();
                    final int prefixLength = address.getNetworkPrefixLength();
                    if (prefixLength < MAX_CIDR && prefixLength > 0) {
                        final String ip = ipFromInetAddress(addr);
                        if (ip.equalsIgnoreCase(defaultHostIp)) {
                            cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
                        }
                    }
                }
            }
        }
    } catch (final SocketException e) {
        s_logger.warn("UnknownHostException in getLocalCidrs().", e);
    }

    return cidrList.toArray(new String[0]);
}

From source file:com.hypersocket.client.hosts.HostsFileManager.java

private boolean checkRange(int _8bits, int _16bits, int _24bits) throws SocketException, UnknownHostException {

    Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
    while (e.hasMoreElements()) {
        NetworkInterface net = e.nextElement();
        for (InterfaceAddress i : net.getInterfaceAddresses()) {
            String range = _8bits + "." + _16bits + "." + _24bits;
            if (log.isInfoEnabled()) {
                log.info("Checking interface " + i.toString());
            }/*from www.j a  va2s. c  om*/
            if (i.getNetworkPrefixLength() > 0 && i.getNetworkPrefixLength() <= 31) {

                CIDR c = CIDR4.newCIDR(range + ".0" + "/" + i.getNetworkPrefixLength());

                if (c.contains(i.getAddress())) {
                    if (log.isInfoEnabled()) {
                        log.warn(i.getAddress() + " appears to be in our chosen range " + range + ".0" + "/"
                                + i.getNetworkPrefixLength());
                    }
                    return false;
                }
            }
        }
    }
    return true;
}

From source file:com.vuze.plugin.azVPN_Helper.CheckerCommon.java

public int getNetworkPrefixLength(NetworkInterface networkInterface, InetAddress address) {
    int networkPrefixLength = -1;
    List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
    for (InterfaceAddress interfaceAddress : interfaceAddresses) {
        if (!interfaceAddress.getAddress().equals(address)) {
            continue;
        }//  w w  w. j a v  a 2s.com
        networkPrefixLength = interfaceAddress.getNetworkPrefixLength();
        // JDK-7107883 : getNetworkPrefixLength() does not return correct prefix length
        // networkPrefixLength will be zero on Java <= 7 when there is no
        // Broadcast address.
        // I'm guessing there is no broadcast address returned when mask is 32
        // on linux, but I can't confirm (I've seen it though)
        if (networkPrefixLength == 0 && interfaceAddress.getBroadcast() == null) {
            networkPrefixLength = 32;
        }
    }
    return networkPrefixLength;
}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

private NetworkInterface getIPv4NetIf(String ifname) throws SocketException {
    NetworkInterface netIf = NetworkInterface.getByName(ifname);
    if (netIf == null) {
        // if not found by name, see if the name is actually an address
        try {//from w  w w .j a  v a 2  s  .  com
            InetAddress ipaddr = InetAddress.getByName(ifname);
            netIf = NetworkInterface.getByInetAddress(ipaddr);
        } catch (UnknownHostException ex) {
            log.warn("Unknown interface: " + ifname + ": " + ex);
        }
    }
    if (netIf != null) {
        if (netIf.isUp()) {
            // the loopback interface is excluded
            if (!netIf.isLoopback()) {
                boolean isV4 = false;
                List<InterfaceAddress> ifAddrs = netIf.getInterfaceAddresses();
                for (InterfaceAddress ifAddr : ifAddrs) {
                    if (ifAddr.getAddress() instanceof Inet4Address) {
                        isV4 = true;
                        break;
                    }
                }
                if (!isV4) {
                    System.err.println("Interface is not configured for IPv4: " + netIf);
                    return null;
                }
            } else {
                System.err.println("Interface is loopback: " + netIf);
                return null;
            }
        } else {
            System.err.println("Interface is not up: " + netIf);
            return null;
        }
    } else {
        System.err.println("Interface not found or inactive: " + ifname);
        return null;
    }
    return netIf;
}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

/**
 * Gets the IPv6 network interfaces for the supplied interface names.
 * //from  w  w  w  . j a va 2s  .c o  m
 * @param ifnames the interface names to locate NetworkInterfaces by
 * 
 * @return the list of NetworkInterfaces that are up, support multicast,
 * and have at least one IPv6 address configured
 * 
 * @throws SocketException the socket exception
 */
private List<NetworkInterface> getIPv6NetIfs(String[] ifnames) throws SocketException {
    List<NetworkInterface> netIfs = new ArrayList<NetworkInterface>();
    for (String ifname : ifnames) {
        if (ifname.equals("*")) {
            return getAllIPv6NetIfs();
        }
        NetworkInterface netIf = NetworkInterface.getByName(ifname);
        if (netIf == null) {
            // if not found by name, see if the name is actually an address
            try {
                InetAddress ipaddr = InetAddress.getByName(ifname);
                netIf = NetworkInterface.getByInetAddress(ipaddr);
            } catch (UnknownHostException ex) {
                log.warn("Unknown interface: " + ifname + ": " + ex);
            }
        }
        if (netIf != null) {
            if (netIf.isUp()) {
                // for multicast, the loopback interface is excluded
                if (netIf.supportsMulticast() && !netIf.isLoopback()) {
                    boolean isV6 = false;
                    List<InterfaceAddress> ifAddrs = netIf.getInterfaceAddresses();
                    for (InterfaceAddress ifAddr : ifAddrs) {
                        if (ifAddr.getAddress() instanceof Inet6Address) {
                            netIfs.add(netIf);
                            isV6 = true;
                            break;
                        }
                    }
                    if (!isV6) {
                        System.err.println("Interface is not configured for IPv6: " + netIf);
                        return null;
                    }
                } else {
                    System.err.println("Interface does not support multicast: " + netIf);
                    return null;
                }
            } else {
                System.err.println("Interface is not up: " + netIf);
                return null;
            }
        } else {
            System.err.println("Interface not found or inactive: " + ifname);
            return null;
        }
    }
    return netIfs;
}