Example usage for java.net NetworkInterface getByInetAddress

List of usage examples for java.net NetworkInterface getByInetAddress

Introduction

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

Prototype

public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException 

Source Link

Document

Convenience method to search for a network interface that has the specified Internet Protocol (IP) address bound to it.

Usage

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

boolean joinGroup() {
    boolean success = true;
    InetSocketAddress socketAddress = new InetSocketAddress(multicastAddress, multicastPort);
    try {/*  w w  w .  j  ava2 s . com*/
        // 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:org.sonar.application.config.ClusterSettings.java

private static void ensureLocalAddress(Props props, String key) {
    String ipList = props.value(key);

    if (ipList == null) {
        return;//from w  w w  .jav a  2s . c o m
    }

    stream(ipList.split(",")).filter(StringUtils::isNotBlank).map(StringUtils::trim).forEach(ip -> {
        InetAddress inetAddress = convertToInetAddress(ip, key);
        try {
            if (NetworkInterface.getByInetAddress(inetAddress) == null) {
                throw new MessageException(
                        format("The interface address [%s] of [%s] is not a local address", ip, key));
            }
        } catch (SocketException e) {
            throw new MessageException(
                    format("The interface address [%s] of [%s] is not a local address", ip, key));
        }
    });
}

From source file:org.springframework.vault.authentication.MacAddressUserId.java

@Override
public String createUserId() {

    try {//from  w  w  w .j a v a  2  s  .c  o  m

        NetworkInterface networkInterface = null;
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        if (StringUtils.hasText(networkInterfaceHint)) {

            try {
                networkInterface = getNetworkInterface(Integer.parseInt(networkInterfaceHint), interfaces);
            } catch (NumberFormatException e) {
                networkInterface = getNetworkInterface((networkInterfaceHint), interfaces);
            }
        }

        if (networkInterface == null) {

            if (StringUtils.hasText(networkInterfaceHint)) {
                log.warn(String.format("Did not find a NetworkInterface applying hint %s",
                        networkInterfaceHint));
            }

            InetAddress localHost = InetAddress.getLocalHost();
            networkInterface = NetworkInterface.getByInetAddress(localHost);

            if (networkInterface == null) {
                throw new IllegalStateException(
                        String.format("Cannot determine NetworkInterface for %s", localHost));
            }
        }

        byte[] mac = networkInterface.getHardwareAddress();
        if (mac == null) {
            throw new IllegalStateException(
                    String.format("Network interface %s has no hardware address", networkInterface.getName()));
        }

        return Sha256.toSha256(Sha256.toHexString(mac));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

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 v a2s  . co  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:org.openhab.io.hueemulation.internal.HueEmulationUpnpServer.java

@Override
public void run() {
    MulticastSocket recvSocket = null;
    // since jupnp shares port 1900, lets use a different port to send UDP packets on just to be safe.
    DatagramSocket sendSocket = null;
    byte[] buf = new byte[1000];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while (running) {
        try {//  w w w .ja  v  a 2  s  . co m
            if (discoveryIp != null && discoveryIp.trim().length() > 0) {
                address = InetAddress.getByName(discoveryIp);
            } else {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface ni = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                            address = addr;
                            break;
                        }
                    }
                }
            }
            InetSocketAddress socketAddr = new InetSocketAddress(MULTI_ADDR, UPNP_PORT_RECV);
            recvSocket = new MulticastSocket(UPNP_PORT_RECV);
            recvSocket.joinGroup(socketAddr, NetworkInterface.getByInetAddress(address));
            sendSocket = new DatagramSocket();
            while (running) {
                recvSocket.receive(recv);
                if (recv.getLength() > 0) {
                    String data = new String(recv.getData());
                    logger.trace("Got SSDP Discovery packet from {}:{}", recv.getAddress().getHostAddress(),
                            recv.getPort());
                    if (data.startsWith("M-SEARCH")) {
                        String msg = String.format(discoString, "http://" + address.getHostAddress().toString()
                                + ":" + System.getProperty("org.osgi.service.http.port") + discoPath, usn);
                        DatagramPacket response = new DatagramPacket(msg.getBytes(), msg.length(),
                                recv.getAddress(), recv.getPort());
                        try {
                            logger.trace("Sending to {} : {}", recv.getAddress().getHostAddress(), msg);
                            sendSocket.send(response);
                        } catch (IOException e) {
                            logger.error("Could not send UPNP response", e);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Socket error with UPNP server", e);
        } catch (IOException e) {
            logger.error("IO Error with UPNP server", e);
        } finally {
            IOUtils.closeQuietly(recvSocket);
            IOUtils.closeQuietly(sendSocket);
            if (running) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
            }
        }
    }
}

From source file:uk.ac.horizon.ubihelper.j2se.Server.java

public void init(InetAddress address, int port) {
    protocol = new MyProtocolManager();
    peerConnectionListener = new ProtocolManager.ClientConnectionListener(protocol);
    // create channels
    // create server socket
    try {//from  w  w w .ja v  a 2  s. com
        serverSocketChannel = ServerSocketChannel.open();
        ServerSocket ss = serverSocketChannel.socket();
        ss.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), port));
        serverPort = ss.getLocalPort();
        logger.info("Open server socket on port " + serverPort);
        serverSocketChannel.configureBlocking(false);
    } catch (IOException e) {
        logger.severe("Error opening ServerSocketChannel: " + e.getMessage());
        failed = true;
        return;
    }
    try {
        selector = new PeerConnectionScheduler(serverSocketChannel);
        selector.setListener(selectorListener);
        selector.start();
    } catch (IOException e) {
        logger.severe("Error starting Selector: " + e.getMessage());
        failed = true;
        return;
    }
    // create and advertise with DnsServer
    dns = new DnsServer();
    NetworkInterface ni = null;
    try {
        ni = NetworkInterface.getByInetAddress(address);//DnsClient.getFirstActiveInterface();
    } catch (Exception e) {
        logger.severe("Could not get NetworkInterface for " + address + ": " + e);
    }
    dns.setNeworkInterface(ni);
    InetAddress ip = getInetAddress(ni);
    logger.info("Binding for multicast to " + ip.getHostAddress());

    id = ip.getHostAddress() + ":" + serverPort;

    String servicename = DnsUtils.getServiceDiscoveryName();
    String name = ip.getHostAddress();
    SrvData srv = new SrvData(1, 1, serverPort, name);
    logger.info("Discoverable " + name + " as " + servicename);
    dns.add(new DnsProtocol.RR(servicename, DnsProtocol.TYPE_SRV, DnsProtocol.CLASS_IN, DEFAULT_TTL,
            DnsProtocol.srvToData(srv)));

    String instancename = "Server on " + ip;
    logger.info("Discoverable as " + instancename + " " + servicename);
    DnsProtocol.RR ptrRR = new DnsProtocol.RR(servicename, DnsProtocol.TYPE_PTR, DnsProtocol.CLASS_IN,
            DEFAULT_TTL, DnsProtocol.ptrToData(instancename, servicename));
    dns.add(ptrRR);

    dns.start();
}

From source file:org.openhab.binding.opensprinkler.discovery.OpenSprinklerDiscoveryService.java

/**
 * Provide a string list of all the IP addresses associated with the network interfaces on
 * this machine./*from   w  w  w  .  j  a v a  2s  .  com*/
 *
 * @return String list of IP addresses.
 * @throws UnknownHostException
 * @throws SocketException
 */
private List<String> getIpAddressScanList() throws UnknownHostException, SocketException {
    List<String> results = new ArrayList<String>();

    InetAddress localHost = InetAddress.getLocalHost();
    NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);

    for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
        InetAddress ipAddress = address.getAddress();

        String cidrSubnet = ipAddress.getHostAddress() + "/" + DISCOVERY_SUBNET_MASK;

        /* Apache Subnet Utils only supports IP v4 for creating string list of IP's */
        if (ipAddress instanceof Inet4Address) {
            logger.debug("Found interface IPv4 address to scan: {}", cidrSubnet);

            SubnetUtils utils = new SubnetUtils(cidrSubnet);

            results.addAll(Arrays.asList(utils.getInfo().getAllAddresses()));
        } else if (ipAddress instanceof Inet6Address) {
            logger.debug("Found interface IPv6 address to scan: {}", cidrSubnet);
        } else {
            logger.debug("Found interface unknown IP type address to scan: {}", cidrSubnet);
        }
    }

    return results;
}

From source file:ws.argo.DemoWebClient.Browser.BrowserController.java

/**
 * Return the ip info of where the web host lives that supports the browser
 * app./*ww  w  . ja  v  a2s. c  om*/
 * 
 * @return the ip addr info
 * @throws UnknownHostException if something goes wrong
 */
@GET
@Path("/ipAddrInfo")
public String getIPAddrInfo() throws UnknownHostException {

    Properties clientProps = getPropeSenderProps();

    StringBuffer buf = new StringBuffer();

    InetAddress localhost = null;
    NetworkInterface ni = null;
    try {
        localhost = InetAddress.getLocalHost();
        LOGGER.debug("Network Interface name not specified.  Using the NI for localhost "
                + localhost.getHostAddress());
        ni = NetworkInterface.getByInetAddress(localhost);
    } catch (UnknownHostException | SocketException e) {
        LOGGER.error("Error occured dealing with network interface name lookup ", e);

    }

    buf.append("<p>").append("<span style='color: red'> IP Address: </span>")
            .append(localhost.getHostAddress());
    buf.append("<span style='color: red'> Host name: </span>").append(localhost.getCanonicalHostName());
    if (ni == null) {
        buf.append("<span style='color: red'> Network Interface is NULL </span>");
    } else {
        buf.append("<span style='color: red'> Network Interface name: </span>").append(ni.getDisplayName());
    }
    buf.append("</p><p>");
    buf.append("Sending probes to " + respondToAddresses.size() + " addresses -  ");
    for (ProbeRespondToAddress rta : respondToAddresses) {
        buf.append("<span style='color: red'> Probe to: </span>")
                .append(rta.respondToAddress + ":" + rta.respondToPort);
    }
    buf.append("</p>");

    return buf.toString();
}

From source file:org.openhab.binding.globalcache.handler.GlobalCacheHandler.java

@Override
public void initialize() {
    logger.debug("Initializing thing {}", thingID());
    try {/*w w w  .  j  ava 2s  .c  om*/
        ifAddress = InetAddress.getByName(NetUtil.getLocalIpv4HostAddress());
        logger.debug("Handler using address {} on network interface {}", ifAddress.getHostAddress(),
                NetworkInterface.getByInetAddress(ifAddress).getName());
    } catch (SocketException e) {
        logger.error("Handler got Socket exception creating multicast socket: {}", e.getMessage());
        markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
                "No suitable network interface");
        return;
    } catch (UnknownHostException e) {
        logger.error("Handler got UnknownHostException getting local IPv4 network interface: {}",
                e.getMessage());
        markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
                "No suitable network interface");
        return;
    }
    scheduledFuture = scheduledExecutorService.schedule(commandProcessor, 2, TimeUnit.SECONDS);
}

From source file:com.ikon.servlet.ValidateLicenseServlet.java

/**
 * get MacId of the server./*from  w ww. j av a 2 s . com*/
 * @return
 * @throws IOException
 */
static String getMacAddress() throws IOException {
    InetAddress inetAddress;
    NetworkInterface networkInterface;
    StringBuilder sb = new StringBuilder();

    try {
        inetAddress = InetAddress.getLocalHost();
        networkInterface = NetworkInterface.getByInetAddress(inetAddress);
        byte[] mac = networkInterface.getHardwareAddress();

        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
        }
    } catch (UnknownHostException e) {
        throw new IOException("Unknown Host. Please try again later.");
    } catch (SocketException e) {
        throw new IOException("Could not connect to the socket. Please try again later.");
    }
    return sb.toString();
}