java.net.NetworkInterface#isVirtual ( )源码实例Demo

下面列出了java.net.NetworkInterface#isVirtual ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hasting   文件: RpcUtils.java
/**
 * 获取本机ipv4地址列表
 * @return
 */
public static List<String> getLocalV4IPs(){
	List<String> ips = new ArrayList<String>();
	try {
		Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
		while(interfaces.hasMoreElements()){
			NetworkInterface ni = interfaces.nextElement();
			String name = ni.getDisplayName();
			if(!ni.isLoopback()&&!ni.isVirtual()&&ni.isUp()){
				if(name==null||!name.contains("Loopback")){
					Enumeration<InetAddress> addresses = ni.getInetAddresses();
					while(addresses.hasMoreElements()){
						InetAddress address = addresses.nextElement();
						String ip = address.getHostAddress();
						if(!ip.contains(":")){
							ips.add(ip);
						}
					}
				}
			}
		}
	} catch (SocketException e) {
		logger.error("localips error",e);
	}
	return ips;
}
 
源代码2 项目: cosmic   文件: NetUtils.java
public static InetAddress[] getInterfaceInetAddresses(final String ifName) {
    final List<InetAddress> addrList = new ArrayList<>();
    try {
        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;
}
 
源代码3 项目: hbase   文件: Addressing.java
private static InetAddress getIpAddress(AddressSelectionCondition condition) throws
    SocketException {
  // Before we connect somewhere, we cannot be sure about what we'd be bound to; however,
  // we only connect when the message where client ID is, is long constructed. Thus,
  // just use whichever IP address we can find.
  Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
  while (interfaces.hasMoreElements()) {
    NetworkInterface current = interfaces.nextElement();
    if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
    Enumeration<InetAddress> addresses = current.getInetAddresses();
    while (addresses.hasMoreElements()) {
      InetAddress addr = addresses.nextElement();
      if (addr.isLoopbackAddress()) continue;
      if (condition.isAcceptableAddress(addr)) {
        return addr;
      }
    }
  }

  throw new SocketException("Can't get our ip address, interfaces are: " + interfaces);
}
 
源代码4 项目: cosmic   文件: NetUtils.java
public static String[] getLocalCidrs() {
    final String defaultHostIp = getDefaultHostIp();

    final List<String> cidrList = new ArrayList<>();
    try {
        for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
                for (final InterfaceAddress address : ifc.getInterfaceAddresses()) {
                    final InetAddress addr = address.getAddress();
                    final int prefixLength = address.getNetworkPrefixLength();
                    if (prefixLength < MAX_CIDR && prefixLength > 0) {
                        final String ip = addr.getHostAddress();
                        if (ip.equalsIgnoreCase(defaultHostIp)) {
                            cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
                        }
                    }
                }
            }
        }
    } catch (final SocketException e) {
        s_logger.warn("UnknownHostException in getLocalCidrs().", e);
    }

    return cidrList.toArray(new String[0]);
}
 
源代码5 项目: flow   文件: AbstractTestBenchTest.java
/**
 * Returns host address that can be targeted from the outside, like from a
 * test hub.
 *
 * @return host address
 * @throws RuntimeException
 *             if host name could not be determined or
 *             {@link SocketException} was caught during the determination.
 */
protected String getCurrentHostAddress() {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface
                .getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface nwInterface = interfaces.nextElement();
            if (!nwInterface.isUp() || nwInterface.isLoopback()
                    || nwInterface.isVirtual()) {
                continue;
            }
            Optional<String> address = getHostAddress(nwInterface);
            if (address.isPresent()) {
                return address.get();
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException("Could not find the host name", e);
    }
    throw new RuntimeException(
            "No compatible (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) ip address found.");
}
 
源代码6 项目: shine-mq   文件: HttpUtil.java
public static String getIpAddress() {
    try {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = allNetInterfaces.nextElement();
            if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                continue;
            } else {
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (ip instanceof Inet4Address) {
                        return ip.getHostAddress();
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}
 
源代码7 项目: cloudstack   文件: NetUtils.java
public static InetAddress[] getAllLocalInetAddresses() {
    final List<InetAddress> addrList = new ArrayList<InetAddress>();
    try {
        for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
            if (ifc.isUp() && !ifc.isVirtual()) {
                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;
}
 
源代码8 项目: crate   文件: IfConfig.java
/** 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();
}
 
源代码9 项目: chronus   文件: ScheduleUtils.java
public static String getLocalIP() {
    try {
        if (LOCAL_IP != null) {
            return LOCAL_IP;
        }
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = allNetInterfaces.nextElement();
            if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                continue;
            } else {
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        LOCAL_IP = ip.getHostAddress();
                        return LOCAL_IP;
                    }
                }
            }
        }
    } catch (Exception e) {
        return "";
    }
    return "";
}
 
源代码10 项目: smarthome   文件: NetUtil.java
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;
}
 
源代码11 项目: Baragon   文件: JavaUtils.java
public static String getHostAddress() throws Exception {
  final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

  while (interfaces.hasMoreElements()) {
    final NetworkInterface current = interfaces.nextElement();

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

    final Enumeration<InetAddress> addresses = current.getInetAddresses();

    while (addresses.hasMoreElements()) {
      final InetAddress current_addr = addresses.nextElement();

      if (current_addr.isLoopbackAddress()) {
        continue;
      }

      if (current_addr instanceof Inet4Address) {
        return current_addr.getHostAddress();
      }
    }
  }

  throw new RuntimeException("Couldn't deduce host address");
}
 
源代码12 项目: openhab-core   文件: NetUtil.java
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;
    }
}
 
源代码13 项目: translationstudio8   文件: LinuxSeries.java
public String getSeries() {
//		try {
////			NativeInterfaces.setLibDir(new File("lib"));
//			NativeInterfaces.setLibDir(new File(FileLocator.toFileURL(Platform.getBundle("net.heartsome.cat.ts.help").getEntry("")).getPath() 
//					+ File.separator + System.getProperty("sun.arch.data.model")));
//			EthernetAddress[] macs = NativeInterfaces.getAllInterfaces();
//			String series = "";
//			for (EthernetAddress a : macs) {
//				series += a.toString() + "+";
//			}
//			return "".equals(series) ? null : StringUtils.removeColon(series.substring(0, series.length() - 1));
//		} catch (IOException e) {
//			e.printStackTrace();
//			return null;
//		}	
		
		try {
			String series = "";
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface network = networkInterfaces.nextElement();
				if (!network.getName().startsWith("vmnet") && !network.getName().startsWith("vboxnet")) {
					byte[] mac = network.getHardwareAddress();
					if (mac != null && mac.length == 6 && !network.isLoopback() && !network.isVirtual()) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < mac.length; i++) {
							sb.append(String.format("%02x", mac[i]));
						}
						sb.append("+");
						series += sb.toString();
					}
				}
			}
			return "".equals(series) ? null : series.substring(0, series.length() - 1);
		} catch (SocketException e) {
			e.printStackTrace();
			return null;
		}
	}
 
源代码14 项目: cache2k   文件: Server.java
/**
* 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;
}
 
源代码15 项目: tmxeditor8   文件: LinuxSeries.java
public String getSeries() {
//		try {
////			NativeInterfaces.setLibDir(new File("lib"));
//			NativeInterfaces.setLibDir(new File(FileLocator.toFileURL(Platform.getBundle("net.heartsome.cat.ts.help").getEntry("")).getPath() 
//					+ File.separator + System.getProperty("sun.arch.data.model")));
//			EthernetAddress[] macs = NativeInterfaces.getAllInterfaces();
//			String series = "";
//			for (EthernetAddress a : macs) {
//				series += a.toString() + "+";
//			}
//			return "".equals(series) ? null : StringUtils.removeColon(series.substring(0, series.length() - 1));
//		} catch (IOException e) {
//			e.printStackTrace();
//			return null;
//		}	
		
		try {
			String series = "";
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (networkInterfaces.hasMoreElements()) {
				NetworkInterface network = networkInterfaces.nextElement();
				if (!network.getName().startsWith("vmnet") && !network.getName().startsWith("vboxnet")) {
					byte[] mac = network.getHardwareAddress();
					if (mac != null && mac.length == 6 && !network.isLoopback() && !network.isVirtual()) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < mac.length; i++) {
							sb.append(String.format("%02x", mac[i]));
						}
						sb.append("+");
						series += sb.toString();
					}
				}
			}
			return "".equals(series) ? null : series.substring(0, series.length() - 1);
		} catch (SocketException e) {
			e.printStackTrace();
			return null;
		}
	}
 
源代码16 项目: openhab-core   文件: NetUtil.java
/**
 * @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;
    }
}
 
源代码17 项目: smarthome   文件: NetUtil.java
/**
 * @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;
    }
}
 
源代码18 项目: heisenberg   文件: HeisenbergServer.java
private String macAddr() {
    try {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        byte[] mac = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint()
                    || !netInterface.isUp()) {
                continue;
            } else {
                mac = netInterface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                    }
                    if (sb.length() > 0) {
			if (macAddr == null) {
				return StringUtil.EMPTY;
			}
                        LOGGER.info("本机mac地址为:" + macAddr);
                        return sb.toString();
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("MAC地址获取失败", e);
    }
    return "";
}
 
源代码19 项目: cosmic   文件: AgentResourceBase.java
@Override
public boolean configure(final Map<String, Object> params) throws ConfigurationException {
    String publicNic = (String) params.get("public.network.device");
    if (publicNic == null) {
        publicNic = "xenbr1";
    }
    String privateNic = (String) params.get("private.network.device");
    if (privateNic == null) {
        privateNic = "xenbr0";
    }
    final String storageNic = (String) params.get("storage.network.device");
    final String storageNic2 = (String) params.get("storage.network.device.2");

    this._privateNic = getNetworkInterface(privateNic);
    this._publicNic = getNetworkInterface(publicNic);
    this._storageNic = getNetworkInterface(storageNic);
    this._storageNic2 = getNetworkInterface(storageNic2);

    if (this._privateNic == null) {
        s_logger.warn("Nics are not specified in properties file/db, will try to autodiscover");

        Enumeration<NetworkInterface> nics = null;
        try {
            nics = NetworkInterface.getNetworkInterfaces();
            if (nics == null || !nics.hasMoreElements()) {
                throw new ConfigurationException("Private NIC is not configured");
            }
        } catch (final SocketException e) {
            throw new ConfigurationException("Private NIC is not configured");
        }

        while (nics.hasMoreElements()) {
            final NetworkInterface nic = nics.nextElement();
            final String nicName = nic.getName();
            //  try {
            if (//!nic.isLoopback() &&
                //nic.isUp() &&
                    !nic.isVirtual() && !nicName.startsWith("vnif") && !nicName.startsWith("vnbr") && !nicName.startsWith("peth") && !nicName.startsWith("vif") &&
                            !nicName.startsWith("virbr") && !nicName.contains(":")) {
                final String[] info = NetUtils.getNicParams(nicName);
                if (info != null && info[0] != null) {
                    this._privateNic = nic;
                    s_logger.info("Designating private to be nic " + nicName);
                    break;
                }
            }
            //      } catch (final SocketException e) {
            //        s_logger.warn("Error looking at " + nicName, e);
            //  }
            s_logger.debug("Skipping nic " + nicName);
        }

        if (this._privateNic == null) {
            throw new ConfigurationException("Private NIC is not configured");
        }
    }
    final String[] infos = NetUtils.getNetworkParams(this._privateNic);
    if (infos == null) {
        s_logger.warn("Incorrect details for private Nic during initialization of ServerResourceBase");
        return false;
    }
    params.put("host.ip", infos[0]);
    params.put("host.mac.address", infos[1]);

    return true;
}
 
源代码20 项目: openjdk-8-source   文件: ThreadLocalRandom.java
private static long initialSeed() {
    String pp = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction(
                    "java.util.secureRandomSeed"));
    if (pp != null && pp.equalsIgnoreCase("true")) {
        byte[] seedBytes = java.security.SecureRandom.getSeed(8);
        long s = (long)(seedBytes[0]) & 0xffL;
        for (int i = 1; i < 8; ++i)
            s = (s << 8) | ((long)(seedBytes[i]) & 0xffL);
        return s;
    }
    long h = 0L;
    try {
        Enumeration<NetworkInterface> ifcs =
                NetworkInterface.getNetworkInterfaces();
        boolean retry = false; // retry once if getHardwareAddress is null
        while (ifcs.hasMoreElements()) {
            NetworkInterface ifc = ifcs.nextElement();
            if (!ifc.isVirtual()) { // skip fake addresses
                byte[] bs = ifc.getHardwareAddress();
                if (bs != null) {
                    int n = bs.length;
                    int m = Math.min(n >>> 1, 4);
                    for (int i = 0; i < m; ++i)
                        h = (h << 16) ^ (bs[i] << 8) ^ bs[n-1-i];
                    if (m < 4)
                        h = (h << 8) ^ bs[n-1-m];
                    h = mix64(h);
                    break;
                }
                else if (!retry)
                    retry = true;
                else
                    break;
            }
        }
    } catch (Exception ignore) {
    }
    return (h ^ mix64(System.currentTimeMillis()) ^
            mix64(System.nanoTime()));
}