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

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

源代码1 项目: wildfly-core   文件: OverallInterfaceCriteria.java
static Map<NetworkInterface, Set<InetAddress>> pruneAliasDuplicates(Map<NetworkInterface, Set<InetAddress>> result) {
    final Map<NetworkInterface, Set<InetAddress>> pruned = new HashMap<NetworkInterface, Set<InetAddress>>();
    for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : result.entrySet()) {
        NetworkInterface ni = entry.getKey();
        if (ni.getParent() != null) {
            pruned.put(ni, entry.getValue());
        } else {
            Set<InetAddress> retained = new HashSet<InetAddress>(entry.getValue());
            Enumeration<NetworkInterface> subInterfaces = ni.getSubInterfaces();
            while (subInterfaces.hasMoreElements()) {
                NetworkInterface sub = subInterfaces.nextElement();
                Set<InetAddress> subAddresses = result.get(sub);
                if (subAddresses != null) {
                    retained.removeAll(subAddresses);
                }
            }
            if (retained.size() > 0) {
                pruned.put(ni, retained);
            }
        }
    }
    return pruned;
}
 
@BeforeClass
public static void setup() throws Exception {
    Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
    while (nifs.hasMoreElements()) {
        NetworkInterface nif = nifs.nextElement();
        processNetworkInterface(nif);
        Enumeration<NetworkInterface> subs = nif.getSubInterfaces();
        while (subs.hasMoreElements()) {
            NetworkInterface sub = subs.nextElement();
            processNetworkInterface(sub);
        }
    }
    System.out.println("loopback: " + loopbackInterface + " " + loopbackAddress);
    for (Map.Entry<NetworkInterface, Set<Inet6Address>> entry : addresses.entrySet()) {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }

}
 
源代码3 项目: elasticsearch-helper   文件: NetworkUtils.java
private static List<NetworkInterface> getNetworkInterfaces() throws SocketException {
    List<NetworkInterface> networkInterfaces = new ArrayList<>();
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();
        networkInterfaces.add(networkInterface);
        Enumeration<NetworkInterface> subInterfaces = networkInterface.getSubInterfaces();
        if (subInterfaces.hasMoreElements()) {
            while (subInterfaces.hasMoreElements()) {
                networkInterfaces.add(subInterfaces.nextElement());
            }
        }
    }
    sortInterfaces(networkInterfaces);
    return networkInterfaces;
}
 
源代码4 项目: grpc-nebula-java   文件: AbstractBenchmark.java
/**
 * Resolve the address bound to the benchmark interface. Currently we assume it's a
 * child interface of the loopback interface with the term 'benchmark' in its name.
 *
 * <p>>This allows traffic shaping to be applied to an IP address and to have the benchmarks
 * detect it's presence and use it. E.g for Linux we can apply netem to a specific IP to
 * do traffic shaping, bind that IP to the loopback adapter and then apply a label to that
 * binding so that it appears as a child interface.
 *
 * <pre>
 * sudo tc qdisc del dev lo root
 * sudo tc qdisc add dev lo root handle 1: prio
 * sudo tc qdisc add dev lo parent 1:1 handle 2: netem delay 0.1ms rate 10gbit
 * sudo tc filter add dev lo parent 1:0 protocol ip prio 1  \
 *            u32 match ip dst 127.127.127.127 flowid 2:1
 * sudo ip addr add dev lo 127.127.127.127/32 label lo:benchmark
 * </pre>
 */
private static InetAddress buildBenchmarkAddr() {
  InetAddress tmp = null;
  try {
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    outer: while (networkInterfaces.hasMoreElements()) {
      NetworkInterface networkInterface = networkInterfaces.nextElement();
      if (!networkInterface.isLoopback()) {
        continue;
      }
      Enumeration<NetworkInterface> subInterfaces = networkInterface.getSubInterfaces();
      while (subInterfaces.hasMoreElements()) {
        NetworkInterface subLoopback = subInterfaces.nextElement();
        if (subLoopback.getDisplayName().contains("benchmark")) {
          tmp = subLoopback.getInetAddresses().nextElement();
          System.out.println("\nResolved benchmark address to " + tmp + " on "
              + subLoopback.getDisplayName() + "\n\n");
          break outer;
        }
      }
    }
  } catch (SocketException se) {
    System.out.println("\nWARNING: Error trying to resolve benchmark interface \n" +  se);
  }
  if (tmp == null) {
    try {
      System.out.println(
          "\nWARNING: Unable to resolve benchmark interface, defaulting to localhost");
      tmp = InetAddress.getLocalHost();
    } catch (UnknownHostException uhe) {
      throw new RuntimeException(uhe);
    }
  }
  return tmp;
}
 
源代码5 项目: hadoop   文件: DNS.java
/**
 * @param nif network interface to get addresses for
 * @return set containing addresses for each subinterface of nif,
 *    see below for the rationale for using an ordered set
 */
private static LinkedHashSet<InetAddress> getSubinterfaceInetAddrs(
    NetworkInterface nif) {
  LinkedHashSet<InetAddress> addrs = new LinkedHashSet<InetAddress>();
  Enumeration<NetworkInterface> subNifs = nif.getSubInterfaces();
  while (subNifs.hasMoreElements()) {
    NetworkInterface subNif = subNifs.nextElement();
    addrs.addAll(Collections.list(subNif.getInetAddresses()));
  }
  return addrs;
}
 
源代码6 项目: hadoop   文件: NetUtils.java
/**
 * Return an InetAddress for each interface that matches the
 * given subnet specified using CIDR notation.
 *
 * @param subnet subnet specified using CIDR notation
 * @param returnSubinterfaces
 *            whether to return IPs associated with subinterfaces
 * @throws IllegalArgumentException if subnet is invalid
 */
public static List<InetAddress> getIPs(String subnet,
    boolean returnSubinterfaces) {
  List<InetAddress> addrs = new ArrayList<InetAddress>();
  SubnetInfo subnetInfo = new SubnetUtils(subnet).getInfo();
  Enumeration<NetworkInterface> nifs;

  try {
    nifs = NetworkInterface.getNetworkInterfaces();
  } catch (SocketException e) {
    LOG.error("Unable to get host interfaces", e);
    return addrs;
  }

  while (nifs.hasMoreElements()) {
    NetworkInterface nif = nifs.nextElement();
    // NB: adding addresses even if the nif is not up
    addMatchingAddrs(nif, subnetInfo, addrs);

    if (!returnSubinterfaces) {
      continue;
    }
    Enumeration<NetworkInterface> subNifs = nif.getSubInterfaces();
    while (subNifs.hasMoreElements()) {
      addMatchingAddrs(subNifs.nextElement(), subnetInfo, addrs);
    }
  }
  return addrs;
}
 
源代码7 项目: big-c   文件: DNS.java
/**
 * @param nif network interface to get addresses for
 * @return set containing addresses for each subinterface of nif,
 *    see below for the rationale for using an ordered set
 */
private static LinkedHashSet<InetAddress> getSubinterfaceInetAddrs(
    NetworkInterface nif) {
  LinkedHashSet<InetAddress> addrs = new LinkedHashSet<InetAddress>();
  Enumeration<NetworkInterface> subNifs = nif.getSubInterfaces();
  while (subNifs.hasMoreElements()) {
    NetworkInterface subNif = subNifs.nextElement();
    addrs.addAll(Collections.list(subNif.getInetAddresses()));
  }
  return addrs;
}
 
源代码8 项目: big-c   文件: NetUtils.java
/**
 * Return an InetAddress for each interface that matches the
 * given subnet specified using CIDR notation.
 *
 * @param subnet subnet specified using CIDR notation
 * @param returnSubinterfaces
 *            whether to return IPs associated with subinterfaces
 * @throws IllegalArgumentException if subnet is invalid
 */
public static List<InetAddress> getIPs(String subnet,
    boolean returnSubinterfaces) {
  List<InetAddress> addrs = new ArrayList<InetAddress>();
  SubnetInfo subnetInfo = new SubnetUtils(subnet).getInfo();
  Enumeration<NetworkInterface> nifs;

  try {
    nifs = NetworkInterface.getNetworkInterfaces();
  } catch (SocketException e) {
    LOG.error("Unable to get host interfaces", e);
    return addrs;
  }

  while (nifs.hasMoreElements()) {
    NetworkInterface nif = nifs.nextElement();
    // NB: adding addresses even if the nif is not up
    addMatchingAddrs(nif, subnetInfo, addrs);

    if (!returnSubinterfaces) {
      continue;
    }
    Enumeration<NetworkInterface> subNifs = nif.getSubInterfaces();
    while (subNifs.hasMoreElements()) {
      addMatchingAddrs(subNifs.nextElement(), subnetInfo, addrs);
    }
  }
  return addrs;
}
 
源代码9 项目: wildfly-core   文件: NetworkInterfaceService.java
private static void storeAddresses(final NetworkInterface networkInterface, final Map<NetworkInterface, Set<InetAddress>> candidates) {
    final Enumeration<InetAddress> interfaceAddresses = networkInterface.getInetAddresses();
    Set<InetAddress> addresses = new HashSet<InetAddress>();
    candidates.put(networkInterface, addresses);
    while (interfaceAddresses.hasMoreElements()) {
        addresses.add(interfaceAddresses.nextElement());
    }
    final Enumeration<NetworkInterface> subInterfaces = networkInterface.getSubInterfaces();
    while (subInterfaces.hasMoreElements()) {
        storeAddresses(subInterfaces.nextElement(), candidates);
    }
}
 
源代码10 项目: grpc-java   文件: AbstractBenchmark.java
/**
 * Resolve the address bound to the benchmark interface. Currently we assume it's a
 * child interface of the loopback interface with the term 'benchmark' in its name.
 *
 * <p>>This allows traffic shaping to be applied to an IP address and to have the benchmarks
 * detect it's presence and use it. E.g for Linux we can apply netem to a specific IP to
 * do traffic shaping, bind that IP to the loopback adapter and then apply a label to that
 * binding so that it appears as a child interface.
 *
 * <pre>
 * sudo tc qdisc del dev lo root
 * sudo tc qdisc add dev lo root handle 1: prio
 * sudo tc qdisc add dev lo parent 1:1 handle 2: netem delay 0.1ms rate 10gbit
 * sudo tc filter add dev lo parent 1:0 protocol ip prio 1  \
 *            u32 match ip dst 127.127.127.127 flowid 2:1
 * sudo ip addr add dev lo 127.127.127.127/32 label lo:benchmark
 * </pre>
 */
private static InetAddress buildBenchmarkAddr() {
  InetAddress tmp = null;
  try {
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
    outer: while (networkInterfaces.hasMoreElements()) {
      NetworkInterface networkInterface = networkInterfaces.nextElement();
      if (!networkInterface.isLoopback()) {
        continue;
      }
      Enumeration<NetworkInterface> subInterfaces = networkInterface.getSubInterfaces();
      while (subInterfaces.hasMoreElements()) {
        NetworkInterface subLoopback = subInterfaces.nextElement();
        if (subLoopback.getDisplayName().contains("benchmark")) {
          tmp = subLoopback.getInetAddresses().nextElement();
          System.out.println("\nResolved benchmark address to " + tmp + " on "
              + subLoopback.getDisplayName() + "\n\n");
          break outer;
        }
      }
    }
  } catch (SocketException se) {
    System.out.println("\nWARNING: Error trying to resolve benchmark interface \n" +  se);
  }
  if (tmp == null) {
    try {
      System.out.println(
          "\nWARNING: Unable to resolve benchmark interface, defaulting to localhost");
      tmp = InetAddress.getLocalHost();
    } catch (UnknownHostException uhe) {
      throw new RuntimeException(uhe);
    }
  }
  return tmp;
}
 
源代码11 项目: elasticsearch-helper   文件: NetworkUtils.java
public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException {
    List<NetworkInterface> allInterfaces = new ArrayList<>();
    for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) {
        NetworkInterface networkInterface = interfaces.nextElement();
        allInterfaces.add(networkInterface);
        Enumeration<NetworkInterface> subInterfaces = networkInterface.getSubInterfaces();
        if (subInterfaces.hasMoreElements()) {
            while (subInterfaces.hasMoreElements()) {
                allInterfaces.add(subInterfaces.nextElement());
            }
        }
    }
    sortInterfaces(allInterfaces);
    return allInterfaces;
}
 
源代码12 项目: TVRemoteIME   文件: NetworkAddressFactoryImpl.java
protected void logInterfaceInformation(NetworkInterface networkInterface) throws SocketException {
    log.info("---------------------------------------------------------------------------------");
    log.info(String.format("Interface display name: %s", networkInterface.getDisplayName()));
    if (networkInterface.getParent() != null)
        log.info(String.format("Parent Info: %s", networkInterface.getParent()));
    log.info(String.format("Name: %s", networkInterface.getName()));

    Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();

    for (InetAddress inetAddress : Collections.list(inetAddresses)) {
        log.info(String.format("InetAddress: %s", inetAddress));
    }

    List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();

    for (InterfaceAddress interfaceAddress : interfaceAddresses) {
        if (interfaceAddress == null) {
            log.warning("Skipping null InterfaceAddress!");
            continue;
        }
        log.info(" Interface Address");
        log.info("  Address: " + interfaceAddress.getAddress());
        log.info("  Broadcast: " + interfaceAddress.getBroadcast());
        log.info("  Prefix length: " + interfaceAddress.getNetworkPrefixLength());
    }

    Enumeration<NetworkInterface> subIfs = networkInterface.getSubInterfaces();

    for (NetworkInterface subIf : Collections.list(subIfs)) {
        if (subIf == null) {
            log.warning("Skipping null NetworkInterface sub-interface");
            continue;
        }
        log.info(String.format("\tSub Interface Display name: %s", subIf.getDisplayName()));
        log.info(String.format("\tSub Interface Name: %s", subIf.getName()));
    }
    log.info(String.format("Up? %s", networkInterface.isUp()));
    log.info(String.format("Loopback? %s", networkInterface.isLoopback()));
    log.info(String.format("PointToPoint? %s", networkInterface.isPointToPoint()));
    log.info(String.format("Supports multicast? %s", networkInterface.supportsMulticast()));
    log.info(String.format("Virtual? %s", networkInterface.isVirtual()));
    log.info(String.format("Hardware address: %s", Arrays.toString(networkInterface.getHardwareAddress())));
    log.info(String.format("MTU: %s", networkInterface.getMTU()));
}
 
源代码13 项目: SPADE   文件: HostInfo.java
/**
 * Returns all the 'configured' network interfaces
 * 
 * @return list of network interfaces / NULL (in case of error)
 */
private static List<Interface> readInterfaces(){
	try{
		List<Interface> interfacesResult = new ArrayList<Interface>();
		
		Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
		LinkedList<NetworkInterface> networkInterfacesList = new LinkedList<NetworkInterface>();
		while(networkInterfaces.hasMoreElements()){
			networkInterfacesList.addLast(networkInterfaces.nextElement());
		}
		
		while(!networkInterfacesList.isEmpty()){
			NetworkInterface networkInterface = networkInterfacesList.removeFirst();
			// Since there can be subinterfaces, adding all to the networkInterfaces list and processing them. 
			// Breadth first traversal.
			Enumeration<NetworkInterface> networkSubInterfaces = networkInterface.getSubInterfaces();
			while(networkSubInterfaces.hasMoreElements()){
				networkInterfacesList.addLast(networkSubInterfaces.nextElement());
			}
			
			Interface interfaceResult = new Interface();
			interfaceResult.name = unNullify(networkInterface.getName());
			interfaceResult.macAddress = parseBytesToMacAddress(networkInterface.getHardwareAddress());
			
			List<String> ips = new ArrayList<String>();
			Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
			while(inetAddresses.hasMoreElements()){
				InetAddress inetAddress = inetAddresses.nextElement();
				byte[] ipBytes = inetAddress.getAddress();
				if(inetAddress instanceof Inet4Address){
					ips.add(parseBytesToIpv4(ipBytes));
				}else if(inetAddress instanceof Inet6Address){
					ips.add(parseBytesToIpv6(ipBytes));
				}else{
					logger.log(Level.WARNING, "Unknown address type: " + inetAddress);
				}
			}
			
			interfaceResult.ips = ips;
			
			interfacesResult.add(interfaceResult);
		}
		
		return interfacesResult;
	}catch(Exception e){
		logger.log(Level.SEVERE, "Failed to poll network interfaces", e);
	}
	return null;
}
 
源代码14 项目: DroidDLNA   文件: NetworkAddressFactoryImpl.java
protected void logInterfaceInformation(NetworkInterface networkInterface) throws SocketException {
    log.info("---------------------------------------------------------------------------------");
    log.info(String.format("Interface display name: %s", networkInterface.getDisplayName()));
    if (networkInterface.getParent() != null)
        log.info(String.format("Parent Info: %s", networkInterface.getParent()));
    log.info(String.format("Name: %s", networkInterface.getName()));

    Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();

    for (InetAddress inetAddress : Collections.list(inetAddresses)) {
        log.info(String.format("InetAddress: %s", inetAddress));
    }

    List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();

    for (InterfaceAddress interfaceAddress : interfaceAddresses) {
        if (interfaceAddress == null) {
            log.warning("Skipping null InterfaceAddress!");
            continue;
        }
        log.info(" Interface Address");
        log.info("  Address: " + interfaceAddress.getAddress());
        log.info("  Broadcast: " + interfaceAddress.getBroadcast());
        log.info("  Prefix length: " + interfaceAddress.getNetworkPrefixLength());
    }

    Enumeration<NetworkInterface> subIfs = networkInterface.getSubInterfaces();

    for (NetworkInterface subIf : Collections.list(subIfs)) {
        if (subIf == null) {
            log.warning("Skipping null NetworkInterface sub-interface");
            continue;
        }
        log.info(String.format("\tSub Interface Display name: %s", subIf.getDisplayName()));
        log.info(String.format("\tSub Interface Name: %s", subIf.getName()));
    }
    log.info(String.format("Up? %s", networkInterface.isUp()));
    log.info(String.format("Loopback? %s", networkInterface.isLoopback()));
    log.info(String.format("PointToPoint? %s", networkInterface.isPointToPoint()));
    log.info(String.format("Supports multicast? %s", networkInterface.supportsMulticast()));
    log.info(String.format("Virtual? %s", networkInterface.isVirtual()));
    log.info(String.format("Hardware address: %s", Arrays.toString(networkInterface.getHardwareAddress())));
    log.info(String.format("MTU: %s", networkInterface.getMTU()));
}