Search in sources :

Example 6 with InterfaceAddress

use of java.net.InterfaceAddress in project openhab1-addons by openhab.

the class MaxCubeDiscover method discoverIp.

/**
     * Automatic UDP discovery of a MAX!Cube
     * 
     * @return if the cube is found, returns the IP address as a string. Otherwise returns null
     */
public static final String discoverIp() {
    String maxCubeIP = null;
    String maxCubeName = null;
    String rfAddress = null;
    Logger logger = LoggerFactory.getLogger(MaxCubeDiscover.class);
    DatagramSocket bcReceipt = null;
    DatagramSocket bcSend = null;
    // Find the MaxCube using UDP broadcast
    try {
        bcSend = new DatagramSocket();
        bcSend.setBroadcast(true);
        byte[] sendData = "eQ3Max*\0**********I".getBytes();
        // Broadcast the message over all the network interfaces
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                InetAddress[] broadcast = new InetAddress[2];
                broadcast[0] = InetAddress.getByName("224.0.0.1");
                broadcast[1] = interfaceAddress.getBroadcast();
                for (InetAddress bc : broadcast) {
                    // Send the broadcast package!
                    if (bc != null) {
                        try {
                            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, bc, 23272);
                            bcSend.send(sendPacket);
                        } catch (IOException e) {
                            logger.debug("IO error during MAX! Cube discovery: {}", e.getMessage());
                        } catch (Exception e) {
                            logger.debug(e.getMessage());
                            logger.debug(Utils.getStackTrace(e));
                        }
                        logger.trace("Request packet sent to: {} Interface: {}", bc.getHostAddress(), networkInterface.getDisplayName());
                    }
                }
            }
        }
        logger.trace("Done looping over all network interfaces. Now waiting for a reply!");
        bcSend.close();
        bcReceipt = new DatagramSocket(23272);
        bcReceipt.setReuseAddress(true);
        // Wait for a response
        byte[] recvBuf = new byte[15000];
        DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
        bcReceipt.receive(receivePacket);
        // We have a response
        logger.trace("Broadcast response from server: {}", receivePacket.getAddress());
        // Check if the message is correct
        String message = new String(receivePacket.getData()).trim();
        if (message.startsWith("eQ3Max")) {
            maxCubeIP = receivePacket.getAddress().getHostAddress();
            maxCubeName = message.substring(0, 8);
            rfAddress = message.substring(8, 18);
            logger.debug("Found at: {}", maxCubeIP);
            logger.debug("Name    : {}", maxCubeName);
            logger.debug("Serial  : {}", rfAddress);
            logger.trace("Message : {}", message);
        } else {
            logger.info("No Max!Cube gateway found on network");
        }
    } catch (IOException e) {
        logger.debug("IO error during MAX! Cube discovery: {}", e.getMessage());
    } catch (Exception e) {
        logger.debug(e.getMessage());
        logger.debug(Utils.getStackTrace(e));
    } finally {
        try {
            if (bcReceipt != null) {
                bcReceipt.close();
            }
        } catch (Exception e) {
            logger.debug(e.toString());
        }
        try {
            if (bcSend != null) {
                bcSend.close();
            }
        } catch (Exception e) {
            logger.debug(e.toString());
        }
    }
    return maxCubeIP;
}
Also used : DatagramSocket(java.net.DatagramSocket) InterfaceAddress(java.net.InterfaceAddress) DatagramPacket(java.net.DatagramPacket) NetworkInterface(java.net.NetworkInterface) IOException(java.io.IOException) Logger(org.slf4j.Logger) InetAddress(java.net.InetAddress) IOException(java.io.IOException)

Example 7 with InterfaceAddress

use of java.net.InterfaceAddress in project android_frameworks_base by ResurrectionRemix.

the class NetworkManagementService method modifyNat.

private void modifyNat(String action, String internalInterface, String externalInterface) throws SocketException {
    final Command cmd = new Command("nat", action, internalInterface, externalInterface);
    final NetworkInterface internalNetworkInterface = NetworkInterface.getByName(internalInterface);
    if (internalNetworkInterface == null) {
        cmd.appendArg("0");
    } else {
        // Don't touch link-local routes, as link-local addresses aren't routable,
        // kernel creates link-local routes on all interfaces automatically
        List<InterfaceAddress> interfaceAddresses = excludeLinkLocal(internalNetworkInterface.getInterfaceAddresses());
        cmd.appendArg(interfaceAddresses.size());
        for (InterfaceAddress ia : interfaceAddresses) {
            InetAddress addr = NetworkUtils.getNetworkPart(ia.getAddress(), ia.getNetworkPrefixLength());
            cmd.appendArg(addr.getHostAddress() + "/" + ia.getNetworkPrefixLength());
        }
    }
    try {
        mConnector.execute(cmd);
    } catch (NativeDaemonConnectorException e) {
        throw e.rethrowAsParcelableException();
    }
}
Also used : Command(com.android.server.NativeDaemonConnector.Command) InterfaceAddress(java.net.InterfaceAddress) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 8 with InterfaceAddress

use of java.net.InterfaceAddress in project android_frameworks_base by ResurrectionRemix.

the class LinkAddressTest method testConstructors.

public void testConstructors() throws SocketException {
    LinkAddress address;
    // Valid addresses work as expected.
    address = new LinkAddress(V4_ADDRESS, 25);
    assertEquals(V4_ADDRESS, address.getAddress());
    assertEquals(25, address.getPrefixLength());
    assertEquals(0, address.getFlags());
    assertEquals(RT_SCOPE_UNIVERSE, address.getScope());
    address = new LinkAddress(V6_ADDRESS, 127);
    assertEquals(V6_ADDRESS, address.getAddress());
    assertEquals(127, address.getPrefixLength());
    assertEquals(0, address.getFlags());
    assertEquals(RT_SCOPE_UNIVERSE, address.getScope());
    // Nonsensical flags/scopes or combinations thereof are acceptable.
    address = new LinkAddress(V6 + "/64", IFA_F_DEPRECATED | IFA_F_PERMANENT, RT_SCOPE_LINK);
    assertEquals(V6_ADDRESS, address.getAddress());
    assertEquals(64, address.getPrefixLength());
    assertEquals(IFA_F_DEPRECATED | IFA_F_PERMANENT, address.getFlags());
    assertEquals(RT_SCOPE_LINK, address.getScope());
    address = new LinkAddress(V4 + "/23", 123, 456);
    assertEquals(V4_ADDRESS, address.getAddress());
    assertEquals(23, address.getPrefixLength());
    assertEquals(123, address.getFlags());
    assertEquals(456, address.getScope());
    // InterfaceAddress doesn't have a constructor. Fetch some from an interface.
    List<InterfaceAddress> addrs = NetworkInterface.getByName("lo").getInterfaceAddresses();
    // We expect to find 127.0.0.1/8 and ::1/128, in any order.
    LinkAddress ipv4Loopback, ipv6Loopback;
    assertEquals(2, addrs.size());
    if (addrs.get(0).getAddress() instanceof Inet4Address) {
        ipv4Loopback = new LinkAddress(addrs.get(0));
        ipv6Loopback = new LinkAddress(addrs.get(1));
    } else {
        ipv4Loopback = new LinkAddress(addrs.get(1));
        ipv6Loopback = new LinkAddress(addrs.get(0));
    }
    assertEquals(NetworkUtils.numericToInetAddress("127.0.0.1"), ipv4Loopback.getAddress());
    assertEquals(8, ipv4Loopback.getPrefixLength());
    assertEquals(NetworkUtils.numericToInetAddress("::1"), ipv6Loopback.getAddress());
    assertEquals(128, ipv6Loopback.getPrefixLength());
    // Null addresses are rejected.
    try {
        address = new LinkAddress(null, 24);
        fail("Null InetAddress should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        address = new LinkAddress((String) null, IFA_F_PERMANENT, RT_SCOPE_UNIVERSE);
        fail("Null string should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        address = new LinkAddress((InterfaceAddress) null);
        fail("Null string should cause NullPointerException");
    } catch (NullPointerException expected) {
    }
    // Invalid prefix lengths are rejected.
    try {
        address = new LinkAddress(V4_ADDRESS, -1);
        fail("Negative IPv4 prefix length should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        address = new LinkAddress(V6_ADDRESS, -1);
        fail("Negative IPv6 prefix length should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        address = new LinkAddress(V4_ADDRESS, 33);
        fail("/33 IPv4 prefix length should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        address = new LinkAddress(V4 + "/33", IFA_F_PERMANENT, RT_SCOPE_UNIVERSE);
        fail("/33 IPv4 prefix length should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        address = new LinkAddress(V6_ADDRESS, 129, IFA_F_PERMANENT, RT_SCOPE_UNIVERSE);
        fail("/129 IPv6 prefix length should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        address = new LinkAddress(V6 + "/129", IFA_F_PERMANENT, RT_SCOPE_UNIVERSE);
        fail("/129 IPv6 prefix length should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    // Multicast addresses are rejected.
    try {
        address = new LinkAddress("224.0.0.2/32");
        fail("IPv4 multicast address should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
    try {
        address = new LinkAddress("ff02::1/128");
        fail("IPv6 multicast address should cause IllegalArgumentException");
    } catch (IllegalArgumentException expected) {
    }
}
Also used : LinkAddress(android.net.LinkAddress) Inet4Address(java.net.Inet4Address) InterfaceAddress(java.net.InterfaceAddress)

Example 9 with InterfaceAddress

use of java.net.InterfaceAddress in project CloudStack-archive by CloudStack-extras.

the class NetUtils method getLocalCidrs.

public static String[] getLocalCidrs() {
    String defaultHostIp = getDefaultHostIp();
    List<String> cidrList = new ArrayList<String>();
    try {
        for (NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
                for (InterfaceAddress address : ifc.getInterfaceAddresses()) {
                    InetAddress addr = address.getAddress();
                    int prefixLength = address.getNetworkPrefixLength();
                    if (prefixLength < 32 && prefixLength > 0) {
                        String ip = ipFromInetAddress(addr);
                        if (ip.equalsIgnoreCase(defaultHostIp))
                            cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
                    }
                }
            }
        }
    } catch (SocketException e) {
        s_logger.warn("UnknownHostException in getLocalCidrs().", e);
    }
    return cidrList.toArray(new String[0]);
}
Also used : SocketException(java.net.SocketException) InterfaceAddress(java.net.InterfaceAddress) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 10 with InterfaceAddress

use of java.net.InterfaceAddress in project CloudStack-archive by CloudStack-extras.

the class NetUtils method getNetworkParams.

public static String[] getNetworkParams(NetworkInterface nic) {
    List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
        return null;
    }
    InterfaceAddress addr = null;
    for (InterfaceAddress iaddr : addrs) {
        InetAddress inet = iaddr.getAddress();
        if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) {
            addr = iaddr;
            break;
        }
    }
    if (addr == null) {
        return null;
    }
    String[] result = new String[3];
    result[0] = addr.getAddress().getHostAddress();
    try {
        byte[] mac = nic.getHardwareAddress();
        result[1] = byte2Mac(mac);
    } catch (Exception e) {
    }
    result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
    return result;
}
Also used : InterfaceAddress(java.net.InterfaceAddress) InetAddress(java.net.InetAddress) URISyntaxException(java.net.URISyntaxException) SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException)

Aggregations

InterfaceAddress (java.net.InterfaceAddress)94 NetworkInterface (java.net.NetworkInterface)63 InetAddress (java.net.InetAddress)52 Inet4Address (java.net.Inet4Address)26 SocketException (java.net.SocketException)24 Test (org.junit.Test)19 ArrayList (java.util.ArrayList)15 IOException (java.io.IOException)9 UnknownHostException (java.net.UnknownHostException)7 NotifyListener (net.mm2d.upnp.SsdpNotifyReceiver.NotifyListener)7 Command (com.android.server.NativeDaemonConnector.Command)6 Inet6Address (java.net.Inet6Address)6 LinkAddress (android.net.LinkAddress)5 DatagramPacket (java.net.DatagramPacket)5 InetSocketAddress (java.net.InetSocketAddress)4 List (java.util.List)4 SharedPreferences (android.content.SharedPreferences)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Enumeration (java.util.Enumeration)3 LinkedList (java.util.LinkedList)3