Java Code Examples for java.net.NetworkInterface#isPointToPoint()

The following examples show how to use java.net.NetworkInterface#isPointToPoint() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NetworkConfiguration.java    From openjdk-jdk9 with GNU General Public License v2.0 9 votes vote down vote up
/**
 * Return a NetworkConfiguration instance.
 */
public static NetworkConfiguration probe() throws IOException {
    Map<NetworkInterface, List<Inet4Address>> ip4Interfaces = new HashMap<>();
    Map<NetworkInterface, List<Inet6Address>> ip6Interfaces = new HashMap<>();

    List<NetworkInterface> nifs = list(getNetworkInterfaces());
    for (NetworkInterface nif : nifs) {
        // ignore interfaces that are down
        if (!nif.isUp() || nif.isPointToPoint())
            continue;

        List<Inet4Address> ip4Addresses = new LinkedList<>();
        List<Inet6Address> ip6Addresses = new LinkedList<>();
        ip4Interfaces.put(nif, ip4Addresses);
        ip6Interfaces.put(nif, ip6Addresses);
        for (InetAddress addr : list(nif.getInetAddresses())) {
            if (addr instanceof Inet4Address)
                ip4Addresses.add((Inet4Address)addr);
            else if (addr instanceof Inet6Address)
                ip6Addresses.add((Inet6Address)addr);
        }
    }
    return new NetworkConfiguration(ip4Interfaces, ip6Interfaces);
}
 
Example 2
Source File: Tethering.java    From InviZible with GNU General Public License v3.0 6 votes vote down vote up
private void setVpnInterfaceName(NetworkInterface intf) throws SocketException {

        if (!intf.isPointToPoint()) {
            return;
        }

        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
             enumIpAddr.hasMoreElements(); ) {
            InetAddress inetAddress = enumIpAddr.nextElement();
            String hostAddress = inetAddress.getHostAddress();

            if (hostAddress.contains(addressVPN)) {
                vpnInterfaceName = intf.getName();
                Log.i(LOG_TAG, "VPN interface name " + vpnInterfaceName);
            }
        }
    }
 
Example 3
Source File: NetworkConfiguration.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return a NetworkConfiguration instance.
 */
public static NetworkConfiguration probe() throws IOException {
    Map<NetworkInterface, List<Inet4Address>> ip4Interfaces = new HashMap<>();
    Map<NetworkInterface, List<Inet6Address>> ip6Interfaces = new HashMap<>();

    List<NetworkInterface> nifs = list(getNetworkInterfaces());
    for (NetworkInterface nif : nifs) {
        // ignore interfaces that are down
        if (!nif.isUp() || nif.isPointToPoint()) {
            continue;
        }

        List<Inet4Address> ip4Addresses = new LinkedList<>();
        List<Inet6Address> ip6Addresses = new LinkedList<>();
        ip4Interfaces.put(nif, ip4Addresses);
        ip6Interfaces.put(nif, ip6Addresses);
        for (InetAddress addr : list(nif.getInetAddresses())) {
            if (addr instanceof Inet4Address) {
                ip4Addresses.add((Inet4Address) addr);
            } else if (addr instanceof Inet6Address) {
                ip6Addresses.add((Inet6Address) addr);
            }
        }
    }
    return new NetworkConfiguration(ip4Interfaces, ip6Interfaces);
}
 
Example 4
Source File: ClusterMetadataManager.java    From onos with Apache License 2.0 6 votes vote down vote up
private IpAddress findLocalIp() throws SocketException {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface iface = interfaces.nextElement();
        if (iface.isLoopback() || iface.isPointToPoint()) {
            continue;
        }

        Enumeration<InetAddress> inetAddresses = iface.getInetAddresses();
        while (inetAddresses.hasMoreElements()) {
            InetAddress inetAddress = inetAddresses.nextElement();
            if (inetAddress instanceof Inet4Address) {
                Inet4Address inet4Address = (Inet4Address) inetAddress;
                try {
                    if (!inet4Address.getHostAddress().equals(InetAddress.getLocalHost().getHostAddress())) {
                        return IpAddress.valueOf(inetAddress);
                    }
                } catch (UnknownHostException e) {
                    return IpAddress.valueOf(inetAddress);
                }
            }
        }
    }
    throw new IllegalStateException("Unable to determine local ip");
}
 
Example 5
Source File: IfConfig.java    From crate with Apache License 2.0 6 votes vote down vote up
/** format network interface flags */
private static String formatFlags(NetworkInterface nic) throws SocketException {
    StringBuilder flags = new StringBuilder();
    if (nic.isUp()) {
        flags.append("UP ");
    }
    if (nic.supportsMulticast()) {
        flags.append("MULTICAST ");
    }
    if (nic.isLoopback()) {
        flags.append("LOOPBACK ");
    }
    if (nic.isPointToPoint()) {
        flags.append("POINTOPOINT ");
    }
    if (nic.isVirtual()) {
        flags.append("VIRTUAL ");
    }
    flags.append("mtu:").append(nic.getMTU());
    flags.append(" index:").append(nic.getIndex());
    return flags.toString();
}
 
Example 6
Source File: NetworkHelper.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Workaround ambiguous InetAddress.getLocalHost() on Linux-based systems.
 *
 * @see <a href="http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4665037">http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4665037</a>
 */
public static String findLocalHostAddress() throws Exception {
  // first look for a local address which isn't the loopback interface or P2P/VPN
  Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
  while (interfaces.hasMoreElements()) {
    NetworkInterface intf = interfaces.nextElement();
    if (intf.isUp() && !intf.isLoopback() && !intf.isPointToPoint() && !intf.isVirtual()) {
      Enumeration<InetAddress> addresses = intf.getInetAddresses();
      while (addresses.hasMoreElements()) {
        InetAddress addr = addresses.nextElement();
        if (addr.isSiteLocalAddress() && !addr.isLoopbackAddress()) {
          return addr.getHostAddress();
        }
      }
    }
  }
  // otherwise fall back to the JDKs 'guesstimate'
  return InetAddress.getLocalHost().getHostAddress();
}
 
Example 7
Source File: NetworkUtils.java    From kylin with Apache License 2.0 6 votes vote down vote up
public static String getLocalIp() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
                continue;
            if (iface.getName().startsWith("vboxnet"))
                continue;

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                final String ip = addr.getHostAddress();
                if (Inet4Address.class == addr.getClass())
                    return ip;
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
Example 8
Source File: DhcpInterfaceManager.java    From dhcp4j with Apache License 2.0 6 votes vote down vote up
@Override
public boolean apply(NetworkInterface iface) {
    try {
        if (iface == null) {
            LOG.debug("Ignoring NetworkInterface: null!");
            return false;
        }
        // Bridges claim to be down when no attached interfaces are up. :-(
        // if (false && !iface.isUp()) { LOG.debug("Ignoring NetworkInterface: Down: {}", iface); return false; }
        if (iface.isLoopback()) {
            LOG.debug("Ignoring NetworkInterface: Loopback: {}", iface);
            return false;
        }
        if (iface.isPointToPoint()) {
            LOG.debug("Ignoring NetworkInterface: PointToPoint: {}", iface);
            return false;
        }
        return true;
    } catch (SocketException e) {
        LOG.error("Failed to query " + iface, e);
        return false;
    }
}
 
Example 9
Source File: NetUtil.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @deprecated Please use the NetworkAddressService with {@link #getPrimaryIpv4HostAddress()}
 *
 *             Get the first candidate for a local IPv4 host address (non loopback, non localhost).
 */
@Deprecated
public static @Nullable String getLocalIpv4HostAddress() {
    try {
        String hostAddress = null;
        final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            final NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
                continue;
            }
            final Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                final InetAddress currentAddr = addresses.nextElement();
                if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
                    continue;
                }
                if (hostAddress != null) {
                    LOGGER.warn("Found multiple local interfaces - ignoring {}", currentAddr.getHostAddress());
                } else {
                    hostAddress = currentAddr.getHostAddress();
                }
            }
        }
        return hostAddress;
    } catch (SocketException ex) {
        LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
        return null;
    }
}
 
Example 10
Source File: NetUtil.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private @Nullable String getFirstLocalIPv4Address() {
    try {
        String hostAddress = null;
        final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            final NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
                continue;
            }
            final Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                final InetAddress currentAddr = addresses.nextElement();
                if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
                    continue;
                }
                if (hostAddress != null) {
                    LOGGER.warn("Found multiple local interfaces - ignoring {}", currentAddr.getHostAddress());
                } else {
                    hostAddress = currentAddr.getHostAddress();
                }
            }
        }
        return hostAddress;
    } catch (SocketException ex) {
        LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
        return null;
    }
}
 
Example 11
Source File: NetUtil.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @deprecated Please use the NetworkAddressService with {@link #getPrimaryIpv4HostAddress()}
 *
 *             Get the first candidate for a local IPv4 host address (non loopback, non localhost).
 */
@Deprecated
public static @Nullable String getLocalIpv4HostAddress() {
    try {
        String hostAddress = null;
        final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            final NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
                continue;
            }
            final Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                final InetAddress currentAddr = addresses.nextElement();
                if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
                    continue;
                }
                if (hostAddress != null) {
                    LOGGER.warn("Found multiple local interfaces - ignoring {}", currentAddr.getHostAddress());
                } else {
                    hostAddress = currentAddr.getHostAddress();
                }
            }
        }
        return hostAddress;
    } catch (SocketException ex) {
        LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
        return null;
    }
}
 
Example 12
Source File: NetworkInterfaceTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testDumpAll() throws Exception {
    Set<String> allNames = new HashSet<String>();
    Set<Integer> allIndexes = new HashSet<Integer>();
    for (NetworkInterface nif : Collections.list(NetworkInterface.getNetworkInterfaces())) {
        //System.err.println(nif);
        //System.err.println(nif.getInterfaceAddresses());
        String flags = nif.isUp() ? "UP" : "DOWN";
        if (nif.isLoopback()) {
            flags += " LOOPBACK";
        }
        if (nif.isPointToPoint()) {
            flags += " PTP";
        }
        if (nif.isVirtual()) {
            flags += " VIRTUAL";
        }
        if (nif.supportsMulticast()) {
            flags += " MULTICAST";
        }
        flags += " MTU=" + nif.getMTU();
        byte[] mac = nif.getHardwareAddress();
        if (mac != null) {
            flags += " HWADDR=";
            for (int i = 0; i < mac.length; ++i) {
                if (i > 0) {
                    flags += ":";
                }
                flags += String.format("%02x", mac[i]);
            }
        }
        //System.err.println(flags);
        //System.err.println("-");

        assertFalse(allNames.contains(nif.getName()));
        allNames.add(nif.getName());

        assertFalse(allIndexes.contains(nif.getIndex()));
        allIndexes.add(nif.getIndex());
    }
}
 
Example 13
Source File: XidFactoryImpl.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static byte[] getHardwareAddress() {
	Enumeration<NetworkInterface> enumeration = null;
	try {
		enumeration = NetworkInterface.getNetworkInterfaces();
	} catch (Exception ex) {
		logger.debug(ex.getMessage(), ex);
	}

	byte[] byteArray = null;
	while (byteArray == null && enumeration != null && enumeration.hasMoreElements()) {
		NetworkInterface element = enumeration.nextElement();

		try {
			if (element.isUp() == false) {
				continue;
			} else if (element.isPointToPoint() || element.isVirtual()) {
				continue;
			} else if (element.isLoopback()) {
				continue;
			}

			byte[] hardwareAddr = element.getHardwareAddress();
			if (hardwareAddr == null || hardwareAddr.length != SIZE_OF_MAC) {
				continue;
			}

			byteArray = new byte[SIZE_OF_MAC];
			System.arraycopy(hardwareAddr, 0, byteArray, 0, SIZE_OF_MAC);
		} catch (Exception rex) {
			logger.debug(rex.getMessage(), rex);
		}
	}

	return byteArray != null ? byteArray : new byte[SIZE_OF_MAC];
}
 
Example 14
Source File: NetUtil.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private @Nullable String getFirstLocalIPv4Address() {
    try {
        String hostAddress = null;
        final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            final NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
                continue;
            }
            final Enumeration<InetAddress> addresses = current.getInetAddresses();
            while (addresses.hasMoreElements()) {
                final InetAddress currentAddr = addresses.nextElement();
                if (currentAddr.isLoopbackAddress() || (currentAddr instanceof Inet6Address)) {
                    continue;
                }
                if (hostAddress != null) {
                    LOGGER.warn("Found multiple local interfaces - ignoring {}", currentAddr.getHostAddress());
                } else {
                    hostAddress = currentAddr.getHostAddress();
                }
            }
        }
        return hostAddress;
    } catch (SocketException ex) {
        LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
        return null;
    }
}
 
Example 15
Source File: PointToPointInterfaceCriteria.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @return <code>address</code> if <code>networkInterface</code> is a
 *         {@link NetworkInterface#isPointToPoint() point-to-point interface}.
 */
@Override
protected InetAddress isAcceptable(NetworkInterface networkInterface, InetAddress address) throws SocketException {

    if( networkInterface.isPointToPoint() )
        return address;
    return null;
}
 
Example 16
Source File: NetUtil.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private @Nullable String getIPv4inSubnet(String ipAddress, String subnetMask) {
    try {
        final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            final NetworkInterface current = interfaces.nextElement();
            if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
                continue;
            }

            for (InterfaceAddress ifAddr : current.getInterfaceAddresses()) {
                InetAddress addr = ifAddr.getAddress();

                if (addr.isLoopbackAddress() || (addr instanceof Inet6Address)) {
                    continue;
                }

                String ipv4AddressOnInterface = addr.getHostAddress();
                String subnetStringOnInterface = getIpv4NetAddress(ipv4AddressOnInterface,
                        ifAddr.getNetworkPrefixLength()) + "/" + String.valueOf(ifAddr.getNetworkPrefixLength());

                String configuredSubnetString = getIpv4NetAddress(ipAddress, Short.parseShort(subnetMask)) + "/"
                        + subnetMask;

                // use first IP within this subnet
                if (subnetStringOnInterface.equals(configuredSubnetString)) {
                    return ipv4AddressOnInterface;
                }
            }
        }
    } catch (SocketException ex) {
        LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
    }
    return null;
}
 
Example 17
Source File: Server.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
* Get non-loopback address.  InetAddress.getLocalHost() does not work on machines without static ip address.
*
* @param ni target network interface
* @param preferIPv4 true iff require IPv4 addresses only
* @param preferIPv6 true iff prefer IPv6 addresses
* @return nonLoopback {@link InetAddress}
* @throws SocketException
*/
private static InetAddress getFirstNonLoopbackAddress(NetworkInterface ni,
                                                      boolean preferIPv4,
                                                      boolean preferIPv6) throws SocketException {
    InetAddress result = null;

    // skip virtual interface name, PTP and non-running interface.
    if (ni.isVirtual() || ni.isPointToPoint() || ! ni.isUp()) {
        return result;
    }
    LOG.info("Interface name is: " + ni.getDisplayName());
    for (Enumeration en2 = ni.getInetAddresses(); en2.hasMoreElements(); ) {
        InetAddress addr = (InetAddress) en2.nextElement();
        if (!addr.isLoopbackAddress()) {
            if (addr instanceof Inet4Address) {
                if (preferIPv6) {
                    continue;
                }
                result = addr;
                break;
            }

            if (addr instanceof Inet6Address) {
                if (preferIPv4) {
                    continue;
                }
                result = addr;
                break;
            }
        }
    }
    return result;
}
 
Example 18
Source File: ServiceInstanceBuilder.java    From curator with Apache License 2.0 4 votes vote down vote up
@Override
public boolean use(NetworkInterface nif, InetAddress adr) throws SocketException
{
    return (adr != null) && !adr.isLoopbackAddress() && (nif.isPointToPoint() || !adr.isLinkLocalAddress());
}
 
Example 19
Source File: Tethering.java    From InviZible with GNU General Public License v3.0 4 votes vote down vote up
void setInterfaceNames() {
    final String addressesRangeUSB = "192.168.42.";
    final String addressesRangeWiFi = "192.168.43.";

    usbTetherOn = false;
    ethernetOn = false;

    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
             en.hasMoreElements(); ) {

            NetworkInterface intf = en.nextElement();

            if (intf.isLoopback()) {
                continue;
            }
            if (intf.isVirtual()) {
                continue;
            }
            if (!intf.isUp()) {
                continue;
            }

            setVpnInterfaceName(intf);

            if (intf.isPointToPoint()) {
                continue;
            }
            if (intf.getHardwareAddress() == null) {
                continue;
            }

            if (intf.getName().replaceAll("\\d+", "").equalsIgnoreCase("eth")) {
                ethernetOn = true;
                ethernetInterfaceName = intf.getName();
                Log.i(LOG_TAG, "LAN interface name " + ethernetInterfaceName);
            }

            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                 enumIpAddr.hasMoreElements(); ) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                String hostAddress = inetAddress.getHostAddress();

                if (hostAddress.contains(addressesRangeWiFi)) {
                    this.apIsOn = true;
                    wifiAPInterfaceName = intf.getName();
                    Log.i(LOG_TAG, "WiFi AP interface name " + wifiAPInterfaceName);
                }

                if (hostAddress.contains(addressesRangeUSB)) {
                    usbTetherOn = true;
                    usbModemInterfaceName = intf.getName();
                    Log.i(LOG_TAG, "USB Modem interface name " + usbModemInterfaceName);
                }
            }
        }
    } catch (SocketException e) {
        Log.e(LOG_TAG, "Tethering SocketException " + e.getMessage() + " " + e.getCause());
    }

    if (usbTetherOn && !new PrefManager(context).getBoolPref("ModemIsON")) {
        new PrefManager(context).setBoolPref("ModemIsON", true);
        ModulesStatus.getInstance().setIptablesRulesUpdateRequested(context, true);
    } else if (!usbTetherOn && new PrefManager(context).getBoolPref("ModemIsON")) {
        new PrefManager(context).setBoolPref("ModemIsON", false);
        ModulesStatus.getInstance().setIptablesRulesUpdateRequested(context, true);
    }
}
 
Example 20
Source File: Hello.java    From blog_demos with Apache License 2.0 2 votes vote down vote up
/**
 * 过滤回环网卡、点对点网卡、非活动网卡、虚拟网卡并要求网卡名字是eth或ens开头
 * @param ni 网卡
 * @return 如果满足要求则true,否则false
 */
private static boolean isValidInterface(NetworkInterface ni) throws SocketException {
    return !ni.isLoopback() && !ni.isPointToPoint() && ni.isUp() && !ni.isVirtual()
            && (ni.getName().startsWith("eth") || ni.getName().startsWith("ens"));
}