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

The following examples show how to use java.net.NetworkInterface#getDisplayName() . 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: NetworkAddressFactoryImpl.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
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());
    }
 
Example 2
Source File: NetworkService.java    From jolie with GNU Lesser General Public License v2.1 6 votes vote down vote up
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;
}
 
Example 3
Source File: NetworkData.java    From uuid-creator with MIT License 6 votes vote down vote up
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;
}
 
Example 4
Source File: RpcUtils.java    From hasting with MIT License 6 votes vote down vote up
/**
 * 获取本机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;
}
 
Example 5
Source File: IPUtils.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
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";
    }
}
 
Example 6
Source File: Config.java    From oneops with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 7
Source File: Inet6AddressSerializationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example 8
Source File: NetworkInformation.java    From FlyingAgent with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 9
Source File: PlainMulticastSender.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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;
}
 
Example 10
Source File: InterfaceIpV4Address.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: NetworkUtils.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
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));

    }
 
Example 12
Source File: NetworkConfiguration.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: NetworkInterfaceStreamTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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");
}
 
Example 14
Source File: NetworkConfiguration.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: RemoteServer.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
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";
}
 
Example 16
Source File: AndroidNetworkAddressFactory.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
@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());
}
 
Example 17
Source File: NetworkConfiguration.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 18
Source File: NetworkUtils.java    From SlidesRemote with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 19
Source File: NetworkAddressFactoryImpl.java    From TVRemoteIME with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source File: NetworkAddressFactoryImpl.java    From DroidDLNA with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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;
}