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

The following examples show how to use java.net.NetworkInterface#isUp() . 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: UdpServerTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("JdkObsolete")
private boolean isMulticastEnabledIPv4Interface(NetworkInterface iface) {
	try {
		if (!iface.supportsMulticast() || !iface.isUp()) {
			return false;
		}
	}
	catch (SocketException se) {
		return false;
	}

	// Suppressed "JdkObsolete", usage of Enumeration is deliberate
	for (Enumeration<InetAddress> i = iface.getInetAddresses(); i.hasMoreElements(); ) {
		InetAddress address = i.nextElement();
		if (address.getClass() == Inet4Address.class) {
			return true;
		}
	}

	return false;
}
 
Example 2
Source File: VoidParameterServer.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns set of local IP addresses available in system.
 *
 * PLEASE NOTE: loopback, disabled interfaces, IPv6 addresses are ignored here.
 *
 * @return
 */
public static Set<String> getLocalAddresses() {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        Set<String> result = new HashSet<>();

        for (NetworkInterface networkInterface : interfaces) {
            if (networkInterface.isLoopback() || !networkInterface.isUp())
                continue;

            for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
                String addr = address.getAddress().getHostAddress();

                if (addr == null || addr.isEmpty() || addr.contains(":"))
                    continue;

                result.add(addr);
            }
        }

        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: WSDiscoveryClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
static NetworkInterface findIpv4Interface() throws Exception {
    Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces();
    List<NetworkInterface> possibles = new ArrayList<>();
    while (ifcs.hasMoreElements()) {
        NetworkInterface ni = ifcs.nextElement();
        if (ni.supportsMulticast()
            && ni.isUp()) {
            for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                if (ia.getAddress() instanceof java.net.Inet4Address
                    && !ia.getAddress().isLoopbackAddress()
                    && !ni.getDisplayName().startsWith("vnic")) {
                    possibles.add(ni);
                }
            }
        }
    }
    return possibles.isEmpty() ? null : possibles.get(possibles.size() - 1);
}
 
Example 4
Source File: NetworkUtils.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
public static InetAddress getFirstNonLoopbackAddress(ProtocolVersion ip_version) throws SocketException {
    InetAddress address;
    for (NetworkInterface networkInterface : getNetworkInterfaces()) {
        try {
            if (!networkInterface.isUp() || networkInterface.isLoopback()) {
                continue;
            }
        } catch (Exception e) {
            continue;
        }
        address = getFirstNonLoopbackAddress(networkInterface, ip_version);
        if (address != null) {
            return address;
        }
    }
    return null;
}
 
Example 5
Source File: VoidParameterServer.java    From nd4j with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns set of local IP addresses available in system.
 *
 * PLEASE NOTE: loopback, disabled interfaces, IPv6 addresses are ignored here.
 *
 * @return
 */
public static Set<String> getLocalAddresses() {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        Set<String> result = new HashSet<>();

        for (NetworkInterface networkInterface : interfaces) {
            if (networkInterface.isLoopback() || !networkInterface.isUp())
                continue;

            for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
                String addr = address.getAddress().getHostAddress();

                if (addr == null || addr.isEmpty() || addr.contains(":"))
                    continue;

                result.add(addr);
            }
        }

        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: LightwaveRFReceiverThread.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets a list of INetAddresses for this server. Allowing us to filter out
 * broadcast packets we receive that we originally sent
 * 
 * @return
 */
private Set<InetAddress> getIpAddresses() {
    Set<InetAddress> ips = new LinkedHashSet<InetAddress>();
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface iface = interfaces.nextElement();
            // filters out 127.0.0.1 and inactive interfaces
            if (iface.isLoopback() || !iface.isUp()) {
                continue;
            }

            Enumeration<InetAddress> addresses = iface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                ips.add(addr);
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return ips;
}
 
Example 7
Source File: HeisenbergServer.java    From heisenberg with Apache License 2.0 6 votes vote down vote up
private static String getIpAddress() {
    try {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint()
                    || !netInterface.isUp()) {
                continue;
            } else {
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        LOGGER.info("ip地址为:" + ip.getHostAddress());
                        return ip.getHostAddress();
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("IP地址获取失败", e);
    }
    return "";
}
 
Example 8
Source File: NetworkUtils.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/** Returns addresses for the given interface (it must be marked up) */
static InetAddress[] getAddressesForInterface(String name) throws SocketException {
    NetworkInterface intf = NetworkInterface.getByName(name);
    if (intf == null) {
        throw new IllegalArgumentException("No interface named '" + name + "' found, got " + getInterfaces());
    }
    if (!intf.isUp()) {
        throw new IllegalArgumentException("Interface '" + name + "' is not up and running");
    }
    List<InetAddress> list = Collections.list(intf.getInetAddresses());
    if (list.isEmpty()) {
        throw new IllegalArgumentException("Interface '" + name + "' has no internet addresses");
    }
    return list.toArray(new InetAddress[list.size()]);
}
 
Example 9
Source File: NetworkUtils.java    From crate with Apache License 2.0 5 votes vote down vote up
/** Returns all addresses (any scope) for interfaces that are up.
 *  This is only used to pick a publish address, when the user set network.host to a wildcard */
static InetAddress[] getAllAddresses() throws SocketException {
    List<InetAddress> list = new ArrayList<>();
    for (NetworkInterface intf : getInterfaces()) {
        if (intf.isUp()) {
            for (InetAddress address : Collections.list(intf.getInetAddresses())) {
                list.add(address);
            }
        }
    }
    if (list.isEmpty()) {
        throw new IllegalArgumentException("No up-and-running addresses found, got " + getInterfaces());
    }
    return list.toArray(new InetAddress[list.size()]);
}
 
Example 10
Source File: OverallInterfaceCriteriaUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testMultipleCriteria() throws Exception {

    Assume.assumeFalse(nonLoopBackInterfaces.size() < 1 || loopbackInterfaces.size() < 1);

    Map<NetworkInterface, Set<InetAddress>> correct = new HashMap<NetworkInterface, Set<InetAddress>>();
    for (NetworkInterface ni : loopbackInterfaces) {
        if (ni.isUp()) {
            correct.put(ni, getRightTypeAddresses(allCandidates.get(ni)));
        }
    }

    Assume.assumeFalse(correct.size() == 0);

    Set<InterfaceCriteria> criterias = new HashSet<InterfaceCriteria>();
    criterias.add(UpInterfaceCriteria.INSTANCE);
    criterias.add(LoopbackInterfaceCriteria.INSTANCE);
    OverallInterfaceCriteria testee = new OverallInterfaceCriteria("test", criterias);
    Map<NetworkInterface, Set<InetAddress>> result = testee.getAcceptableAddresses(allCandidates);
    assertNotNull(result);
    assertEquals(1, result.size());

    Map.Entry<NetworkInterface, Set<InetAddress>> entry = result.entrySet().iterator().next();
    assertEquals(1, entry.getValue().size());
    Set<InetAddress> set = correct.get(entry.getKey());
    assertNotNull(set);
    assertTrue(set.contains(entry.getValue().iterator().next()));
}
 
Example 11
Source File: NetUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * docker环境中,有时无法通过InetAddress.getLocalHost()获取 ,会报unknown host Exception, system error
 * 此时,通过遍历网卡接口的方式规避,出来的数据不一定对
 */
private static void doGetIpv4AddressFromNetworkInterface() throws SocketException {
  Enumeration<NetworkInterface> iterNetwork = NetworkInterface.getNetworkInterfaces();

  while (iterNetwork.hasMoreElements()) {
    NetworkInterface network = iterNetwork.nextElement();

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

    Enumeration<InetAddress> iterAddress = network.getInetAddresses();
    while (iterAddress.hasMoreElements()) {
      InetAddress address = iterAddress.nextElement();

      if (address.isAnyLocalAddress() || address.isLoopbackAddress() || address.isMulticastAddress()
          || Inet6Address.class.isInstance(address)) {
        continue;
      }

      if (Inet4Address.class.isInstance(address)) {
        LOGGER.info(
            "add network interface name:" + network.getName() + ",host address:" + address.getHostAddress());
        allInterfaceAddresses.put(network.getName(), address);
      }
    }
  }
}
 
Example 12
Source File: MixAll.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public static String getLocalhostByNetworkInterface() throws SocketException {
    List<String> candidatesHost = new ArrayList<String>();
    Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();

    while (enumeration.hasMoreElements()) {
        NetworkInterface networkInterface = enumeration.nextElement();
        // Workaround for docker0 bridge
        if ("docker0".equals(networkInterface.getName()) || !networkInterface.isUp()) {
            continue;
        }
        Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
        while (addrs.hasMoreElements()) {
            InetAddress address = addrs.nextElement();
            if (address.isLoopbackAddress()) {
                continue;
            }
            //ip4 highter priority
            if (address instanceof Inet6Address) {
                candidatesHost.add(address.getHostAddress());
                continue;
            }
            return address.getHostAddress();
        }
    }

    if (!candidatesHost.isEmpty()) {
        return candidatesHost.get(0);
    }
    return null;
}
 
Example 13
Source File: MixAll.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public static String getLocalhostByNetworkInterface() throws SocketException {
    List<String> candidatesHost = new ArrayList<String>();
    Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();

    while (enumeration.hasMoreElements()) {
        NetworkInterface networkInterface = enumeration.nextElement();
        // Workaround for docker0 bridge
        if ("docker0".equals(networkInterface.getName()) || !networkInterface.isUp()) {
            continue;
        }
        Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
        while (addrs.hasMoreElements()) {
            InetAddress address = addrs.nextElement();
            if (address.isLoopbackAddress()) {
                continue;
            }
            //ip4 higher priority
            if (address instanceof Inet6Address) {
                candidatesHost.add(address.getHostAddress());
                continue;
            }
            return address.getHostAddress();
        }
    }

    if (!candidatesHost.isEmpty()) {
        return candidatesHost.get(0);
    }
    return null;
}
 
Example 14
Source File: NetworkUtils.java    From AndroidUtilCode with Apache License 2.0 5 votes vote down vote up
/**
 * Return the ip address.
 * <p>Must hold {@code <uses-permission android:name="android.permission.INTERNET" />}</p>
 *
 * @param useIPv4 True to use ipv4, false otherwise.
 * @return the ip address
 */
@RequiresPermission(INTERNET)
public static String getIPAddress(final boolean useIPv4) {
    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        LinkedList<InetAddress> adds = new LinkedList<>();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            // To prevent phone of xiaomi return "10.0.2.15"
            if (!ni.isUp() || ni.isLoopback()) continue;
            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            while (addresses.hasMoreElements()) {
                adds.addFirst(addresses.nextElement());
            }
        }
        for (InetAddress add : adds) {
            if (!add.isLoopbackAddress()) {
                String hostAddress = add.getHostAddress();
                boolean isIPv4 = hostAddress.indexOf(':') < 0;
                if (useIPv4) {
                    if (isIPv4) return hostAddress;
                } else {
                    if (!isIPv4) {
                        int index = hostAddress.indexOf('%');
                        return index < 0
                                ? hostAddress.toUpperCase()
                                : hostAddress.substring(0, index).toUpperCase();
                    }
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 15
Source File: AppNetWorkUtil.java    From Ency with Apache License 2.0 5 votes vote down vote up
/**
 * 获取IP地址
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
 *
 * @param useIPv4 是否用IPv4
 * @return IP地址
 */
public static String getIPAddress(boolean useIPv4) {
    try {
        for (Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); nis.hasMoreElements(); ) {
            NetworkInterface ni = nis.nextElement();
            // 防止小米手机返回10.0.2.15
            if (!ni.isUp()) continue;
            for (Enumeration<InetAddress> addresses = ni.getInetAddresses(); addresses.hasMoreElements(); ) {
                InetAddress inetAddress = addresses.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    String hostAddress = inetAddress.getHostAddress();
                    boolean isIPv4 = hostAddress.indexOf(':') < 0;
                    if (useIPv4) {
                        if (isIPv4) {
                            return hostAddress;
                        }
                    } else {
                        if (!isIPv4) {
                            int index = hostAddress.indexOf('%');
                            return index < 0 ? hostAddress.toUpperCase() : hostAddress.substring(0, index).toUpperCase();
                        }
                    }
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 16
Source File: SetGetNetworkInterfaceTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static boolean isNetworkInterfaceTestable(NetworkInterface netIf) throws Exception {
    System.out.println("checking netif == " + netIf.getName());
    return  (netIf.isUp() && netIf.supportsMulticast() && isIpAddrAvailable(netIf));
}
 
Example 17
Source File: SetGetNetworkInterfaceTest.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static boolean isNetworkInterfaceTestable(NetworkInterface netIf) throws Exception {
    System.out.println("checking netif == " + netIf.getName());
    return  (netIf.isUp() && netIf.supportsMulticast() && isIpAddrAvailable(netIf));
}
 
Example 18
Source File: Boot.java    From MakeLobbiesGreatAgain with MIT License 4 votes vote down vote up
public static void getLocalAddr() throws InterruptedException, PcapNativeException, UnknownHostException, SocketException,
		ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
	if (Settings.getDouble("autoload", 0) == 1) {
		addr = InetAddress.getByName(Settings.get("addr", ""));
		return;
	}

	UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	final JFrame frame = new JFrame("Network Device");
	frame.setFocusableWindowState(true);

	final JLabel ipLab = new JLabel("Select LAN IP obtained from Network Settings:", JLabel.LEFT);
	final JComboBox<String> lanIP = new JComboBox<String>();
	final JLabel lanLabel = new JLabel("If your device IP isn't in the dropdown, provide it below.");
	final JTextField lanText = new JTextField(Settings.get("addr", ""));

	ArrayList<InetAddress> inets = new ArrayList<InetAddress>();

	for (PcapNetworkInterface i : Pcaps.findAllDevs()) {
		for (PcapAddress x : i.getAddresses()) {
			InetAddress xAddr = x.getAddress();
			if (xAddr != null && x.getNetmask() != null && !xAddr.toString().equals("/0.0.0.0")) {
				NetworkInterface inf = NetworkInterface.getByInetAddress(x.getAddress());
				if (inf != null && inf.isUp() && !inf.isVirtual()) {
					inets.add(xAddr);
					lanIP.addItem((lanIP.getItemCount() + 1) + " - " + inf.getDisplayName() + " ::: " + xAddr.getHostAddress());
					System.out.println("Found: " + lanIP.getItemCount() + " - " + inf.getDisplayName() + " ::: " + xAddr.getHostAddress());
				}
			}
		}
	}

	if (lanIP.getItemCount() == 0) {
		JOptionPane.showMessageDialog(null, "Unable to locate devices.\nPlease try running the program in Admin Mode.\nIf this does not work, you may need to reboot your computer.",
				"Error", JOptionPane.ERROR_MESSAGE);
		System.exit(1);
	}
	lanIP.setFocusable(false);
	final JButton start = new JButton("Start");
	start.addActionListener(e -> {
		try {
			if (lanText.getText().length() >= 7 && !lanText.getText().equals("0.0.0.0")) { // 7 is because the minimum field is 0.0.0.0
				addr = InetAddress.getByName(lanText.getText());
				System.out.println("Using IP from textfield: " + lanText.getText());
			} else {
				addr = inets.get(lanIP.getSelectedIndex());
				System.out.println("Using device from dropdown: " + lanIP.getSelectedItem());
			}
			Settings.set("addr", addr.getHostAddress().replaceAll("/", ""));
			frame.setVisible(false);
			frame.dispose();
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
	});

	frame.setLayout(new GridLayout(5, 1));
	frame.add(ipLab);
	frame.add(lanIP);
	frame.add(lanLabel);
	frame.add(lanText);
	frame.add(start);
	frame.setAlwaysOnTop(true);
	frame.pack();
	frame.setLocationRelativeTo(null);
	frame.setVisible(true);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	while (frame.isVisible())
		Thread.sleep(10);
}
 
Example 19
Source File: InetTools.java    From pampas with Apache License 2.0 4 votes vote down vote up
public InetAddress findFirstNonLoopbackAddress() {
        InetAddress result = null;
        try {
            int lowest = Integer.MAX_VALUE;
            for (Enumeration<NetworkInterface> nics = NetworkInterface
                    .getNetworkInterfaces(); nics.hasMoreElements(); ) {
                NetworkInterface ifc = nics.nextElement();
                if (ifc.isUp()) {
//                    log.trace("Testing interface: " + ifc.getDisplayName());
                    if (ifc.getIndex() < lowest || result == null) {
                        lowest = ifc.getIndex();
                    } else if (result != null) {
                        continue;
                    }

                    // @formatter:off
                    if (!ignoreInterface(ifc.getDisplayName())) {
                        for (Enumeration<InetAddress> addrs = ifc
                                .getInetAddresses(); addrs.hasMoreElements(); ) {
                            InetAddress address = addrs.nextElement();
                            if (address instanceof Inet4Address && !address.isLoopbackAddress() && !ignoreAddress(address)) {
//                                log.trace("Found non-loopback interface: " + ifc.getDisplayName());
                                result = address;
                            }
                        }
                    }
                    // @formatter:on
                }
            }
        } catch (IOException ex) {
            log.error("Cannot get first non-loopback address", ex);
        }

        if (result != null) {
            return result;
        }

        try {
            return InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            log.warn("Unable to retrieve localhost");
        }

        return null;
    }
 
Example 20
Source File: LocalhostUtil.java    From sumk with Apache License 2.0 2 votes vote down vote up
/**
 * 网卡是否有效
 * 
 * @param ni
 * @return
 * @throws SocketException
 */
private static boolean isUp(NetworkInterface ni) throws SocketException {
	return (!ni.isVirtual()) && ni.isUp() && (!ni.isLoopback());
}