Example usage for java.net NetworkInterface isLoopback

List of usage examples for java.net NetworkInterface isLoopback

Introduction

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

Prototype


public boolean isLoopback() throws SocketException 

Source Link

Document

Returns whether a network interface is a loopback interface.

Usage

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 {// w ww.j a  va  2  s.c  o  m
            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  . ja  v a2s  .  c  om
 * @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;
}

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

public static List<InetAddress> getDns(Context context) {
    List<InetAddress> listDns = new ArrayList<>();
    List<String> sysDns = Util.getDefaultDNS(context);

    // Get custom DNS servers
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String vpnDns1 = prefs.getString("dns", null);
    String vpnDns2 = prefs.getString("dns2", null);
    Log.i(TAG, "DNS system=" + TextUtils.join(",", sysDns) + " VPN1=" + vpnDns1 + " VPN2=" + vpnDns2);

    if (vpnDns1 != null)
        try {//from  w  w  w  . j av a  2  s .com
            InetAddress dns = InetAddress.getByName(vpnDns1);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()))
                listDns.add(dns);
        } catch (Throwable ignored) {
        }

    if (vpnDns2 != null)
        try {
            InetAddress dns = InetAddress.getByName(vpnDns2);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()))
                listDns.add(dns);
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

    // Use system DNS servers only when no two custom DNS servers specified
    if (listDns.size() <= 1)
        for (String def_dns : sysDns)
            try {
                InetAddress ddns = InetAddress.getByName(def_dns);
                if (!listDns.contains(ddns) && !(ddns.isLoopbackAddress() || ddns.isAnyLocalAddress()))
                    listDns.add(ddns);
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

    // Remove local DNS servers when not routing LAN
    boolean lan = prefs.getBoolean("lan", false);
    if (lan) {
        List<InetAddress> listLocal = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            if (nis != null)
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback()) {
                        List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                        if (ias != null)
                            for (InterfaceAddress ia : ias) {
                                InetAddress hostAddress = ia.getAddress();
                                BigInteger host = new BigInteger(1, hostAddress.getAddress());

                                int prefix = ia.getNetworkPrefixLength();
                                BigInteger mask = BigInteger.valueOf(-1)
                                        .shiftLeft(hostAddress.getAddress().length * 8 - prefix);

                                for (InetAddress dns : listDns)
                                    if (hostAddress.getAddress().length == dns.getAddress().length) {
                                        BigInteger ip = new BigInteger(1, dns.getAddress());

                                        if (host.and(mask).equals(ip.and(mask))) {
                                            Log.i(TAG, "Local DNS server host=" + hostAddress + "/" + prefix
                                                    + " dns=" + dns);
                                            listLocal.add(dns);
                                        }
                                    }
                            }
                    }
                }
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

        List<InetAddress> listDns4 = new ArrayList<>();
        List<InetAddress> listDns6 = new ArrayList<>();
        try {
            listDns4.add(InetAddress.getByName("8.8.8.8"));
            listDns4.add(InetAddress.getByName("8.8.4.4"));
            listDns6.add(InetAddress.getByName("2001:4860:4860::8888"));
            listDns6.add(InetAddress.getByName("2001:4860:4860::8844"));

        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

        for (InetAddress dns : listLocal) {
            listDns.remove(dns);
            if (dns instanceof Inet4Address) {
                if (listDns4.size() > 0) {
                    listDns.add(listDns4.get(0));
                    listDns4.remove(0);
                }
            } else {
                if (listDns6.size() > 0) {
                    listDns.add(listDns6.get(0));
                    listDns6.remove(0);
                }
            }
        }
    }

    // Prefer IPv4 addresses
    Collections.sort(listDns, new Comparator<InetAddress>() {
        @Override
        public int compare(InetAddress a, InetAddress b) {
            boolean a4 = (a instanceof Inet4Address);
            boolean b4 = (b instanceof Inet4Address);
            if (a4 && !b4)
                return -1;
            else if (!a4 && b4)
                return 1;
            else
                return 0;
        }
    });

    return listDns;
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

public static List<InetAddress> getDns(Context context) {
    List<InetAddress> listDns = new ArrayList<>();
    List<String> sysDns = Util.getDefaultDNS(context);

    // Get custom DNS servers
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean ip6 = prefs.getBoolean("ip6", true);
    String vpnDns1 = prefs.getString("dns", null);
    String vpnDns2 = prefs.getString("dns2", null);
    Log.i(TAG, "DNS system=" + TextUtils.join(",", sysDns) + " VPN1=" + vpnDns1 + " VPN2=" + vpnDns2);

    if (vpnDns1 != null)
        try {//from  www  .  j  a  v  a  2  s.  c om
            InetAddress dns = InetAddress.getByName(vpnDns1);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()) && (ip6 || dns instanceof Inet4Address))
                listDns.add(dns);
        } catch (Throwable ignored) {
        }

    if (vpnDns2 != null)
        try {
            InetAddress dns = InetAddress.getByName(vpnDns2);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()) && (ip6 || dns instanceof Inet4Address))
                listDns.add(dns);
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

    // Use system DNS servers only when no two custom DNS servers specified
    if (listDns.size() <= 1)
        for (String def_dns : sysDns)
            try {
                InetAddress ddns = InetAddress.getByName(def_dns);
                if (!listDns.contains(ddns) && !(ddns.isLoopbackAddress() || ddns.isAnyLocalAddress())
                        && (ip6 || ddns instanceof Inet4Address))
                    listDns.add(ddns);
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }

    // Remove local DNS servers when not routing LAN
    boolean lan = prefs.getBoolean("lan", false);
    boolean use_hosts = prefs.getBoolean("filter", false) && prefs.getBoolean("use_hosts", false);
    if (lan && use_hosts) {
        List<InetAddress> listLocal = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            if (nis != null)
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback()) {
                        List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                        if (ias != null)
                            for (InterfaceAddress ia : ias) {
                                InetAddress hostAddress = ia.getAddress();
                                BigInteger host = new BigInteger(1, hostAddress.getAddress());

                                int prefix = ia.getNetworkPrefixLength();
                                BigInteger mask = BigInteger.valueOf(-1)
                                        .shiftLeft(hostAddress.getAddress().length * 8 - prefix);

                                for (InetAddress dns : listDns)
                                    if (hostAddress.getAddress().length == dns.getAddress().length) {
                                        BigInteger ip = new BigInteger(1, dns.getAddress());

                                        if (host.and(mask).equals(ip.and(mask))) {
                                            Log.i(TAG, "Local DNS server host=" + hostAddress + "/" + prefix
                                                    + " dns=" + dns);
                                            listLocal.add(dns);
                                        }
                                    }
                            }
                    }
                }
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

        List<InetAddress> listDns4 = new ArrayList<>();
        List<InetAddress> listDns6 = new ArrayList<>();
        try {
            listDns4.add(InetAddress.getByName("8.8.8.8"));
            listDns4.add(InetAddress.getByName("8.8.4.4"));
            if (ip6) {
                listDns6.add(InetAddress.getByName("2001:4860:4860::8888"));
                listDns6.add(InetAddress.getByName("2001:4860:4860::8844"));
            }

        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }

        for (InetAddress dns : listLocal) {
            listDns.remove(dns);
            if (dns instanceof Inet4Address) {
                if (listDns4.size() > 0) {
                    listDns.add(listDns4.get(0));
                    listDns4.remove(0);
                }
            } else {
                if (listDns6.size() > 0) {
                    listDns.add(listDns6.get(0));
                    listDns6.remove(0);
                }
            }
        }
    }

    return listDns;
}

From source file:configuration.Util.java

/**
 * Code from : http://stackoverflow.com/questions/8083479/java-getting-my-ip-address
 *
 * @return/* ww  w  .  j  a  v  a 2  s. c  o  m*/
 */
public String ip() {
    String ip;
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            // filters out 127.0.0.1 and inactive interfaces
            if (iface.isLoopback() || !iface.isUp())
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                ip = addr.getHostAddress();
                return ip;
                //System.out.println(iface.getDisplayName() + " " + ip);
            }
        }
    } catch (Exception e) {
        System.out.println("Ip Failed!");
        System.out.println(e);
        return "";
    }
    return "";
}

From source file:com.master.metehan.filtereagle.ServiceSinkhole.java

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);//from w  ww . j  a v  a2s .c o  m
    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<>();
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8)); // localhost

        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));
        }

        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));
            }
        }

        Configuration config = getResources().getConfiguration();
        if (config.mcc == 310 && config.mnc == 260) {
            // T-Mobile Wi-Fi calling
            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));
        }
        listExclude.add(new IPUtil.CIDR("224.0.0.0", 3)); // broadcast

        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());
            }
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", "255.255.255.255"))
                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)
        builder.addRoute("0:0:0:0:0:0:0:0", 0);

    // 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)
        if (last_connected && !filter)
            for (Rule rule : listAllowed)
                try {
                    builder.addDisallowedApplication(rule.info.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.info.packageName);
                        builder.addDisallowedApplication(rule.info.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;
}

From source file:com.zhengde163.netguard.ServiceSinkhole.java

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);//ww w  .j  a v a2  s . co m
    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<>();
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8)); // localhost

        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));
        }

        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));
            }
        }

        Configuration config = getResources().getConfiguration();
        if (config.mcc == 310 && config.mnc == 260) {
            // T-Mobile Wi-Fi calling
            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));
        }
        listExclude.add(new IPUtil.CIDR("224.0.0.0", 3)); // broadcast

        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());
            }
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", "255.255.255.255"))
                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)
        builder.addRoute("0:0:0:0:0:0:0:0", 0);

    // 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)
        if (last_connected && !filter)
            for (Rule rule : listAllowed)
                try {
                    builder.addDisallowedApplication(rule.info.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.info.packageName);
                        builder.addDisallowedApplication(rule.info.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;
}

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

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);//from w w  w .  j a  v a  2  s  . c  o  m
    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<>();
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8)); // localhost

        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));
        }

        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));
            }
        }

        Configuration config = getResources().getConfiguration();
        if (config.mcc == 310 && config.mnc == 260) {
            // T-Mobile Wi-Fi calling
            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));
        }
        listExclude.add(new IPUtil.CIDR("224.0.0.0", 3)); // broadcast

        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());
            }
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", "255.255.255.255"))
                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)
        builder.addRoute("0:0:0:0:0:0:0:0", 0);

    // 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)
        if (last_connected && !filter)
            for (Rule rule : listAllowed)
                try {
                    builder.addDisallowedApplication(rule.info.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.info.packageName);
                        builder.addDisallowedApplication(rule.info.packageName);
                    } catch (PackageManager.NameNotFoundException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

    // Build configure intent
    Intent configure = new Intent(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, configure, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setConfigureIntent(pi);

    return builder;
}

From source file:org.panbox.desktop.common.gui.PanboxClientGUI.java

private DefaultComboBoxModel<Object> generateNetworkInterfacesModel() {
    DefaultComboBoxModel<Object> model = new DefaultComboBoxModel<>();
    try {/*from w w  w.jav a2 s.  c o m*/
        List<NetworkInterface> nics = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nic : nics) {
            List<InetAddress> addrs = Collections.list(nic.getInetAddresses());
            if (addrs.size() > 0 && !nic.isLoopback() && nic.isUp()) {
                model.addElement(nic);
            }
        }
    } catch (SocketException e) {
        logger.warn(
                "An exception occurred while iterating over available network interfaces. Will return unfinished list: ",
                e);
    }
    return model;
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

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);//from  w ww. j av  a  2  s . c o m
    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<>();
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8)); // localhost

        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))) {
            listExclude.add(new IPUtil.CIDR("66.174.0.0", 16)); // 66.174.0.0 - 66.174.255.255
            listExclude.add(new IPUtil.CIDR("66.82.0.0", 15)); // 69.82.0.0 - 69.83.255.255
            listExclude.add(new IPUtil.CIDR("69.96.0.0", 13)); // 69.96.0.0 - 69.103.255.255
            listExclude.add(new IPUtil.CIDR("70.192.0.0", 11)); // 70.192.0.0 - 70.223.255.255
            listExclude.add(new IPUtil.CIDR("97.128.0.0", 9)); // 97.128.0.0 - 97.255.255.255
            listExclude.add(new IPUtil.CIDR("174.192.0.0", 9)); // 174.192.0.0 - 174.255.255.255
            listExclude.add(new IPUtil.CIDR("72.96.0.0", 9)); // 72.96.0.0 - 72.127.255.255
            listExclude.add(new IPUtil.CIDR("75.192.0.0", 9)); // 75.192.0.0 - 75.255.255.255
            listExclude.add(new IPUtil.CIDR("97.0.0.0", 10)); // 97.0.0.0 - 97.63.255.255
        }

        // 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());
            }
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", "255.255.255.255"))
                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)
        builder.addRoute("0:0:0:0:0:0:0:0", 0);

    // 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)
        if (last_connected && !filter)
            for (Rule rule : listAllowed)
                try {
                    builder.addDisallowedApplication(rule.info.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.info.packageName);
                        builder.addDisallowedApplication(rule.info.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;
}