List of usage examples for java.net NetworkInterface getNetworkInterfaces
public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException
From source file:com.qwazr.server.configuration.ServerConfiguration.java
/** * Manage that kind of pattern:// w w w.j av a2s.c o m * 192.168.0.0/16,172.168.0.0/16 * 192.168.0.0/16 * 10.3.12.12 * * @param addressPattern a mask or an ip address * @param collect a collection filled with the matching addresses * @throws SocketException */ private static void findMatchingAddress(final String addressPattern, final Collection<String> collect) throws SocketException { final String[] patterns = StringUtils.split(addressPattern, ",; "); if (patterns == null) return; for (String pattern : patterns) { if (pattern == null) continue; pattern = pattern.trim(); if (!pattern.contains("/")) { collect.add(pattern); continue; } final SubnetUtils.SubnetInfo subnet = pattern.contains("/") ? new SubnetUtils(pattern).getInfo() : null; final Enumeration<NetworkInterface> enumInterfaces = NetworkInterface.getNetworkInterfaces(); while (enumInterfaces != null && enumInterfaces.hasMoreElements()) { final NetworkInterface ifc = enumInterfaces.nextElement(); if (!ifc.isUp()) continue; final Enumeration<InetAddress> enumAddresses = ifc.getInetAddresses(); while (enumAddresses != null && enumAddresses.hasMoreElements()) { final InetAddress inetAddress = enumAddresses.nextElement(); if (!(inetAddress instanceof Inet4Address)) continue; final String address = inetAddress.getHostAddress(); if (subnet != null && subnet.isInRange(address) || address.equals(pattern)) collect.add(address); } } } }
From source file:org.cc86.MMC.client.Main.java
public static String serverDiscovery() { String res = "0.0.0.0"; DatagramSocket c;// www .j a va 2s . c o m // Find the server using UDP broadcast try { //Open a random port to send the package c = new DatagramSocket(); c.setBroadcast(true); byte[] sendData = "DISCOVER_MMC_REQUEST".getBytes(); //Try the 255.255.255.255 first try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 0xCC86); c.send(sendPacket); l.info("Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch (Exception e) { } // Broadcast the message over all the network interfaces Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement(); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } // Send the broadcast package! try { DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); c.send(sendPacket); } catch (Exception e) { } l.info("Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName()); } } l.info("Done looping over all network interfaces. Now waiting for a reply!"); //Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); c.receive(receivePacket); //We have a response l.info("Broadcast response from server: " + receivePacket.getAddress().getHostAddress()); //Check if the message is correct String message = new String(receivePacket.getData()).trim(); if (message.equals("DISCOVER_MMC_RESPONSE")) { //DO SOMETHING WITH THE SERVER'S IP (for example, store it in your controller) res = (receivePacket.getAddress() + "").substring(1); } //Close the port! c.close(); } catch (IOException ex) { } return res; }
From source file:be.deadba.ampd.SettingsActivity.java
private static String getLocalIpAddress() { try {//from w w w.jav 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(); String hostAddress = inetAddress.getHostAddress(); if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(hostAddress)) { return hostAddress; } } } } catch (Exception ex) { Log.e(TAG, ex.toString()); } return null; }
From source file:com.cloud.utils.net.NetUtils.java
public static InetAddress[] getInterfaceInetAddresses(final String ifName) { final List<InetAddress> addrList = new ArrayList<InetAddress>(); try {/*from w ww . j a va 2 s . c o m*/ for (final NetworkInterface ifc : IteratorUtil .enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) { if (ifc.isUp() && !ifc.isVirtual() && ifc.getName().equals(ifName)) { for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) { addrList.add(addr); } } } } catch (final SocketException e) { s_logger.warn("SocketException in getAllLocalInetAddresses().", e); } final InetAddress[] addrs = new InetAddress[addrList.size()]; if (addrList.size() > 0) { System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size()); } return addrs; }
From source file:nl.eduvpn.app.service.VPNService.java
/** * Retrieves the IP4 and IPv6 addresses assigned by the VPN server to this client using a network interface lookup. * * @return The IPv4 and IPv6 addresses in this order as a pair. If not found, a null value is returned instead. *///from w w w . j a v a 2 s . c o m private Pair<String, String> _lookupVpnIpAddresses() { try { List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface networkInterface : networkInterfaces) { if (VPN_INTERFACE_NAME.equals(networkInterface.getName())) { List<InetAddress> addresses = Collections.list(networkInterface.getInetAddresses()); String ipV4 = null; String ipV6 = null; for (InetAddress address : addresses) { String ip = address.getHostAddress(); boolean isIPv4 = ip.indexOf(':') < 0; if (isIPv4) { ipV4 = ip; } else { int delimiter = ip.indexOf('%'); ipV6 = delimiter < 0 ? ip.toLowerCase() : ip.substring(0, delimiter).toLowerCase(); } } if (ipV4 != null || ipV6 != null) { return new Pair<>(ipV4, ipV6); } else { return null; } } } } catch (SocketException ex) { Log.w(TAG, "Unable to retrieve network interface info!", ex); } return null; }
From source file:com.triggertrap.ZeroConf.java
/** * Returns the first found IP4 address./*from w ww . j a va 2 s. c o m*/ * * @return the first found IP4 address */ public static InetAddress getIPAddress(int wifi_ipaddr) { try { String ipString = String.format("%d.%d.%d.%d", (wifi_ipaddr & 0xff), (wifi_ipaddr >> 8 & 0xff), (wifi_ipaddr >> 16 & 0xff), (wifi_ipaddr >> 24 & 0xff)); 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() && (ipString.equals(addr.getHostAddress()))) { //String sAddr = addr.getHostAddress().toUpperCase(); if (addr instanceof java.net.Inet4Address) { //Log.d("found IP address to listen: " , sAddr); return addr; } } } } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:cycronix.CTandroid.CTAserver.java
/** * Get IP address from first non-localhost interface * @param ipv4 true=return ipv4, false=return ipv6 * @return address or empty string/*from ww w .j a v a2 s. co m*/ */ 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(); // org.apache.http.conn.util is no longer supported under Android API 23 // http://stackoverflow.com/questions/32141785/android-api-23-inetaddressutils-replacement // https://developer.android.com/sdk/api_diff/23/changes.html // boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); InetAddress tempInetAddress = InetAddress.getByName(sAddr); boolean isIPv4 = false; if (tempInetAddress instanceof Inet4Address) { isIPv4 = true; } 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 ex) { } // for now eat exceptions return "Unknown"; }
From source file:davmail.exchange.ExchangeSessionFactory.java
/** * Check if at least one network interface is up and active (i.e. has an address) * * @return true if network available/* w w w . j av a2 s . c o m*/ */ static boolean checkNetwork() { boolean up = false; Enumeration<NetworkInterface> enumeration; try { enumeration = NetworkInterface.getNetworkInterfaces(); while (!up && enumeration.hasMoreElements()) { NetworkInterface networkInterface = enumeration.nextElement(); up = networkInterface.isUp() && !networkInterface.isLoopback() && networkInterface.getInetAddresses().hasMoreElements(); } } catch (NoSuchMethodError error) { ExchangeSession.LOGGER.debug("Unable to test network interfaces (not available under Java 1.5)"); up = true; } catch (SocketException exc) { ExchangeSession.LOGGER.error( "DavMail configuration exception: \n Error listing network interfaces " + exc.getMessage(), exc); } return up; }
From source file:de.jaetzold.networking.SimpleServiceDiscovery.java
/** * Comma separated List of IP adresses of available network interfaces * @param useIPv4/* w ww . ja va 2 s . c o m*/ * @return */ public static String getIPAddress(boolean useIPv4) { String addresses = ""; 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) addresses += sAddr + ", "; } else { if (!isIPv4) { int delim = sAddr.indexOf('%'); // drop ip6 port suffix if (delim < 0) addresses += sAddr + ", "; else addresses += sAddr.substring(0, delim) + ", "; } } } } } } catch (Exception ex) { } // for now eat exceptions if (addresses == null || addresses.length() <= 3) return ""; return addresses.subSequence(0, addresses.length() - 2).toString(); }