List of usage examples for java.net NetworkInterface getNetworkInterfaces
public static Enumeration<NetworkInterface> getNetworkInterfaces() throws SocketException
From source file:de.pawlidi.openaletheia.utils.AletheiaUtils.java
/** * /*from ww w . jav a2 s. co m*/ * @return * @throws UnknownHostException */ public static InetAddress getLocalIpAddress() throws UnknownHostException { try { InetAddress localAddress = null; // load all existed network interfaces for (Enumeration<?> networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces .hasMoreElements();) { NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement(); for (Enumeration<?> ipAddresses = networkInterface.getInetAddresses(); ipAddresses .hasMoreElements();) { InetAddress ipAddress = (InetAddress) ipAddresses.nextElement(); if (!ipAddress.isLoopbackAddress()) { if (ipAddress.isSiteLocalAddress()) { return ipAddress; } else if (localAddress == null) { localAddress = ipAddress; } } } } if (localAddress != null) { return localAddress; } // try to get localhost address localAddress = InetAddress.getLocalHost(); if (localAddress == null) { throw new UnknownHostException("Could not load localhost ip address"); } return localAddress; } catch (Exception e) { UnknownHostException unknownHostException = new UnknownHostException( "Could not load localhost ip address " + e); unknownHostException.initCause(e); throw unknownHostException; } }
From source file:org.mule.module.http.functional.listener.HttpListenerConfigFunctionalTestCase.java
private String getNonLocalhostIp() { try {//from w ww . j a v a 2 s. c om Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface networkInterface : Collections.list(nets)) { final Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); if (!inetAddress.isLoopbackAddress() && IPADDRESS_PATTERN.matcher(inetAddress.getHostAddress()).find()) { return inetAddress.getHostAddress(); } } } throw new RuntimeException("Could not find network interface different from localhost"); } catch (SocketException e) { throw new RuntimeException(e); } }
From source file:net.straylightlabs.archivo.controller.TelemetryController.java
private static List<String> getNetworkInterfaces() { List<String> nics = new ArrayList<>(); try {//from w w w .j av a 2 s .c o m for (NetworkInterface nic : Collections.list(NetworkInterface.getNetworkInterfaces())) { if (nic.isUp()) nics.add(String.format( "name='%s' isLoopback=%b isP2P=%b isVirtual=%b multicast=%b addresses=[%s]\n", nic.getDisplayName(), nic.isLoopback(), nic.isPointToPoint(), nic.isVirtual(), nic.supportsMulticast(), getAddressesAsString(nic))); } } catch (SocketException e) { logger.error("Error fetching network interface list: ", e); } return nics; }
From source file:com.jiangyifen.ec2.globaldata.license.LicenseManager.java
/** * "xx-xx-xx-xx-xx-xx"??MAC?//ww w .j a v a2s. c o m * * @return * @throws Exception */ private static List<String> getMacAddressList() { List<String> macAddressList = new ArrayList<String>(); try { Enumeration<NetworkInterface> ni = NetworkInterface.getNetworkInterfaces(); while (ni.hasMoreElements()) { NetworkInterface netI = ni.nextElement(); byte[] bytes = netI.getHardwareAddress(); if (netI.isUp() && netI != null && bytes != null && bytes.length == 6) { StringBuffer sb = new StringBuffer(); for (byte b : bytes) { // 11110000????4? sb.append(Integer.toHexString((b & 240) >> 4)); // 00001111????4? sb.append(Integer.toHexString(b & 15)); sb.append("-"); } sb.deleteCharAt(sb.length() - 1); macAddressList.add(sb.toString().toLowerCase()); } } } catch (Exception e) { e.printStackTrace(); } return macAddressList; }
From source file:net.padlocksoftware.padlock.DefaultMacAddressProvider.java
private Set<String> getMACAddresses() { Set<String> addresses = new HashSet<String>(); if (!FORCE_MACADDR_SHELL) { try {/*from w ww .j ava 2 s .c o m*/ Method method = NetworkInterface.class.getMethod("getHardwareAddress", (Class[]) null); Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces(); if (ifs != null) { while (ifs.hasMoreElements()) { NetworkInterface iface = ifs.nextElement(); byte[] hardware = (byte[]) method.invoke(iface); if (hardware != null && hardware.length == 6 && hardware[1] != (byte) 0xff) { if (permitVMAddresses || !isVirtualAddress(hardware)) { addresses.add(new String(Hex.encodeHex(hardware))); } } } } } catch (Exception ex) { logger.log(Level.FINE, null, ex); } // may not have found any if (!addresses.isEmpty()) { return addresses; } } // otherwise default to JDK1.5 way return useShellToFindAddresses(); }
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//from w w w . ja 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:org.apache.marmotta.platform.security.services.SecurityServiceImpl.java
/** * Parse host patterns into subnet information. A host pattern has one of the following forms: * <ul>/*from w w w .ja va 2 s. c o m*/ * <li>LOCAL, meaning all local interfaces</li> * <li>x.x.x.x/yy, meaning an IPv4 CIDR address with netmask (number of bits significant for the network, max 32), e.g. 192.168.100.0/24 </li> * <li>xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/yy, meaning an IPv6 CIDR address with netmask (prefix length, max 128)</li> * </ul> * @param hostPatternStrings * @return */ private Set<SubnetInfo> parseHostAddresses(List<String> hostPatternStrings) { HashSet<SubnetInfo> hostPatterns = new HashSet<SubnetInfo>(); for (String host : hostPatternStrings) { try { // reserved name: LOCAL maps to all local addresses if ("LOCAL".equalsIgnoreCase(host)) { try { Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces(); while (ifs.hasMoreElements()) { NetworkInterface iface = ifs.nextElement(); Enumeration<InetAddress> addrs = iface.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); try { hostPatterns.add(SubnetInfo.getSubnetInfo(addr)); } catch (UnknownHostException e) { log.warn("could not parse interface address: {}", e.getMessage()); } } } } catch (SocketException ex) { log.warn("could not determine local IP addresses, will use 127.0.0.1/24"); try { hostPatterns.add(SubnetInfo.getSubnetInfo("127.0.0.1/24")); // IPv4 hostPatterns.add(SubnetInfo.getSubnetInfo("::1/128")); // IPv6 } catch (UnknownHostException e) { log.error("could not parse localhost address: {}", e.getMessage()); } } } else if (host.matches("^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\\./[0-9]+$")) { // CIDR notation try { hostPatterns.add(SubnetInfo.getSubnetInfo(host)); } catch (UnknownHostException e) { log.warn("could not parse host specification '{}': {}", host, e.getMessage()); } } else if (host.matches("^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$")) { // IP address try { hostPatterns.add(SubnetInfo.getSubnetInfo(host + "/32")); } catch (UnknownHostException e) { log.warn("could not parse host specification '{}': {}", host, e.getMessage()); } } else if (IPAddressUtil.isIPv6LiteralAddress(host)) { // IPv6 address try { hostPatterns.add(SubnetInfo.getSubnetInfo(host)); } catch (UnknownHostException e) { log.warn("could not parse host specification '{}': {}", host, e.getMessage()); } } else { log.warn( "invalid host name specification: {}; please use either CIDR u.v.w.x/zz notation or the keyword LOCAL", host); } } catch (IllegalArgumentException ex) { log.warn("illegal host specification for security constraint {}; not in CIDR notation!", host); } } return hostPatterns; }
From source file:org.kchine.rpf.PoolUtils.java
public static String getIPAddressFromNetworkInterfaces() { Vector<String> IPs = new Vector<String>(); try {/*w w w . j a va 2s . co m*/ NetworkInterface iface = null; for (Enumeration<?> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) { iface = (NetworkInterface) ifaces.nextElement(); InetAddress ia = null; for (Enumeration<?> ips = iface.getInetAddresses(); ips.hasMoreElements();) { ia = (InetAddress) ips.nextElement(); boolean matches = isValidIPAddress(ia.getHostAddress()) && !isLoopBackIP(ia.getHostAddress()); if (matches) { IPs.add(ia.getHostAddress()); } } } } catch (Exception e) { e.printStackTrace(); } if (IPs.size() == 1) return IPs.elementAt(0); return null; }
From source file:com.zz.cluster4spring.localinfo.DefaultLocalNetworkInfoProvider.java
public List<String> getLocalHostAddresses(InetAddressAcceptor aAcceptor) throws SocketException { List<String> result = new ArrayList<String>(); Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); if (aAcceptor.acceptNetworkInterface(networkInterface)) { if (fLog.isInfoEnabled()) { String name = networkInterface.getName(); String displayName = networkInterface.getDisplayName(); fLog.info(MessageFormat.format( "Discovered NetworkInterface - ACCEPTED. Name:[{0}]. Display Name:[{1}]", name, displayName));/*from w ww.ja va 2 s .c om*/ } collectInterfaceIPs(networkInterface, result, aAcceptor); } else if (fLog.isInfoEnabled()) { String name = networkInterface.getName(); String displayName = networkInterface.getDisplayName(); fLog.info(MessageFormat.format( "Discovered NetworkInterface - SKIPPED. Name:[{0}]. Display Name:[{1}]", name, displayName)); } } return result; }
From source file:com.scottieknows.test.cassandra.CassandraClusterManager.java
/** * @return {@link Map} of interface name to address *//*w w w . j a v a 2s .c o m*/ Map<String, String> getIpsStartingWith(String prefix) { if (prefix == null) { return Collections.emptyMap(); } try { Map<String, String> rtn = new HashMap<>(); Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface i = networkInterfaces.nextElement(); Enumeration<InetAddress> addrs = i.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); String hostAddress = addr.getHostAddress(); if (hostAddress.startsWith(prefix)) { rtn.put(i.getName(), hostAddress); } } } return rtn; } catch (SocketException e) { throw new RuntimeException("could not retrieve network interfaces: " + e, e); } }