List of usage examples for java.net InterfaceAddress getAddress
public InetAddress getAddress()
From source file:eu.stratosphere.pact.test.util.minicluster.NepheleMiniCluster.java
private static InterfaceAddress getIPInterfaceAddress(boolean preferIPv4) throws Exception, SocketException { final List<InterfaceAddress> interfaces = getNetworkInterface().getInterfaceAddresses(); final Iterator<InterfaceAddress> it = interfaces.iterator(); final List<InterfaceAddress> matchesIPv4 = new ArrayList<InterfaceAddress>(); final List<InterfaceAddress> matchesIPv6 = new ArrayList<InterfaceAddress>(); while (it.hasNext()) { final InterfaceAddress ia = it.next(); if (ia.getBroadcast() != null) { if (ia.getAddress() instanceof Inet4Address) { matchesIPv4.add(ia);//from www .j a v a2 s . co m } else { matchesIPv6.add(ia); } } } if (matchesIPv4.isEmpty() && matchesIPv6.isEmpty()) { throw new Exception( "Interface " + getNetworkInterface().getName() + " has no interface address attached."); } if (preferIPv4 && !matchesIPv4.isEmpty()) { for (InterfaceAddress ia : matchesIPv4) { if ((ia.getAddress().toString().contains("192") || ia.getAddress().toString().contains("10"))) { return ia; } } return matchesIPv4.get(0); } return !matchesIPv6.isEmpty() ? matchesIPv6.get(0) : matchesIPv4.get(0); }
From source file:org.openhab.binding.network.service.NetworkService.java
/** * Gets every IPv4 Address on each Interface except the loopback * The Address format is ip/subnet/*w ww . j a v a 2 s . c om*/ * * @return The collected IPv4 Addresses */ private static TreeSet<String> getInterfaceIPs() { TreeSet<String> interfaceIPs = new TreeSet<String>(); try { // For each interface ... for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface networkInterface = en.nextElement(); if (!networkInterface.isLoopback()) { // .. and for each address ... for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it .hasNext();) { // ... get IP and Subnet InterfaceAddress interfaceAddress = it.next(); interfaceIPs.add(interfaceAddress.getAddress().getHostAddress() + "/" + interfaceAddress.getNetworkPrefixLength()); } } } } catch (SocketException e) { } return interfaceIPs; }
From source file:nz.co.fortytwo.signalk.util.Util.java
public static boolean sameNetwork(String localAddress, String remoteAddress) throws Exception { InetAddress addr = InetAddress.getByName(localAddress); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(addr); short netmask = -1; for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if (address.getAddress().equals(addr)) { netmask = address.getNetworkPrefixLength(); }/*from w w w .ja v a 2s . c o m*/ } byte[] a1 = InetAddress.getByName(localAddress).getAddress(); byte[] a2 = InetAddress.getByName(remoteAddress).getAddress(); byte[] m = InetAddress.getByName(normalizeFromCIDR(netmask)).getAddress(); for (int i = 0; i < a1.length; i++) if ((a1[i] & m[i]) != (a2[i] & m[i])) return false; return true; }
From source file:eu.stratosphere.nephele.discovery.DiscoveryService.java
/** * Returns the set of broadcast addresses available to the network interfaces of this host. In case of IPv6 the set * contains the IPv6 multicast address to reach all nodes on the local link. Moreover, all addresses of the loopback * interfaces are added to the set.//from w w w. ja v a 2 s. co m * * @return (possibly empty) set of broadcast addresses reachable by this host */ private static Set<InetAddress> getBroadcastAddresses() { final Set<InetAddress> broadcastAddresses = new HashSet<InetAddress>(); // get all network interfaces Enumeration<NetworkInterface> ie = null; try { ie = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { LOG.error("Could not collect network interfaces of host", e); return broadcastAddresses; } while (ie.hasMoreElements()) { NetworkInterface nic = ie.nextElement(); try { if (!nic.isUp()) { continue; } if (nic.isLoopback()) { for (InterfaceAddress adr : nic.getInterfaceAddresses()) { broadcastAddresses.add(adr.getAddress()); } } else { // check all IPs bound to network interfaces for (InterfaceAddress adr : nic.getInterfaceAddresses()) { if (adr == null) { continue; } // collect all broadcast addresses if (USE_IPV6) { try { final InetAddress interfaceAddress = adr.getAddress(); if (interfaceAddress instanceof Inet6Address) { final Inet6Address ipv6Address = (Inet6Address) interfaceAddress; final InetAddress multicastAddress = InetAddress.getByName(IPV6MULTICASTADDRESS + "%" + Integer.toString(ipv6Address.getScopeId())); broadcastAddresses.add(multicastAddress); } } catch (UnknownHostException e) { LOG.error(e); } } else { final InetAddress broadcast = adr.getBroadcast(); if (broadcast != null) { broadcastAddresses.add(broadcast); } } } } } catch (SocketException e) { LOG.error("Socket exception when checking " + nic.getName() + ". " + "Ignoring this device.", e); } } return broadcastAddresses; }
From source file:android_network.hetnet.vpn_service.Util.java
public static String getNetworkInfo(Context context) { StringBuilder sb = new StringBuilder(); ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ani = cm.getActiveNetworkInfo(); List<NetworkInfo> listNI = new ArrayList<>(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) listNI.addAll(Arrays.asList(cm.getAllNetworkInfo())); else//from w w w . j av a 2 s . c om for (Network network : cm.getAllNetworks()) { NetworkInfo ni = cm.getNetworkInfo(network); if (ni != null) listNI.add(ni); } for (NetworkInfo ni : listNI) { sb.append(ni.getTypeName()).append('/').append(ni.getSubtypeName()).append(' ') .append(ni.getDetailedState()) .append(TextUtils.isEmpty(ni.getExtraInfo()) ? "" : " " + ni.getExtraInfo()) .append(ni.getType() == ConnectivityManager.TYPE_MOBILE ? " " + Util.getNetworkGeneration(ni.getSubtype()) : "") .append(ni.isRoaming() ? " R" : "") .append(ani != null && ni.getType() == ani.getType() && ni.getSubtype() == ani.getSubtype() ? " *" : "") .append("\r\n"); } try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); if (nis != null) while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); if (ni != null && !ni.isLoopback()) { List<InterfaceAddress> ias = ni.getInterfaceAddresses(); if (ias != null) for (InterfaceAddress ia : ias) sb.append(ni.getName()).append(' ').append(ia.getAddress().getHostAddress()) .append('/').append(ia.getNetworkPrefixLength()).append(' ') .append(ni.getMTU()).append(' ').append(ni.isUp() ? '^' : 'v') .append("\r\n"); } } } catch (Throwable ex) { sb.append(ex.toString()).append("\r\n"); } if (sb.length() > 2) sb.setLength(sb.length() - 2); return sb.toString(); }
From source file:com.master.metehan.filtereagle.Util.java
public static String getNetworkInfo(Context context) { StringBuilder sb = new StringBuilder(); ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ani = cm.getActiveNetworkInfo(); List<NetworkInfo> listNI = new ArrayList<>(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) listNI.addAll(Arrays.asList(cm.getAllNetworkInfo())); else// ww w . jav a2s . c o m for (Network network : cm.getAllNetworks()) { NetworkInfo ni = cm.getNetworkInfo(network); if (ni != null) listNI.add(ni); } for (NetworkInfo ni : listNI) { sb.append(ni.getTypeName()).append('/').append(ni.getSubtypeName()).append(' ') .append(ni.getDetailedState()) .append(TextUtils.isEmpty(ni.getExtraInfo()) ? "" : " " + ni.getExtraInfo()) .append(ni.getType() == ConnectivityManager.TYPE_MOBILE ? " " + Util.getNetworkGeneration(ni.getSubtype()) : "") .append(ni.isRoaming() ? " R" : "") .append(ani != null && ni.getType() == ani.getType() && ni.getSubtype() == ani.getSubtype() ? " *" : "") .append("\r\n"); } try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); if (nis != null) { sb.append("\r\n"); while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); if (ni != null) { List<InterfaceAddress> ias = ni.getInterfaceAddresses(); if (ias != null) for (InterfaceAddress ia : ias) sb.append(ni.getName()).append(' ').append(ia.getAddress().getHostAddress()) .append('/').append(ia.getNetworkPrefixLength()).append(' ') .append(ni.getMTU()).append("\r\n"); } } } } catch (Throwable ex) { sb.append(ex.toString()).append("\r\n"); } if (sb.length() > 2) sb.setLength(sb.length() - 2); return sb.toString(); }
From source file:org.chromium.ChromeSystemNetwork.java
private void getNetworkInterfaces(final CordovaArgs args, final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override/*from w w w .j av a 2 s . c o m*/ public void run() { try { JSONArray ret = new JSONArray(); ArrayList<NetworkInterface> interfaces = Collections .list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface iface : interfaces) { if (iface.isLoopback()) { continue; } for (InterfaceAddress interfaceAddress : iface.getInterfaceAddresses()) { InetAddress address = interfaceAddress.getAddress(); if (address == null) { continue; } JSONObject data = new JSONObject(); data.put("name", iface.getDisplayName()); // Strip address scope zones for IPv6 address. data.put("address", address.getHostAddress().replaceAll("%.*", "")); data.put("prefixLength", interfaceAddress.getNetworkPrefixLength()); ret.put(data); } } callbackContext.success(ret); } catch (Exception e) { Log.e(LOG_TAG, "Error occured while getting network interfaces", e); callbackContext.error("Could not get network interfaces"); } } }); }
From source file:org.openhab.binding.opensprinkler.discovery.OpenSprinklerDiscoveryService.java
/** * Provide a string list of all the IP addresses associated with the network interfaces on * this machine./*w ww . j a va2 s .c o m*/ * * @return String list of IP addresses. * @throws UnknownHostException * @throws SocketException */ private List<String> getIpAddressScanList() throws UnknownHostException, SocketException { List<String> results = new ArrayList<String>(); InetAddress localHost = InetAddress.getLocalHost(); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost); for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { InetAddress ipAddress = address.getAddress(); String cidrSubnet = ipAddress.getHostAddress() + "/" + DISCOVERY_SUBNET_MASK; /* Apache Subnet Utils only supports IP v4 for creating string list of IP's */ if (ipAddress instanceof Inet4Address) { logger.debug("Found interface IPv4 address to scan: {}", cidrSubnet); SubnetUtils utils = new SubnetUtils(cidrSubnet); results.addAll(Arrays.asList(utils.getInfo().getAllAddresses())); } else if (ipAddress instanceof Inet6Address) { logger.debug("Found interface IPv6 address to scan: {}", cidrSubnet); } else { logger.debug("Found interface unknown IP type address to scan: {}", cidrSubnet); } } return results; }
From source file:org.openremote.controller.service.BeehiveCommandCheckService.java
public static String getMACAddresses() throws Exception { StringBuilder macs = new StringBuilder(); Enumeration<NetworkInterface> enum1 = NetworkInterface.getNetworkInterfaces(); while (enum1.hasMoreElements()) { NetworkInterface networkInterface = enum1.nextElement(); if (!networkInterface.isLoopback()) { boolean onlyLinkLocal = true; for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { if (!interfaceAddress.getAddress().isLinkLocalAddress()) { onlyLinkLocal = false; }/*from w ww.j a v a 2s .c o m*/ } if (onlyLinkLocal) { continue; } byte[] mac = networkInterface.getHardwareAddress(); if (mac != null) { macs.append(getMACString(networkInterface.getHardwareAddress())); macs.append(","); } } } if (macs.length() == 0) { return "no-mac-address-found"; } macs.deleteCharAt(macs.length() - 1); return macs.toString(); }
From source file:org.openhab.binding.zway.internal.discovery.ZWayBridgeDiscoveryService.java
private void scan() { logger.debug("Starting scan for Z-Way Server"); ValidateIPV4 validator = new ValidateIPV4(); try {/*from w ww . ja v a 2s . c om*/ Enumeration<NetworkInterface> enumNetworkInterface = NetworkInterface.getNetworkInterfaces(); while (enumNetworkInterface.hasMoreElements()) { NetworkInterface networkInterface = enumNetworkInterface.nextElement(); if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) { for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { if (validator.isValidIPV4(address.getAddress().getHostAddress())) { String ipAddress = address.getAddress().getHostAddress(); Short prefix = address.getNetworkPrefixLength(); logger.debug("Scan IP address for Z-Way Server: {}", ipAddress); // Search on localhost first scheduler.execute(new ZWayServerScan(ipAddress)); String subnet = ipAddress + "/" + prefix; SubnetUtils utils = new SubnetUtils(subnet); String[] addresses = utils.getInfo().getAllAddresses(); for (String addressInSubnet : addresses) { scheduler.execute(new ZWayServerScan(addressInSubnet)); } } } } } } catch (SocketException e) { logger.warn("Error occurred while searching Z-Way servers ({})", e.getMessage()); } }