Example usage for java.net NetworkInterface getNetworkInterfaces

List of usage examples for java.net NetworkInterface getNetworkInterfaces

Introduction

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

Prototype

public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException 

Source Link

Document

Returns an Enumeration of all the interfaces on this machine.

Usage

From source file:org.talend.commons.utils.network.NetworkUtil.java

public static boolean isSelfAddress(String addr) {
    if (addr == null || addr.isEmpty()) {
        return false; // ?
    }/* w  ww .j  a v a  2s.c  om*/

    try {
        final InetAddress sourceAddress = InetAddress.getByName(addr);
        if (sourceAddress.isLoopbackAddress()) {
            // final String hostAddress = sourceAddress.getHostAddress();
            // // if addr is localhost, will be 127.0.0.1 also
            // if (hostAddress.equals("127.0.0.1") || hostAddress.equals("localhost") ) {
            return true;
            // }
        } else {
            // check all ip configs
            InetAddress curAddr = null;
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while (address.hasMoreElements()) {
                    curAddr = address.nextElement();
                    if (addr.equals(curAddr.getHostAddress())) {
                        return true;
                    }
                }
            }
        }

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:net.mm2d.dmsexplorer.ServerListActivity.java

private Collection<NetworkInterface> getWifiInterface() {
    final NetworkInfo ni = mConnectivityManager.getActiveNetworkInfo();
    if (ni == null || !ni.isConnected() || ni.getType() != ConnectivityManager.TYPE_WIFI) {
        return null;
    }//www  . j a  va2s . co m
    final InetAddress address = getWifiInetAddress();
    if (address == null) {
        return null;
    }
    final Enumeration<NetworkInterface> nis;
    try {
        nis = NetworkInterface.getNetworkInterfaces();
    } catch (final SocketException e) {
        return null;
    }
    while (nis.hasMoreElements()) {
        final NetworkInterface nif = nis.nextElement();
        try {
            if (nif.isLoopback() || nif.isPointToPoint() || nif.isVirtual() || !nif.isUp()) {
                continue;
            }
            final List<InterfaceAddress> ifas = nif.getInterfaceAddresses();
            for (final InterfaceAddress a : ifas) {
                if (a.getAddress().equals(address)) {
                    final Collection<NetworkInterface> c = new ArrayList<>();
                    c.add(nif);
                    return c;
                }
            }
        } catch (final SocketException ignored) {
        }
    }
    return null;
}

From source file:ca.frozen.curlingtv.classes.Utils.java

public static String getLocalIpAddress() {
    try {/*from   w w w  .  j  a v a2  s .c  om*/
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:org.ngrinder.recorder.util.NetworkUtil.java

private static InetAddress getFirstNonLoopbackAddress(boolean preferIpv4, boolean preferIPv6)
        throws SocketException {
    Enumeration<?> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
        NetworkInterface i = (NetworkInterface) en.nextElement();
        if (!i.isUp()) {
            continue;
        }/*  w w  w  . ja  v  a 2  s  .  com*/
        if (StringUtils.containsIgnoreCase(i.getDisplayName(), "Host-Only")) {
            continue;
        }
        for (Enumeration<?> en2 = i.getInetAddresses(); en2.hasMoreElements();) {
            InetAddress addr = (InetAddress) en2.nextElement();
            if (!addr.isLoopbackAddress()) {
                if (addr instanceof Inet4Address) {
                    if (preferIPv6) {
                        continue;
                    }
                    return addr;
                }
                if (addr instanceof Inet6Address) {
                    if (preferIpv4) {
                        continue;
                    }
                    return addr;
                }
            }
        }
    }
    return null;
}

From source file:org.kei.android.phone.netcap.OutputFragment.java

@Override
public void onClick(final View v) {
    if (v.equals(refreshBT)) {
        adapter.clear();//from www  .  j  ava2 s . com
        try {
            final List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            if (interfaces != null && interfaces.size() != 0)
                adapter.add(getResources().getText(R.string.any).toString());
            for (final NetworkInterface ni : interfaces)
                if (ni.isUp())
                    adapter.add(ni.getName());
        } catch (final Throwable e) {
            logException(e);
        }
    } else if (v.equals(browseOutputCaptureTV)) {
        final Map<String, String> extra = new HashMap<String, String>();
        extra.put(FileChooser.FILECHOOSER_TYPE_KEY, "" + FileChooser.FILECHOOSER_TYPE_DIRECTORY_ONLY);
        extra.put(FileChooser.FILECHOOSER_TITLE_KEY, "Save");
        extra.put(FileChooser.FILECHOOSER_MESSAGE_KEY, "Use this folder:? ");
        extra.put(FileChooser.FILECHOOSER_DEFAULT_DIR, browseOutputCaptureTV.getText().toString());
        extra.put(FileChooser.FILECHOOSER_SHOW_KEY, "" + FileChooser.FILECHOOSER_SHOW_DIRECTORY_ONLY);
        extra.put(FileChooser.FILECHOOSER_USER_MESSAGE, getClass().getSimpleName());
        Tools.switchToForResult(owner, FileChooserActivity.class, extra,
                FileChooserActivity.FILECHOOSER_SELECTION_TYPE_DIRECTORY);

    } else if (v.equals(captureBT)) {
        if (!captureBT.isChecked()) {
            captureBT.setChecked(true);
            delete();
        } else {
            String sdest = browseOutputCaptureTV.getText().toString();
            if (sdest.isEmpty()) {
                Tools.showAlertDialog(owner, "Error", "Empty destination folder!");
                captureBT.setChecked(false);
                return;
            }

            File legacy = new File(sdest.replaceFirst("emulated/([0-9]+)/", "emulated/legacy/"));
            File fdest = new File(sdest);
            Log.i(getClass().getSimpleName(), "Test directory '" + legacy + "'");
            if (legacy.isDirectory())
                fdest = legacy;
            if (!fdest.isDirectory()) {
                Tools.showAlertDialog(owner, "Error", "The destination folder is not a valid directory!");
                captureBT.setChecked(false);
                return;
            } else if (!fdest.canWrite()) {
                Tools.showAlertDialog(owner, "Error", "Unable to write into the destination folder!");
                captureBT.setChecked(false);
                return;
            }

            if (!RootTools.isAccessGiven()) {
                Resources r = getResources();
                Tools.toast(owner, R.drawable.ic_launcher, r.getString(R.string.root_toast_error));
                showResult.setText(" " + r.getString(R.string.root_error));
                captureBT.setChecked(false);
                return;
            }

            final PackageManager m = owner.getPackageManager();
            String s = owner.getPackageName();
            try {
                final PackageInfo p = m.getPackageInfo(s, 0);
                s = p.applicationInfo.dataDir;
            } catch (final PackageManager.NameNotFoundException e) {
            }
            s = s + "/netcap";
            copyFile(Build.SUPPORTED_ABIS[0] + "/netcap", s, owner);
            final File netcap = new File(s);
            if (!netcap.exists()) {
                Tools.showAlertDialog(owner, "Error",
                        "'netcap' for '" + Build.SUPPORTED_ABIS[0] + "' was not found!");
                return;
            }
            pname = netcap.getAbsolutePath();
            netcap.setExecutable(true);

            ifaces = "";
            String ni = (String) devicesSp.getSelectedItem();
            if (ni.equals(getResources().getText(R.string.any).toString())) {
                for (int i = 0; i < adapter.getCount(); i++) {
                    ni = adapter.getItem(i);
                    if (ni.equals(getResources().getText(R.string.any).toString()))
                        continue;
                    ifaces += ni;
                    if (i < adapter.getCount() - 1)
                        ifaces += ",";
                }
            } else
                ifaces = ni;

            final File outputFile = new File(fdest,
                    new SimpleDateFormat("yyyyMMdd_hhmmssa'_netcap.pcap'", Locale.US).format(new Date()));
            buffer.clear();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String cmd = netcap.getAbsolutePath() + " -i " + ifaces + " -f "
                                + outputFile.getAbsolutePath() + " -d";
                        if (promiscuousCB.isChecked())
                            cmd += " -p";
                        cmd += " 2>&1";
                        command = new Command(0, cmd) {
                            @Override
                            public void commandOutput(int id, String line) {
                                super.commandOutput(id, line);
                                if (line.startsWith(NETCAP_READY))
                                    pid = line.substring(NETCAP_READY.length());
                                buffer.add(line);
                                owner.runOnUiThread(new Runnable() {
                                    @SuppressWarnings("unchecked")
                                    @Override
                                    public void run() {
                                        final String[] lines = (String[]) buffer.toArray(new String[] {});
                                        final StringBuilder sb = new StringBuilder();
                                        for (final String s : lines)
                                            sb.append(" ").append(s).append("\n");
                                        showResult.setText(sb.toString());
                                    }
                                });
                            }

                            public void commandCompleted(int id, int exitcode) {
                                super.commandCompleted(id, exitcode);
                                owner.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        captureBT.setChecked(false);
                                    }
                                });
                            }

                            public void commandTerminated(int id, String reason) {
                                super.commandTerminated(id, reason);
                            }
                        };
                        RootTools.getShell(true).add(command);
                    } catch (final Exception e) {
                        logException(e);
                    }
                }
            }).start();
        }
    }
}

From source file:com.rincliu.library.util.RLNetUtil.java

/**
 * Get IP address from first non-localhost interface
 * //from   w w  w  . j  a  v  a  2 s . co  m
 * @param ipv4 true=return ipv4, false=return ipv6
 * @return address or empty string
 */
public static String getIPAddress(boolean useIPv4) {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress()) {
                    String sAddr = addr.getHostAddress().toUpperCase();
                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                    if (useIPv4) {
                        if (isIPv4)
                            return sAddr;
                    } else {
                        if (!isIPv4) {
                            int delim = sAddr.indexOf('%'); // drop ip6
                                                            // port suffix
                            return delim < 0 ? sAddr : sAddr.substring(0, delim);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:com.cloud.utils.net.NetUtils.java

public static String[] getLocalCidrs() {
    final String defaultHostIp = getDefaultHostIp();

    final List<String> cidrList = new ArrayList<String>();
    try {//from  ww w .j a v a 2 s. c  o m
        for (final NetworkInterface ifc : IteratorUtil
                .enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
                for (final InterfaceAddress address : ifc.getInterfaceAddresses()) {
                    final InetAddress addr = address.getAddress();
                    final int prefixLength = address.getNetworkPrefixLength();
                    if (prefixLength < MAX_CIDR && prefixLength > 0) {
                        final String ip = ipFromInetAddress(addr);
                        if (ip.equalsIgnoreCase(defaultHostIp)) {
                            cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
                        }
                    }
                }
            }
        }
    } catch (final SocketException e) {
        s_logger.warn("UnknownHostException in getLocalCidrs().", e);
    }

    return cidrList.toArray(new String[0]);
}

From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java

public Future sendAnnounceMessage() {
    return processingExecutorService.submit(new Callable() {

        @Override//  w  w  w  .j a v  a  2s  .  c  o  m
        public Object call() throws Exception {
            for (int i = 0; i < 10 && !isListening; i++) { //wait for listening
                Thread.sleep(100);
            }
            if (!isListening) {
                logger.warn("skipping announce message, udp listening is not active");
                return null;
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            new DataOutputStream(out).writeInt(MAGIC);
            Announce.newBuilder()
                    .setId(ByteString.copyFrom(deviceIdStringToHashData(configuration.getDeviceId())))
                    .setInstanceId(configuration.getInstanceId()).build().writeTo(out);
            byte[] data = out.toByteArray();
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                    InetAddress broadcastAddress = interfaceAddress.getBroadcast();
                    logger.trace("interface = {} address = {} broadcast = {}", networkInterface,
                            interfaceAddress, broadcastAddress);
                    if (broadcastAddress != null) {
                        logger.debug("sending broadcast announce on {}", broadcastAddress);
                        try (DatagramSocket broadcastSocket = new DatagramSocket()) {
                            broadcastSocket.setBroadcast(true);
                            DatagramPacket datagramPacket = new DatagramPacket(data, data.length,
                                    broadcastAddress, UDP_PORT);
                            broadcastSocket.send(datagramPacket);
                        } catch (Exception ex) {
                            logger.warn("error sending datagram", ex);
                        }
                    }
                }
            }
            return null;
        }
    });
}

From source file:org.ebayopensource.scc.track.TrackerClient.java

private InetAddress getInetAddress() {
    Enumeration<NetworkInterface> eni = null;
    try {//ww  w  .j  av a 2  s  . c om
        eni = NetworkInterface.getNetworkInterfaces();
        while (eni.hasMoreElements()) {
            NetworkInterface n = eni.nextElement();
            Enumeration<InetAddress> eia = n.getInetAddresses();
            while (eia.hasMoreElements()) {
                InetAddress current = eia.nextElement();
                if (current.isSiteLocalAddress()) {
                    return current;
                }
            }
        }
        return InetAddress.getLocalHost();
    } catch (SocketException | UnknownHostException ex) {
        LOGGER.warn("Failed to get IP address.", ex);
        return null;
    }
}

From source file:org.cc86.MMC.client.Main.java

public static void serverDiscoveryHack(String[] args) {
    try {//  www  . ja  v a2s .c  om

        final boolean[] foundSomething = { false };
        List<InetAddress> addrList = new ArrayList<InetAddress>();
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            try {
                NetworkInterface ifc = (NetworkInterface) interfaces.nextElement();

                if (ifc.isUp()) {
                    Enumeration addresses = ifc.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = (InetAddress) addresses.nextElement();
                        if (addr instanceof Inet6Address) {
                            continue;
                        }
                        byte[] addrraw = addr.getAddress();
                        for (int i = 1; i < 254; i++) {
                            try {
                                final InetAddress calculated = InetAddress.getByAddress(
                                        new byte[] { addrraw[0], addrraw[1], addrraw[2], (byte) i });
                                new Thread(() -> {
                                    //c=new TCPConnection(calculated.getHostAddress(), 0xCC86);
                                    try {
                                        Socket client = new Socket();
                                        client.connect(
                                                new InetSocketAddress(calculated.getHostAddress(), 0xcc87),
                                                2000);
                                        synchronized (foundSomething) {
                                            if (!foundSomething[0]) {
                                                foundSomething[0] = true;
                                                ArrayList<String> lst = new ArrayList(Arrays.asList(args));
                                                lst.add("-i");
                                                lst.add(calculated.getHostAddress());
                                                main(lst.toArray(args));
                                            }
                                        }
                                    } catch (IOException ex) {
                                        //System.out.println(ex.m);
                                        l.trace("Dead host");
                                        //System.exit(0);
                                    }
                                }).start();
                            } catch (UnknownHostException ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }
            } catch (SocketException ex) {
                ex.printStackTrace();
            }
        }

    } catch (SocketException ex) {
        ex.printStackTrace();
    }
}