Search in sources :

Example 26 with InterfaceAddress

use of java.net.InterfaceAddress in project smarthome by eclipse.

the class NetUtil method getAllInterfaceAddresses.

/**
 * Gets every IPv4+IPv6 Address on each Interface except the loopback interface.
 * The Address format is in the CIDR notation which is ip/prefix-length e.g. 129.31.31.1/24.
 *
 * Example to get a list of only IPv4 addresses in string representation:
 * List<String> l = getAllInterfaceAddresses().stream().filter(a->a.getAddress() instanceof
 * Inet4Address).map(a->a.getAddress().getHostAddress()).collect(Collectors.toList());
 *
 * @return The collected IPv4 and IPv6 Addresses
 */
public static Collection<CidrAddress> getAllInterfaceAddresses() {
    Collection<CidrAddress> interfaceIPs = new ArrayList<>();
    Enumeration<NetworkInterface> en;
    try {
        en = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException ex) {
        LOGGER.error("Could not find interface IP addresses: {}", ex.getMessage(), ex);
        return interfaceIPs;
    }
    while (en.hasMoreElements()) {
        NetworkInterface networkInterface = en.nextElement();
        try {
            if (!networkInterface.isUp() || networkInterface.isLoopback()) {
                continue;
            }
        } catch (SocketException ignored) {
            continue;
        }
        for (InterfaceAddress cidr : networkInterface.getInterfaceAddresses()) {
            final InetAddress address = cidr.getAddress();
            // NetworkInterface.getInterfaceAddresses() should return only non-null
            assert address != null;
            // addresses
            interfaceIPs.add(new CidrAddress(address, cidr.getNetworkPrefixLength()));
        }
    }
    return interfaceIPs;
}
Also used : SocketException(java.net.SocketException) InterfaceAddress(java.net.InterfaceAddress) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 27 with InterfaceAddress

use of java.net.InterfaceAddress in project smarthome by eclipse.

the class NetUtil method getIPv4inSubnet.

@Nullable
private String getIPv4inSubnet(String ipAddress, String subnetMask) {
    try {
        final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            final NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
                continue;
            }
            for (InterfaceAddress ifAddr : current.getInterfaceAddresses()) {
                InetAddress addr = ifAddr.getAddress();
                if (addr.isLoopbackAddress() || (addr instanceof Inet6Address)) {
                    continue;
                }
                String ipv4AddressOnInterface = addr.getHostAddress();
                String subnetStringOnInterface = getIpv4NetAddress(ipv4AddressOnInterface, ifAddr.getNetworkPrefixLength()) + "/" + String.valueOf(ifAddr.getNetworkPrefixLength());
                String configuredSubnetString = getIpv4NetAddress(ipAddress, Short.parseShort(subnetMask)) + "/" + subnetMask;
                // use first IP within this subnet
                if (subnetStringOnInterface.equals(configuredSubnetString)) {
                    return ipv4AddressOnInterface;
                }
            }
        }
    } catch (SocketException ex) {
        LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
    }
    return null;
}
Also used : SocketException(java.net.SocketException) InterfaceAddress(java.net.InterfaceAddress) NetworkInterface(java.net.NetworkInterface) Inet6Address(java.net.Inet6Address) InetAddress(java.net.InetAddress) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 28 with InterfaceAddress

use of java.net.InterfaceAddress in project smarthome by eclipse.

the class NetUtil method getAllBroadcastAddresses.

/**
 * Get all broadcast addresses on the current host
 *
 * @return list of broadcast addresses, empty list if no broadcast addresses found
 */
public static List<String> getAllBroadcastAddresses() {
    List<String> broadcastAddresses = new LinkedList<String>();
    try {
        final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            final NetworkInterface networkInterface = networkInterfaces.nextElement();
            final List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
            for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                final InetAddress addr = interfaceAddress.getAddress();
                if (addr instanceof Inet4Address && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress()) {
                    InetAddress broadcast = interfaceAddress.getBroadcast();
                    if (broadcast != null) {
                        broadcastAddresses.add(broadcast.getHostAddress());
                    }
                }
            }
        }
    } catch (SocketException ex) {
        LOGGER.error("Could not find broadcast address: {}", ex.getMessage(), ex);
    }
    return broadcastAddresses;
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) InterfaceAddress(java.net.InterfaceAddress) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress) LinkedList(java.util.LinkedList)

Example 29 with InterfaceAddress

use of java.net.InterfaceAddress in project smarthome by eclipse.

the class LifxNetworkUtil method updateNetworkInformation.

/**
 * Updates the network information without any synchronization in a thread-safe way.
 */
private static void updateNetworkInformation() {
    LOGGER.debug("Updating network information");
    List<InetSocketAddress> newBroadcastAddresses = new ArrayList<>();
    List<InetAddress> newInterfaceAddresses = new ArrayList<>();
    int newBufferSize = 0;
    Enumeration<NetworkInterface> networkInterfaces = null;
    try {
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        LOGGER.debug("Exception while getting network interfaces: '{}'", 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) {
                            newInterfaceAddresses.add(ifaceAddr.getAddress());
                            newBufferSize = Math.max(newBufferSize, iface.getMTU());
                            if (ifaceAddr.getBroadcast() != null) {
                                newBroadcastAddresses.add(new InetSocketAddress(ifaceAddr.getBroadcast(), BROADCAST_PORT));
                            }
                        }
                    }
                }
            } catch (SocketException e) {
                LOGGER.debug("Exception while getting information for network interface '{}': '{}'", iface.getName(), e.getMessage());
            }
        }
        broadcastAddresses = newBroadcastAddresses;
        interfaceAddresses = newInterfaceAddresses;
        bufferSize = newBufferSize;
    }
    lastUpdateMillis = System.currentTimeMillis();
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) InetSocketAddress(java.net.InetSocketAddress) InterfaceAddress(java.net.InterfaceAddress) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 30 with InterfaceAddress

use of java.net.InterfaceAddress in project NetGuard by M66B.

the class ServiceSinkhole method getBuilder.

private Builder getBuilder(List<Rule> listAllowed, List<Rule> listRule) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean subnet = prefs.getBoolean("subnet", false);
    boolean tethering = prefs.getBoolean("tethering", false);
    boolean lan = prefs.getBoolean("lan", false);
    boolean ip6 = prefs.getBoolean("ip6", true);
    boolean filter = prefs.getBoolean("filter", false);
    boolean system = prefs.getBoolean("manage_system", false);
    // Build VPN service
    Builder builder = new Builder();
    builder.setSession(getString(R.string.app_name));
    // VPN address
    String vpn4 = prefs.getString("vpn4", "10.1.10.1");
    Log.i(TAG, "vpn4=" + vpn4);
    builder.addAddress(vpn4, 32);
    if (ip6) {
        String vpn6 = prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1");
        Log.i(TAG, "vpn6=" + vpn6);
        builder.addAddress(vpn6, 128);
    }
    // DNS address
    if (filter)
        for (InetAddress dns : getDns(ServiceSinkhole.this)) {
            if (ip6 || dns instanceof Inet4Address) {
                Log.i(TAG, "dns=" + dns);
                builder.addDnsServer(dns);
            }
        }
    // Subnet routing
    if (subnet) {
        // Exclude IP ranges
        List<IPUtil.CIDR> listExclude = new ArrayList<>();
        // localhost
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8));
        if (tethering) {
            // USB tethering 192.168.42.x
            // Wi-Fi tethering 192.168.43.x
            listExclude.add(new IPUtil.CIDR("192.168.42.0", 23));
            // Wi-Fi direct 192.168.49.x
            listExclude.add(new IPUtil.CIDR("192.168.49.0", 24));
        }
        if (lan) {
            try {
                Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback() && ni.getName() != null && !ni.getName().startsWith("tun"))
                        for (InterfaceAddress ia : ni.getInterfaceAddresses()) if (ia.getAddress() instanceof Inet4Address) {
                            IPUtil.CIDR local = new IPUtil.CIDR(ia.getAddress(), ia.getNetworkPrefixLength());
                            Log.i(TAG, "Excluding " + ni.getName() + " " + local);
                            listExclude.add(local);
                        }
                }
            } catch (SocketException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }
        // https://en.wikipedia.org/wiki/Mobile_country_code
        Configuration config = getResources().getConfiguration();
        // T-Mobile Wi-Fi calling
        if (config.mcc == 310 && (config.mnc == 160 || config.mnc == 200 || config.mnc == 210 || config.mnc == 220 || config.mnc == 230 || config.mnc == 240 || config.mnc == 250 || config.mnc == 260 || config.mnc == 270 || config.mnc == 310 || config.mnc == 490 || config.mnc == 660 || config.mnc == 800)) {
            listExclude.add(new IPUtil.CIDR("66.94.2.0", 24));
            listExclude.add(new IPUtil.CIDR("66.94.6.0", 23));
            listExclude.add(new IPUtil.CIDR("66.94.8.0", 22));
            listExclude.add(new IPUtil.CIDR("208.54.0.0", 16));
        }
        // Verizon wireless calling
        if ((config.mcc == 310 && (config.mnc == 4 || config.mnc == 5 || config.mnc == 6 || config.mnc == 10 || config.mnc == 12 || config.mnc == 13 || config.mnc == 350 || config.mnc == 590 || config.mnc == 820 || config.mnc == 890 || config.mnc == 910)) || (config.mcc == 311 && (config.mnc == 12 || config.mnc == 110 || (config.mnc >= 270 && config.mnc <= 289) || config.mnc == 390 || (config.mnc >= 480 && config.mnc <= 489) || config.mnc == 590)) || (config.mcc == 312 && (config.mnc == 770))) {
            // 66.174.0.0 - 66.174.255.255
            listExclude.add(new IPUtil.CIDR("66.174.0.0", 16));
            // 69.82.0.0 - 69.83.255.255
            listExclude.add(new IPUtil.CIDR("66.82.0.0", 15));
            // 69.96.0.0 - 69.103.255.255
            listExclude.add(new IPUtil.CIDR("69.96.0.0", 13));
            // 70.192.0.0 - 70.223.255.255
            listExclude.add(new IPUtil.CIDR("70.192.0.0", 11));
            // 97.128.0.0 - 97.255.255.255
            listExclude.add(new IPUtil.CIDR("97.128.0.0", 9));
            // 174.192.0.0 - 174.255.255.255
            listExclude.add(new IPUtil.CIDR("174.192.0.0", 9));
            // 72.96.0.0 - 72.127.255.255
            listExclude.add(new IPUtil.CIDR("72.96.0.0", 9));
            // 75.192.0.0 - 75.255.255.255
            listExclude.add(new IPUtil.CIDR("75.192.0.0", 9));
            // 97.0.0.0 - 97.63.255.255
            listExclude.add(new IPUtil.CIDR("97.0.0.0", 10));
        }
        // Broadcast
        listExclude.add(new IPUtil.CIDR("224.0.0.0", 3));
        Collections.sort(listExclude);
        try {
            InetAddress start = InetAddress.getByName("0.0.0.0");
            for (IPUtil.CIDR exclude : listExclude) {
                Log.i(TAG, "Exclude " + exclude.getStart().getHostAddress() + "..." + exclude.getEnd().getHostAddress());
                for (IPUtil.CIDR include : IPUtil.toCIDR(start, IPUtil.minus1(exclude.getStart()))) try {
                    builder.addRoute(include.address, include.prefix);
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
                start = IPUtil.plus1(exclude.getEnd());
            }
            String end = (lan ? "255.255.255.254" : "255.255.255.255");
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", end)) try {
                builder.addRoute(include.address, include.prefix);
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        } catch (UnknownHostException ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    } else
        builder.addRoute("0.0.0.0", 0);
    Log.i(TAG, "IPv6=" + ip6);
    if (ip6)
        // unicast
        builder.addRoute("2000::", 3);
    // MTU
    int mtu = jni_get_mtu();
    Log.i(TAG, "MTU=" + mtu);
    builder.setMtu(mtu);
    // Add list of allowed applications
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        try {
            builder.addDisallowedApplication(getPackageName());
        } catch (PackageManager.NameNotFoundException ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
        if (last_connected && !filter)
            for (Rule rule : listAllowed) try {
                builder.addDisallowedApplication(rule.packageName);
            } catch (PackageManager.NameNotFoundException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        else if (filter)
            for (Rule rule : listRule) if (!rule.apply || (!system && rule.system))
                try {
                    Log.i(TAG, "Not routing " + rule.packageName);
                    builder.addDisallowedApplication(rule.packageName);
                } catch (PackageManager.NameNotFoundException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
    }
    // Build configure intent
    Intent configure = new Intent(this, ActivityMain.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, configure, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setConfigureIntent(pi);
    return builder;
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) Configuration(android.content.res.Configuration) UnknownHostException(java.net.UnknownHostException) SharedPreferences(android.content.SharedPreferences) InterfaceAddress(java.net.InterfaceAddress) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) SpannableString(android.text.SpannableString) Paint(android.graphics.Paint) PackageManager(android.content.pm.PackageManager) PendingIntent(android.app.PendingIntent) InetAddress(java.net.InetAddress)

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