Example usage for java.net NetworkInterface getByName

List of usage examples for java.net NetworkInterface getByName

Introduction

In this page you can find the example usage for java.net NetworkInterface getByName.

Prototype

public static NetworkInterface getByName(String name) throws SocketException 

Source Link

Document

Searches for the network interface with the specified name.

Usage

From source file:ws.argo.mcg.GatewaySender.java

boolean joinGroup() {
    boolean success = true;
    InetSocketAddress socketAddress = new InetSocketAddress(multicastAddress, multicastPort);
    try {/*from   ww w  . j  a va  2 s . c o m*/
        // Setup for incoming multicast requests

        maddress = InetAddress.getByName(multicastAddress);

        if (niName != null)
            ni = NetworkInterface.getByName(niName);
        if (ni == null) {
            InetAddress localhost = InetAddress.getLocalHost();
            LOGGER.fine("Network Interface name not specified or incorrect.  Using the NI for localhost "
                    + localhost.getHostAddress());
            ni = NetworkInterface.getByInetAddress(localhost);
        }

        LOGGER.info("Starting GatewaySender:  Receiving mulitcast @ " + multicastAddress + ":" + multicastPort
                + " -- Sending unicast @ " + unicastAddress + ":" + unicastPort);
        this.inboundSocket = new MulticastSocket(multicastPort);
        if (ni == null) { // for some reason NI is still NULL. Not sure why this
                          // happens.
            this.inboundSocket.joinGroup(maddress);
            LOGGER.warning(
                    "Unable to determine the network interface for the localhost address. Check /etc/hosts for weird entry like 127.0.1.1 mapped to DNS name.");
            LOGGER.info("Unknown network interface joined group " + socketAddress.toString());
        } else {
            this.inboundSocket.joinGroup(socketAddress, ni);
            LOGGER.info(ni.getName() + " joined group " + socketAddress.toString());
        }

    } catch (IOException e) {
        StringBuffer buf = new StringBuffer();
        try {
            buf.append("(lb:" + this.ni.isLoopback() + " ");
        } catch (SocketException e2) {
            buf.append("(lb:err ");
        }
        try {
            buf.append("m:" + this.ni.supportsMulticast() + " ");
        } catch (SocketException e3) {
            buf.append("(m:err ");
        }
        try {
            buf.append("p2p:" + this.ni.isPointToPoint() + " ");
        } catch (SocketException e1) {
            buf.append("p2p:err ");
        }
        try {
            buf.append("up:" + this.ni.isUp() + " ");
        } catch (SocketException e1) {
            buf.append("up:err ");
        }
        buf.append("v:" + this.ni.isVirtual() + ") ");

        System.out.println(this.ni.getName() + " " + buf.toString() + ": could not join group "
                + socketAddress.toString() + " --> " + e.toString());

        success = false;
    }
    return success;
}

From source file:es.upv.grc.grcbox.server.GrcBoxServerApplication.java

private static void startServer(String string) throws Exception {
    Component androPiComponent = new Component();
    NetworkInterface iface = NetworkInterface.getByName(string);
    if (iface == null) {
        System.err.println("ERROR: No inner  interface called " + string + " exists");
        System.exit(-1);/*  www. jav  a2 s. c  om*/
    }
    List<InterfaceAddress> addresses = iface.getInterfaceAddresses();
    InterfaceAddress addr = null;
    for (InterfaceAddress interfaceAddress : addresses) {
        if (interfaceAddress.getAddress() instanceof Inet4Address) {
            addr = interfaceAddress;
            break;
        }
    }

    if (addr != null) {
        Server server = androPiComponent.getServers().add(Protocol.HTTP, addr.getAddress().getHostAddress(),
                8080);
        androPiComponent.getDefaultHost().attach(new GrcBoxServerApplication());
        androPiComponent.start();
    } else {
        LOG.severe("The server could not be initialized. No Ipv4 address on innerinterface present");
        System.exit(1);
    }
}

From source file:ws.argo.mcg.GatewayReceiver.java

boolean joinGroup() {
    boolean success = true;
    InetSocketAddress socketAddress = new InetSocketAddress(multicastAddress, multicastPort);
    try {/*from  w w  w  . j  a  va2 s .c  o  m*/
        // Setup for incoming multicast requests
        maddress = InetAddress.getByName(multicastAddress);

        if (niName != null)
            ni = NetworkInterface.getByName(niName);

        if (ni == null) {
            InetAddress localhost = InetAddress.getLocalHost();
            LOGGER.fine("Network Interface name not specified.  Using the NI for localhost "
                    + localhost.getHostAddress());
            ni = NetworkInterface.getByInetAddress(localhost);
        }

        this.outboundSocket = new MulticastSocket(multicastPort);
        // for some reason NI is still NULL. Check /etc/hosts
        if (ni == null) {
            this.outboundSocket.joinGroup(maddress);
            LOGGER.warning(
                    "Unable to determine the network interface for the localhost address.  Check /etc/hosts for wierd entry like 127.0.1.1 mapped to DNS name.");
            LOGGER.info("Unknown network interface joined group " + socketAddress.toString());
        } else {
            this.outboundSocket.joinGroup(socketAddress, ni);
            LOGGER.info(ni.getName() + " joined group " + socketAddress.toString());
        }
    } catch (IOException e) {
        StringBuffer buf = new StringBuffer();
        try {
            buf.append("(lb:" + this.ni.isLoopback() + " ");
        } catch (SocketException e2) {
            buf.append("(lb:err ");
        }
        try {
            buf.append("m:" + this.ni.supportsMulticast() + " ");
        } catch (SocketException e3) {
            buf.append("(m:err ");
        }
        try {
            buf.append("p2p:" + this.ni.isPointToPoint() + " ");
        } catch (SocketException e1) {
            buf.append("p2p:err ");
        }
        try {
            buf.append("up:" + this.ni.isUp() + " ");
        } catch (SocketException e1) {
            buf.append("up:err ");
        }
        buf.append("v:" + this.ni.isVirtual() + ") ");

        System.out.println(this.ni.getName() + " " + buf.toString() + ": could not join group "
                + socketAddress.toString() + " --> " + e.toString());

        success = false;
    }
    return success;
}

From source file:com.jagornet.dhcp.client.GenerateTestConfig.java

private boolean parseOptions(String args[]) {
    try {//from w  w w  .  j  av  a 2  s  .  com
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("?")) {
            return false;
        }
        if (cmd.hasOption("f")) {
            filename = cmd.getOptionValue("f");
        } else {
            filename = "dhcpserver-test-config.xml";
        }
        if (cmd.hasOption("i")) {
            networkInterface = NetworkInterface.getByName(cmd.getOptionValue("i"));
        } else {
            networkInterface = NetworkInterface.getNetworkInterfaces().nextElement();
        }

        Enumeration<InetAddress> ipAddrs = networkInterface.getInetAddresses();
        while (ipAddrs.hasMoreElements()) {
            InetAddress ipAddr = ipAddrs.nextElement();
            if ((ipAddr instanceof Inet4Address) && !ipAddr.isLinkLocalAddress()
                    && !ipAddr.isLoopbackAddress()) {
                ipv4Address = ipAddr;
                return true;
            }
        }
        System.err.println("No IPv4 address found for interface: " + networkInterface.getName());
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}

From source file:com.redhat.rhn.domain.monitoring.satcluster.SatClusterFactory.java

/**
 * Create a new SatCluster (scout)//from w ww  .  jav a 2 s  .  co m
 * @param user who creates the Scout
 * @return new instance
 */
public static SatCluster createSatCluster(User user) {
    SatCluster retval = new SatCluster();
    CommandTarget ct = new CommandTarget();
    ct.setOrg(user.getOrg());
    ct.setTargetType("cluster");
    retval.setCommandTarget(ct);
    retval.setOrg(user.getOrg());
    retval.setPhysicalLocation(PHYSICAL_LOCATION);
    retval.setTargetType(ct.getTargetType());
    retval.setDeployed("1");
    retval.setLastUpdateUser(user.getLogin());
    retval.setLastUpdateDate(new Date());
    try {
        InetAddress ip = InetAddress.getLocalHost();
        boolean haveIpv4 = ip instanceof Inet4Address;
        if (haveIpv4) {
            retval.setVip(ip.getHostAddress());
        } else {
            retval.setVip6(ip.getHostAddress());
        }
        NetworkInterface ni = NetworkInterface.getByInetAddress(ip);
        for (InterfaceAddress ifa : ni.getInterfaceAddresses()) {
            InetAddress ia = ifa.getAddress();
            if ((ia instanceof Inet4Address) != haveIpv4) {
                if (haveIpv4) {
                    retval.setVip6(ia.getHostAddress());
                } else {
                    retval.setVip(ia.getHostAddress());
                }
                break;
            }
        }
    } catch (Exception e) {
        log.warn("Failed to find out IP host addresses. " + "Setting loopback IPs instead.");
        try {
            NetworkInterface ni = NetworkInterface.getByName("lo");
            for (InterfaceAddress ifa : ni.getInterfaceAddresses()) {
                InetAddress ia = ifa.getAddress();
                if (ia instanceof Inet4Address) {
                    if (StringUtils.isEmpty(retval.getVip())) {
                        retval.setVip(ia.getHostAddress());
                    }
                } else { //IPv6
                    if (StringUtils.isEmpty(retval.getVip6())) {
                        retval.setVip6(ia.getHostAddress());
                    }
                }
            }
        } catch (SocketException se) {
            log.fatal("Failed to find out loopback IPs.");
            se.printStackTrace();
        }
    }
    return retval;
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.transport.TransportUtils.java

public static Map<String, String> getInterfaceIPMap() throws TransportHandlerException {

    Map<String, String> interfaceToIPMap = new HashMap<String, String>();
    Enumeration<NetworkInterface> networkInterfaces;
    String networkInterfaceName = "";
    String ipAddress;/*from w w w . j  a  va  2s  . c o m*/

    try {
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException exception) {
        String errorMsg = "Error encountered whilst trying to get the list of network-interfaces";
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, exception);
    }

    try {
        for (; networkInterfaces.hasMoreElements();) {
            networkInterfaceName = networkInterfaces.nextElement().getName();

            if (log.isDebugEnabled()) {
                log.debug("Network Interface: " + networkInterfaceName);
                log.debug("------------------------------------------");
            }

            Enumeration<InetAddress> interfaceIPAddresses = NetworkInterface.getByName(networkInterfaceName)
                    .getInetAddresses();

            for (; interfaceIPAddresses.hasMoreElements();) {
                ipAddress = interfaceIPAddresses.nextElement().getHostAddress();

                if (log.isDebugEnabled()) {
                    log.debug("IP Address: " + ipAddress);
                }

                if (TransportUtils.validateIPv4(ipAddress)) {
                    interfaceToIPMap.put(networkInterfaceName, ipAddress);
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("------------------------------------------");
            }
        }
    } catch (SocketException exception) {
        String errorMsg = "Error encountered whilst trying to get the IP Addresses of the network "
                + "interface: " + networkInterfaceName;
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, exception);
    }

    return interfaceToIPMap;
}

From source file:ezbake.services.graph.archive.TransactionIdGenerator.java

private static byte[] getMacAddress(String interfaceName) {
    Preconditions.checkArgument(interfaceName != null, "Interface name cannot be null.");
    try {/* www .j  a  v  a 2  s. co m*/
        NetworkInterface network = NetworkInterface.getByName(interfaceName);
        if (network == null) {
            throw new IllegalStateException("Can't get interface: " + interfaceName);
        }
        byte[] mac = network.getHardwareAddress();
        return (mac != null) ? mac : MAC_ADDRESS_DEFAULT;
    } catch (SocketException ex) {
        throw new IllegalStateException("Can't get MAC address: " + interfaceName);
    }
}

From source file:com.chiralBehaviors.slp.hive.configuration.BroadcastConfiguration.java

public Tuple<NetworkInterface, InetSocketAddress> getNetworkInterface() throws SocketException {
    if (networkInterface == null) {
        for (Enumeration<NetworkInterface> intfs = NetworkInterface.getNetworkInterfaces(); intfs
                .hasMoreElements();) {/*from  w  w w.  j ava  2  s  . c o  m*/
            NetworkInterface iface = intfs.nextElement();
            InetSocketAddress broadcastAddress = getBroadcastAddress(iface);
            if (broadcastAddress != null) {
                return new Tuple<NetworkInterface, InetSocketAddress>(iface, broadcastAddress);
            }
        }
        throw new IllegalStateException("No interface supporting broadcast was discovered");
    }
    NetworkInterface iface = NetworkInterface.getByName(networkInterface);
    if (iface == null) {
        throw new IllegalArgumentException(
                String.format("Cannot find network interface: %s ", networkInterface));
    }
    InetSocketAddress broadcastAddress = getBroadcastAddress(iface);
    if (broadcastAddress == null) {
        throw new IllegalStateException(
                String.format("The interface [%s] does not broadcast", networkInterface));
    }
    return new Tuple<NetworkInterface, InetSocketAddress>(iface, broadcastAddress);
}

From source file:it.evilsocket.dsploit.net.Network.java

public Network(Context context) throws NoRouteToHostException, SocketException, UnknownHostException {
    mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    mInfo = mWifiManager.getDhcpInfo();/*from www.  ja v a  2  s . co  m*/
    mWifiInfo = mWifiManager.getConnectionInfo();
    mLocal = new IP4Address(mInfo.ipAddress);
    mGateway = new IP4Address(mInfo.gateway);
    mNetmask = getNetmask();
    mBase = new IP4Address(mInfo.netmask & mInfo.gateway);

    if (isConnected() == false)
        throw new NoRouteToHostException("Not connected to any WiFi access point.");

    else {
        try {
            mInterface = NetworkInterface.getByInetAddress(getLocalAddress());
            if (mInterface == null)
                throw new IllegalStateException("Error retrieving network interface.");
        } catch (SocketException e) {
            System.errorLogging(e);
            /*
             * Issue #26: Initialization error in ColdFusionX ROM
                 * 
                 * It seems it's a ROM issue which doesn't correctly populate device descriptors.
                 * This rom maps the default wifi interface to a generic usb device 
                 * ( maybe it's missing the specific interface driver ), which is obviously not, and
                 * it all goes shit, use an alternative method to obtain the interface object.
                 */
            mInterface = NetworkInterface.getByName(java.lang.System.getProperty("wifi.interface", "wlan0"));

            if (mInterface == null)
                throw e;
        }
    }
}

From source file:org.csploit.android.net.Network.java

public Network(Context context) throws SocketException, UnknownHostException {
    mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    mInfo = mWifiManager.getDhcpInfo();//from   w w w  . j av a 2  s .co  m
    mWifiInfo = mWifiManager.getConnectionInfo();
    mLocal = new IP4Address(mInfo.ipAddress);
    mGateway = new IP4Address(mInfo.gateway);
    mNetmask = getNetmask();
    mBase = new IP4Address(mInfo.netmask & mInfo.gateway);

    if (isConnected() == false)
        throw new NoRouteToHostException("Not connected to any WiFi access point.");

    else {
        try {
            mInterface = NetworkInterface.getByInetAddress(getLocalAddress());
            if (mInterface == null)
                throw new IllegalStateException("Error retrieving network interface.");
        } catch (SocketException e) {
            System.errorLogging(e);
            /*
             * Issue #26: Initialization error in ColdFusionX ROM
                 * 
                 * It seems it's a ROM issue which doesn't correctly populate device descriptors.
                 * This rom maps the default wifi interface to a generic usb device 
                 * ( maybe it's missing the specific interface driver ), which is obviously not, and
                 * it all goes shit, use an alternative method to obtain the interface object.
                 */
            mInterface = NetworkInterface.getByName(java.lang.System.getProperty("wifi.interface", "wlan0"));

            if (mInterface == null)
                throw e;
        }
    }
}