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

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

源代码1 项目: uuid-creator   文件: NetworkData.java
private static NetworkData buildNetworkData(NetworkInterface networkInterface, InetAddress inetAddress)
		throws SocketException {
	if (isPhysicalNetworkInterface(networkInterface)) {

		String hostName = inetAddress != null ? inetAddress.getHostName() : null;
		String hostCanonicalName = inetAddress != null ? inetAddress.getCanonicalHostName() : null;
		String interfaceName = networkInterface.getName();
		String interfaceDisplayName = networkInterface.getDisplayName();
		String interfaceHardwareAddress = ByteUtil.toHexadecimal(networkInterface.getHardwareAddress());
		List<String> interfaceAddresses = getInterfaceAddresses(networkInterface);

		NetworkData networkData = new NetworkData();
		networkData.setHostName(hostName);
		networkData.setHostCanonicalName(hostCanonicalName);
		networkData.setInterfaceName(interfaceName);
		networkData.setInterfaceDisplayName(interfaceDisplayName);
		networkData.setInterfaceHardwareAddress(interfaceHardwareAddress);
		networkData.setInterfaceAddresses(interfaceAddresses);

		return networkData;
	}
	return null;
}
 
源代码2 项目: 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;
}
 
源代码3 项目: blynk-server   文件: IPUtils.java
public static String resolveHostIP(String netInterface) {
    try {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            if (networkInterface.getDisplayName().startsWith(netInterface)) {
                Enumeration<InetAddress> ips = networkInterface.getInetAddresses();
                while (ips.hasMoreElements()) {
                    InetAddress inetAddress = ips.nextElement();
                    if (inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
                return networkInterface.getDisplayName();
            }
        }
        return InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
        return "127.0.0.1";
    }
}
 
源代码4 项目: oneops   文件: Config.java
/**
 * Retruns the inductor IP address (IPV4 address). If there are multiple NICs/IfAddresses, it
 * selects the first one. Openstack VMs normally has only one network interface (eth0).
 *
 * @return IPV4 address of inductor with interface name. Returns <code>null</code> if it couldn't
 * find anything.
 */
private String getInductorIPv4Addr() {
  try {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
    while (nics.hasMoreElements()) {
      NetworkInterface nic = nics.nextElement();
      if (nic.isUp() && !nic.isLoopback()) {
        Enumeration<InetAddress> addrs = nic.getInetAddresses();
        while (addrs.hasMoreElements()) {
          InetAddress add = addrs.nextElement();
          // Print only IPV4 address
          if (add instanceof Inet4Address && !add.isLoopbackAddress()) {
            // Log the first one.
            String ip = add.getHostAddress() + " (" + nic.getDisplayName() + ")";
            logger.info("Inductor IP : " + ip);
            return ip;
          }
        }
      }
    }
  } catch (Exception e) {
    logger.warn("Error getting inductor IP address", e);
    // Skip any errors
  }
  return null;
}
 
static void testAllNetworkInterfaces() throws Exception {
    System.err.println("\n testAllNetworkInterfaces: \n ");
    for (Enumeration<NetworkInterface> e = NetworkInterface
            .getNetworkInterfaces(); e.hasMoreElements();) {
        NetworkInterface netIF = e.nextElement();
        // Skip (Windows)Teredo Tunneling Pseudo-Interface
        if (isWindows) {
            String dName = netIF.getDisplayName();
            if (dName != null && dName.contains("Teredo")) {
                continue;
            }
        }
        for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
                .hasMoreElements();) {
            InetAddress iadr = iadrs.nextElement();
            if (iadr instanceof Inet6Address) {
                System.err.println("Test NetworkInterface:  " + netIF);
                Inet6Address i6adr = (Inet6Address) iadr;
                System.err.println("Testing with " + iadr);
                System.err.println(" scoped iface: "
                        + i6adr.getScopedInterface());
                testInet6AddressSerialization(i6adr, null);
            }
        }
    }
}
 
源代码6 项目: jolie   文件: NetworkService.java
public Value getNetworkInterfaceNames()
	throws FaultException {

	Value response = Value.create();
	ValueVector interfaces = response.getChildren( "interfaceName" );

	try {
		Enumeration< NetworkInterface > list = NetworkInterface.getNetworkInterfaces();
		int index = 0;
		while( list.hasMoreElements() ) {
			NetworkInterface n = list.nextElement();
			interfaces.get( index ).setValue( n.getName() );
			if( n.getDisplayName() == null ) {
				interfaces.get( index ).getFirstChild( "displayName" ).setValue( "" );
			} else {
				interfaces.get( index ).getFirstChild( "displayName" ).setValue( n.getDisplayName() );
			}
			index++;
		}
	} catch( SocketException e ) {
		throw new FaultException( e );
	}
	return response;
}
 
源代码7 项目: DroidDLNA   文件: NetworkAddressFactoryImpl.java
public InetAddress getLocalAddress(NetworkInterface networkInterface, boolean isIPv6, InetAddress remoteAddress) {

        // First try to find a local IP that is in the same subnet as the remote IP
        InetAddress localIPInSubnet = getBindAddressInSubnetOf(remoteAddress);
        if (localIPInSubnet != null) return localIPInSubnet;

        // There are two reasons why we end up here:
        //
        // - Windows Vista returns a 64 or 128 CIDR prefix if you ask it for the network prefix length of an IPv4 address!
        //
        // - We are dealing with genuine IPv6 addresses
        //
        // - Something is really wrong on the LAN and we received a multicast datagram from a source we can't reach via IP
        log.finer("Could not find local bind address in same subnet as: " + remoteAddress.getHostAddress());

        // Next, just take the given interface (which is really totally random) and get the first address that we like
        for (InetAddress interfaceAddress: getInetAddresses(networkInterface)) {
            if (isIPv6 && interfaceAddress instanceof Inet6Address)
                return interfaceAddress;
            if (!isIPv6 && interfaceAddress instanceof Inet4Address)
                return interfaceAddress;
        }
        throw new IllegalStateException("Can't find any IPv4 or IPv6 address on interface: " + networkInterface.getDisplayName());
    }
 
源代码8 项目: SlidesRemote   文件: NetworkUtils.java
public static Map<String, String> getMyIPv4Addresses() {
    Map<String, String> networkList = new HashMap<>();

    try {
        Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) enumeration.nextElement();
            Enumeration ee = networkInterface.getInetAddresses();

            while (ee.hasMoreElements()) {
                InetAddress ip = (InetAddress) ee.nextElement();
                Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);
                // if it is IPv4 Address
                if (IPV4_PATTERN.matcher(ip.getHostAddress()).matches()) {

                    NetworkInterface network = NetworkInterface.getByInetAddress(ip);

                    byte[] mac = network.getHardwareAddress();
                    if (mac != null) {
                        StringBuilder macBuilder = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                            macBuilder.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                        }
                    }

                    String name = networkInterface.getDisplayName();
                    String ipv4 = ip.getHostAddress();
                    networkList.put(name, ipv4);
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }

    return networkList;
}
 
源代码9 项目: FlyingAgent   文件: NetworkInformation.java
NetworkInformation() {
    networkList = new ArrayList<>();
    try {
        Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            NetworkInterface networkInterface = (NetworkInterface) enumeration.nextElement();
            Enumeration ee = networkInterface.getInetAddresses();

            while (ee.hasMoreElements()) {
                InetAddress ip = (InetAddress) ee.nextElement();
                Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);
                // if it is IPv4 Address
                if (IPV4_PATTERN.matcher(ip.getHostAddress()).matches()) {

                    NetworkInterface network = NetworkInterface.getByInetAddress(ip);

                    byte[] mac = network.getHardwareAddress();
                    String macAddress;
                    if (mac != null) {
                        StringBuilder macBuilder = new StringBuilder();
                        for (int i = 0; i < mac.length; i++) {
                            macBuilder.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                        }
                        macAddress = macBuilder.toString();
                    } else {
                        macAddress = "Undefined";
                    }

                    String ipAddress = ip.getHostAddress();
                    String name = networkInterface.getDisplayName();
                    networkList.add(new Network(ipAddress, macAddress, name));
                }
            }
        }

    } catch (SocketException e) {
        e.printStackTrace();
    }
}
 
源代码10 项目: TencentKona-8   文件: NetworkConfiguration.java
private static boolean isNotExcludedInterface(NetworkInterface nif) {
    if (Platform.isOSX() && nif.getName().contains("awdl")) {
        return false;
    }
    String dName = nif.getDisplayName();
    if (Platform.isWindows() && dName != null && dName.contains("Teredo")) {
        return false;
    }
    return true;
}
 
源代码11 项目: TVRemoteIME   文件: AndroidNetworkAddressFactory.java
@Override
public InetAddress getLocalAddress(NetworkInterface networkInterface, boolean isIPv6, InetAddress remoteAddress) {
    // TODO: This is totally random because we can't access low level InterfaceAddress on Android!
    for (InetAddress localAddress : getInetAddresses(networkInterface)) {
        if (isIPv6 && localAddress instanceof Inet6Address)
            return localAddress;
        if (!isIPv6 && localAddress instanceof Inet4Address)
            return localAddress;
    }
    throw new IllegalStateException("Can't find any IPv4 or IPv6 address on interface: " + networkInterface.getDisplayName());
}
 
源代码12 项目: TVRemoteIME   文件: RemoteServer.java
public static String getLocalIPAddress(Context context){
    WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
    int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
    if(ipAddress == 0){
        try {
            Enumeration<NetworkInterface> enumerationNi = NetworkInterface.getNetworkInterfaces();
            while (enumerationNi.hasMoreElements()) {
                NetworkInterface networkInterface = enumerationNi.nextElement();
                String interfaceName = networkInterface.getDisplayName();
                if (interfaceName.equals("eth0") || interfaceName.equals("wlan0")) {
                    Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses();

                    while (enumIpAddr.hasMoreElements()) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            Log.e(IMEService.TAG, "获取本地IP出错", e);
        }
    }else {
        return String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
    }
    return "0.0.0.0";
}
 
源代码13 项目: openjdk-jdk8u   文件: NetworkConfiguration.java
private static boolean isNotExcludedInterface(NetworkInterface nif) {
    if (Platform.isOSX() && nif.getName().contains("awdl")) {
        return false;
    }
    String dName = nif.getDisplayName();
    if (Platform.isWindows() && dName != null && dName.contains("Teredo")) {
        return false;
    }
    return true;
}
 
源代码14 项目: openjdk-jdk9   文件: NetworkInterfaceStreamTest.java
/**
 * Check if the input network interface should be included in the test. It is necessary to exclude
 * "Teredo Tunneling Pseudo-Interface" whose configuration can be variable during a test run.
 *
 * @param ni a network interace
 * @return false if it is a "Teredo Tunneling Pseudo-Interface", otherwise true.
 */
private boolean isIncluded(NetworkInterface ni) {
    if (!IS_WINDOWS) {
        return true;
    }

    String dName = ni.getDisplayName();
    return dName == null || !dName.contains("Teredo");
}
 
源代码15 项目: openjdk-jdk9   文件: NetworkConfiguration.java
private static boolean isNotExcludedInterface(NetworkInterface nif) {
    if (isMacOS && nif.getName().contains("awdl"))
        return false;
    String dName = nif.getDisplayName();
    if (isWindows && dName != null && dName.contains("Teredo"))
        return false;
    return true;
}
 
源代码16 项目: phoenix-omid   文件: NetworkUtils.java
public static String getDefaultNetworkInterface() {

        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            String fallBackName = null;
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface nextElement = networkInterfaces.nextElement();
                String name = nextElement.getDisplayName();
                LOG.info("Iterating over network interfaces, found '{}'", name);
                boolean hasInet = Collections.list(nextElement.getInetAddresses()).size() > 1; // Checking that inet exists, to avoid taking iBridge
                if (hasInet && fallBackName == null) {
                    fallBackName = name;
                }
                if ((name.startsWith(MAC_TSO_NET_IFACE_PREFIX) && hasInet ) ||
                        name.startsWith(LINUX_TSO_NET_IFACE_PREFIX)) {
                  return name;
                }
            }
            if (fallBackName != null) {
                return fallBackName;
            }
        } catch (SocketException ignored) {
            throw new RuntimeException("Failed to find any network interfaces", ignored);
        }
        throw new IllegalArgumentException(String.format("No network '%s*'/'%s*' interfaces found",
                                                         MAC_TSO_NET_IFACE_PREFIX, LINUX_TSO_NET_IFACE_PREFIX));

    }
 
源代码17 项目: hawkular-apm   文件: InterfaceIpV4Address.java
private static Map<String, List<InetAddress>> init() {
    Map<String, List<InetAddress>> interfacesIpAddressesMap = new HashMap<>();

    Enumeration networkInterfaces = null;
    try {
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException ex) {
        throw new RuntimeException("Failed to get network interfaces", ex);
    }
    while (networkInterfaces.hasMoreElements()) {
        NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
        networkInterface.getDisplayName();

        List<InetAddress> ipAddresses = new ArrayList<>();

        Enumeration ee = networkInterface.getInetAddresses();
        while (ee.hasMoreElements()) {
            InetAddress inetAddress = (InetAddress) ee.nextElement();
            if (inetAddress.isSiteLocalAddress()) {
                ipAddresses.add(inetAddress);
            }
        }

        interfacesIpAddressesMap.put(networkInterface.getDisplayName(), Collections.unmodifiableList(ipAddresses));
    }

    return Collections.unmodifiableMap(interfacesIpAddressesMap);
}
 
源代码18 项目: cacheonix-core   文件: PlainMulticastSender.java
/**
 * Creates a warning message about no buffer space available.
 *
 * @param exceptionMessage the message from <code>IOException.getMessage()</code>.
 * @param intf             the interface this happened to
 * @param inetAddress      the inet address it happened to.
 * @return a new warning message about no buffer space available.
 */
private String createIgnoredWarning(final String exceptionMessage, final NetworkInterface intf,
        final InetAddress inetAddress) {

   return exceptionMessage + ": "
           + "interface: " + inetAddress + ", "
           + "network interface: " + intf.getDisplayName() + ", "
           + "total messages sent: " + sentMessages;
}
 
源代码19 项目: TVRemoteIME   文件: NetworkAddressFactoryImpl.java
/**
 * Validation of every discovered network interface.
 * <p>
 * Override this method to customize which network interfaces are used.
 * </p>
 * <p>
 * The given implementation ignores interfaces which are
 * </p>
 * <ul>
 * <li>loopback (yes, we do not bind to lo0)</li>
 * <li>down</li>
 * <li>have no bound IP addresses</li>
 * <li>named "vmnet*" (OS X VMWare does not properly stop interfaces when it quits)</li>
 * <li>named "vnic*" (OS X Parallels interfaces should be ignored as well)</li>
 * <li>named "*virtual*" (VirtualBox interfaces, for example</li>
 * <li>named "ppp*"</li>
 * </ul>
 *
 * @param iface The interface to validate.
 * @return True if the given interface matches all validation criteria.
 * @throws Exception If any validation test failed with an un-recoverable error.
 */
protected boolean isUsableNetworkInterface(NetworkInterface iface) throws Exception {
    if (!iface.isUp()) {
        log.finer("Skipping network interface (down): " + iface.getDisplayName());
        return false;
    }

    if (getInetAddresses(iface).size() == 0) {
        log.finer("Skipping network interface without bound IP addresses: " + iface.getDisplayName());
        return false;
    }

    if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("vmnet") ||
    		(iface.getDisplayName() != null &&  iface.getDisplayName().toLowerCase(Locale.ENGLISH).contains("vmnet"))) {
        log.finer("Skipping network interface (VMWare): " + iface.getDisplayName());
        return false;
    }

    if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("vnic")) {
        log.finer("Skipping network interface (Parallels): " + iface.getDisplayName());
        return false;
    }

    if (iface.getName().toLowerCase(Locale.ENGLISH).contains("virtual")) {
        log.finer("Skipping network interface (named '*virtual*'): " + iface.getDisplayName());
        return false;
    }

    if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("ppp")) {
        log.finer("Skipping network interface (PPP): " + iface.getDisplayName());
        return false;
    }

    if (iface.isLoopback()) {
        log.finer("Skipping network interface (ignoring loopback): " + iface.getDisplayName());
        return false;
    }

    if (useInterfaces.size() > 0 && !useInterfaces.contains(iface.getName())) {
        log.finer("Skipping unwanted network interface (-D" + SYSTEM_PROPERTY_NET_IFACES + "): " + iface.getName());
        return false;
    }

    if (!iface.supportsMulticast())
        log.warning("Network interface may not be multicast capable: "  + iface.getDisplayName());

    return true;
}
 
源代码20 项目: DroidDLNA   文件: NetworkAddressFactoryImpl.java
/**
 * Validation of every discovered network interface.
 * <p>
 * Override this method to customize which network interfaces are used.
 * </p>
 * <p>
 * The given implementation ignores interfaces which are
 * </p>
 * <ul>
 * <li>loopback (yes, we do not bind to lo0)</li>
 * <li>down</li>
 * <li>have no bound IP addresses</li>
 * <li>named "vmnet*" (OS X VMWare does not properly stop interfaces when it quits)</li>
 * <li>named "vnic*" (OS X Parallels interfaces should be ignored as well)</li>
 * <li>named "*virtual*" (VirtualBox interfaces, for example</li>
 * <li>named "ppp*"</li>
 * </ul>
 *
 * @param iface The interface to validate.
 * @return True if the given interface matches all validation criteria.
 * @throws Exception If any validation test failed with an un-recoverable error.
 */
protected boolean isUsableNetworkInterface(NetworkInterface iface) throws Exception {
    if (!iface.isUp()) {
        log.finer("Skipping network interface (down): " + iface.getDisplayName());
        return false;
    }

    if (getInetAddresses(iface).size() == 0) {
        log.finer("Skipping network interface without bound IP addresses: " + iface.getDisplayName());
        return false;
    }

    if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("vmnet") ||
    		(iface.getDisplayName() != null &&  iface.getDisplayName().toLowerCase(Locale.ENGLISH).contains("vmnet"))) {
        log.finer("Skipping network interface (VMWare): " + iface.getDisplayName());
        return false;
    }

    if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("vnic")) {
        log.finer("Skipping network interface (Parallels): " + iface.getDisplayName());
        return false;
    }

    if (iface.getName().toLowerCase(Locale.ENGLISH).contains("virtual")) {
        log.finer("Skipping network interface (named '*virtual*'): " + iface.getDisplayName());
        return false;
    }

    if (iface.getName().toLowerCase(Locale.ENGLISH).startsWith("ppp")) {
        log.finer("Skipping network interface (PPP): " + iface.getDisplayName());
        return false;
    }

    if (iface.isLoopback()) {
        log.finer("Skipping network interface (ignoring loopback): " + iface.getDisplayName());
        return false;
    }

    if (useInterfaces.size() > 0 && !useInterfaces.contains(iface.getName())) {
        log.finer("Skipping unwanted network interface (-D" + SYSTEM_PROPERTY_NET_IFACES + "): " + iface.getName());
        return false;
    }

    if (!iface.supportsMulticast())
        log.warning("Network interface may not be multicast capable: "  + iface.getDisplayName());

    return true;
}