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

The following examples show how to use java.net.NetworkInterface#getInterfaceAddresses() . 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: MainActivity.java    From ForgePE with GNU Affero General Public License v3.0 6 votes vote down vote up
public String[] getBroadcastAddresses() {
    ArrayList<String> list = new ArrayList<>();
    try {
        System.setProperty("java.net.preferIPv4Stack", "true");
        Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();

        while (niEnum.hasMoreElements()) {
            NetworkInterface ni = niEnum.nextElement();

            if (!ni.isLoopback()) {
                for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                    if (interfaceAddress.getBroadcast() != null)
                        list.add(interfaceAddress.getBroadcast().toString().substring(1));
                }
            }
        }
    } catch (Exception ignored) {
    }
    return list.toArray(new String[list.size()]);
}
 
Example 2
Source File: WifiUtils.java    From WifiChat with GNU General Public License v2.0 6 votes vote down vote up
public static String getBroadcastAddress() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    try {
        for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum
                .hasMoreElements();) {
            NetworkInterface ni = niEnum.nextElement();
            if (!ni.isLoopback()) {
                for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                    if (interfaceAddress.getBroadcast() != null) {
                        logger.d(interfaceAddress.getBroadcast().toString().substring(1));
                        return interfaceAddress.getBroadcast().toString().substring(1);
                    }
                }
            }
        }
    }
    catch (SocketException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 3
Source File: PrivateDNS.java    From PacketProxy with Apache License 2.0 6 votes vote down vote up
SpoofAddrFactory() throws Exception {
	Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
	for (NetworkInterface netint : Collections.list(nets)) {
		for (InterfaceAddress intAddress : netint.getInterfaceAddresses()) {
			InetAddress addr = intAddress.getAddress();
			if (addr instanceof Inet4Address) {
				String cidr = String.format("%s/%d", addr.getHostAddress(), intAddress.getNetworkPrefixLength());
				SubnetUtils subnet = new SubnetUtils(cidr);
				subnets.add(subnet.getInfo());
				if (defaultAddr == null) {
					defaultAddr = addr.getHostAddress();
				} else if (defaultAddr.equals("127.0.0.1")) {
					defaultAddr = addr.getHostAddress();
				}
			}
		}
	}
}
 
Example 4
Source File: NetworkPrefixLength.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();

    while (nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        for (InterfaceAddress iaddr : nic.getInterfaceAddresses()) {
            boolean valid = checkPrefix(iaddr);
            if (!valid) {
                passed = false;
                debug(nic.getName(), iaddr);
            }
            InetAddress ia = iaddr.getAddress();
            if (ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                // assumption: prefix length will always be 8
                if (iaddr.getNetworkPrefixLength() != 8) {
                    out.println("Expected prefix of 8, got " + iaddr);
                    passed = false;
                }
            }
        }
    }

    if (!passed)
        throw new RuntimeException("Failed: some interfaces have invalid prefix lengths");
}
 
Example 5
Source File: IrisHalImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Nullable
private final InterfaceAddress getNetworkInterfaceAddress(@Nullable NetworkInterface ni) {
   if (ni == null) {
      return null;
   }

   List<InterfaceAddress> addrs = ni.getInterfaceAddresses();
   if (addrs == null || addrs.isEmpty()) {
      return null;
   }

   // Prefer IPv4 addresses
   for (InterfaceAddress address : addrs) {
      if (address.getAddress() instanceof Inet4Address) {
         return address;
      }
   }

   // Use first IPv6 address if no others are present
   return addrs.get(0);
}
 
Example 6
Source File: NetworkInterfaceTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testInterfaceProperties() throws Exception {
    for (NetworkInterface nif : Collections.list(NetworkInterface.getNetworkInterfaces())) {
        assertEquals(nif, NetworkInterface.getByName(nif.getName()));
        // Skip interfaces that are inactive
        if (nif.isUp() == false) {
            continue;
        }
        // Ethernet
        if (isEthernet(nif.getName())) {
            assertEquals(6, nif.getHardwareAddress().length);
            for (InterfaceAddress ia : nif.getInterfaceAddresses()) {
                if (ia.getAddress() instanceof Inet4Address) {
                    assertNotNull(ia.getBroadcast());
                }
            }
        }
    }
}
 
Example 7
Source File: NetworkUtils.java    From g4proxy with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated This method is no longer used by LittleProxy and may be removed in a future release.
 */
@Deprecated
public static InetAddress firstLocalNonLoopbackIpv4Address() {
    try {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces
                    .nextElement();
            if (networkInterface.isUp()) {
                for (InterfaceAddress ifAddress : networkInterface
                        .getInterfaceAddresses()) {
                    if (ifAddress.getNetworkPrefixLength() > 0
                            && ifAddress.getNetworkPrefixLength() <= 32
                            && !ifAddress.getAddress().isLoopbackAddress()) {
                        return ifAddress.getAddress();
                    }
                }
            }
        }
        return null;
    } catch (SocketException se) {
        return null;
    }
}
 
Example 8
Source File: NetworkPrefixLength.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();

    while (nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        for (InterfaceAddress iaddr : nic.getInterfaceAddresses()) {
            boolean valid = checkPrefix(iaddr);
            if (!valid) {
                passed = false;
                debug(nic.getName(), iaddr);
            }
            InetAddress ia = iaddr.getAddress();
            if (ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                // assumption: prefix length will always be 8
                if (iaddr.getNetworkPrefixLength() != 8) {
                    out.println("Expected prefix of 8, got " + iaddr);
                    passed = false;
                }
            }
        }
    }

    if (!passed)
        throw new RuntimeException("Failed: some interfaces have invalid prefix lengths");
}
 
Example 9
Source File: NetUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static String[] getLocalCidrs() {
    final String defaultHostIp = getDefaultHostIp();

    final List<String> cidrList = new ArrayList<String>();
    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]);
}
 
Example 10
Source File: SsdpDiscovery.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private static List<InetAddress> getBroadCastAddress() throws Exception {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    List<InetAddress> addresses = new ArrayList<InetAddress>();
    addresses.add(InetAddress.getByName("255.255.255.255"));
    while (interfaces.hasMoreElements()) {
        NetworkInterface networkInterface = interfaces.nextElement();
        if (networkInterface.isLoopback() || !networkInterface.supportsMulticast()) {
            continue; // Don't want to broadcast to the loopback interface
        }
        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
            InetAddress broadcast = interfaceAddress.getBroadcast();
            if (broadcast != null) {
                addresses.add(broadcast);
            }
        }
    }
    return addresses;
}
 
Example 11
Source File: NetworkPrefixLength.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();

    while (nics.hasMoreElements()) {
        NetworkInterface nic = nics.nextElement();
        for (InterfaceAddress iaddr : nic.getInterfaceAddresses()) {
            boolean valid = checkPrefix(iaddr);
            if (!valid) {
                passed = false;
                debug(nic.getName(), iaddr);
            }
            InetAddress ia = iaddr.getAddress();
            if (ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                // assumption: prefix length will always be 8
                if (iaddr.getNetworkPrefixLength() != 8) {
                    out.println("Expected prefix of 8, got " + iaddr);
                    passed = false;
                }
            }
        }
    }

    if (!passed)
        throw new RuntimeException("Failed: some interfaces have invalid prefix lengths");
}
 
Example 12
Source File: NetworkHelper.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
public static Set<InetSocketAddress> getLocalAddresses ( final IoAcceptor acceptor ) throws SocketException
{
    final Set<InetSocketAddress> result = new HashSet<InetSocketAddress> ();

    for ( final SocketAddress address : acceptor.getLocalAddresses () )
    {
        logger.info ( "Bound to: {}", address );
        if ( ! ( address instanceof InetSocketAddress ) )
        {
            continue;
        }

        final InetSocketAddress socketAddress = (InetSocketAddress)address;
        if ( socketAddress.getAddress ().isAnyLocalAddress () )
        {
            final int port = socketAddress.getPort ();

            final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces ();
            while ( interfaces.hasMoreElements () )
            {
                final NetworkInterface networkInterface = interfaces.nextElement ();

                for ( final InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses () )
                {
                    result.add ( new InetSocketAddress ( interfaceAddress.getAddress (), port ) );
                }
            }
        }
        else
        {
            result.add ( socketAddress );
        }

    }

    return result;
}
 
Example 13
Source File: UDPLocator.java    From moleculer-java with MIT License 5 votes vote down vote up
protected void startReceivers(NetworkInterface ni, String udpMulticast, boolean udpBroadcast) throws Exception {
	if (ni == null || ni.isLoopback()) {
		return;
	}
	List<InterfaceAddress> list = ni.getInterfaceAddresses();
	if (list == null || list.isEmpty()) {
		return;
	}
	if (udpMulticast != null && ni.supportsMulticast()) {

		// Create multicast receiver
		receivers.add(new UDPMulticastReceiver(nodeID, udpMulticast, transporter, ni));
	}
	if (udpBroadcast) {
		for (InterfaceAddress ia : list) {
			if (ia == null) {
				continue;
			}
			InetAddress address = ia.getBroadcast();
			if (address == null || address.isLoopbackAddress()) {
				continue;
			}
			String udpAddress = address.getHostAddress();
			if (udpAddress == null || udpAddress.isEmpty() || udpAddress.startsWith("127.")) {
				continue;
			}

			// Create broadcast receiver
			receivers.add(new UDPBroadcastReceiver(nodeID, udpAddress, transporter));
		}
	}
}
 
Example 14
Source File: ExtraCounter.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public void buildNetworkSnapshot() {
    try {
        NetworkInformation netInfo = new NetworkInformation();
        netInfo.setTotalMemory(Runtime.getRuntime().maxMemory());
        netInfo.setAvailableMemory(Runtime.getRuntime().freeMemory());

        String sparkIp = System.getenv("SPARK_PUBLIC_DNS");
        if (sparkIp != null) {
            // if spark ip is defined, we just use it, and don't bother with other interfaces

            netInfo.addIpAddress(sparkIp);
        } else {
            // sparkIp wasn't defined, so we'll go for heuristics here
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

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

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

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

                    netInfo.getIpAddresses().add(addr);
                }
            }
        }
        networkInformation.add(netInfo);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source File: UDPDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
private NetworkInterface findNetworkInterface() throws SocketException {
    String name = (String)this.getEndpointInfo().getProperty(UDPDestination.NETWORK_INTERFACE);
    NetworkInterface ret = null;
    if (!StringUtils.isEmpty(name)) {
        ret = NetworkInterface.getByName(name);
    }
    if (ret == null) {
        Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces();
        List<NetworkInterface> possibles = new ArrayList<>();
        while (ifcs.hasMoreElements()) {
            NetworkInterface ni = ifcs.nextElement();
            if (ni.supportsMulticast()
                && ni.isUp()) {
                for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                    if (ia.getAddress() instanceof java.net.Inet4Address
                        && !ia.getAddress().isLoopbackAddress()
                        && !ni.getDisplayName().startsWith("vnic")) {
                        possibles.add(ni);
                    }
                }
            }
        }
        ret = possibles.isEmpty() ? null : possibles.get(possibles.size() - 1);

    }
    return ret;
}
 
Example 16
Source File: NetworkInterfaceTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testLoopback() throws Exception {
    NetworkInterface lo = NetworkInterface.getByName("lo0");
    assertNull(lo.getHardwareAddress());
    for (InterfaceAddress ia : lo.getInterfaceAddresses()) {
        assertNull(ia.getBroadcast());
    }
}
 
Example 17
Source File: NetUtil.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 18
Source File: WifiWizard2.java    From WifiWizard2 with Apache License 2.0 5 votes vote down vote up
/**
 * Get IPv4 Subnet
 * @param inetAddress
 * @return
 */
public static String getIPv4Subnet(InetAddress inetAddress) {
  try {
    NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddress);
    List<InterfaceAddress> intAddrs = ni.getInterfaceAddresses();
    for (InterfaceAddress ia : intAddrs) {
      if (!ia.getAddress().isLoopbackAddress() && ia.getAddress() instanceof Inet4Address) {
        return getIPv4SubnetFromNetPrefixLength(ia.getNetworkPrefixLength()).getHostAddress()
            .toString();
      }
    }
  } catch (Exception e) {
  }
  return "";
}
 
Example 19
Source File: NetUtils.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public static String[] getNetworkParams(final NetworkInterface nic) {
    final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
    if (addrs == null || addrs.size() == 0) {
        return null;
    }
    InterfaceAddress addr = null;
    for (final InterfaceAddress iaddr : addrs) {
        final InetAddress inet = iaddr.getAddress();
        if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) {
            addr = iaddr;
            break;
        }
    }
    if (addr == null) {
        return null;
    }
    final String[] result = new String[3];
    result[0] = addr.getAddress().getHostAddress();
    try {
        final byte[] mac = nic.getHardwareAddress();
        result[1] = byte2Mac(mac);
    } catch (final SocketException e) {
        s_logger.debug("Caught exception when trying to get the mac address ", e);
    }

    result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
    return result;
}
 
Example 20
Source File: AutoGeneratedSelfSignedKeyStoreImpl.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private void generatePrivateKeyAndCertificate()
{
    try
    {


        Set<InetAddress> addresses = new HashSet<>();
        for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces()))
        {
            for (InterfaceAddress inetAddress : networkInterface.getInterfaceAddresses())
            {
                addresses.add(inetAddress.getAddress());
            }
        }

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

        for(InetAddress address : addresses)
        {

            String hostName = address.getHostName();
            if (hostName != null)
            {
                dnsNames.add(hostName);
            }
            String canonicalHostName = address.getCanonicalHostName();
            if (canonicalHostName != null)
            {
                dnsNames.add(canonicalHostName);
            }
        }

        long startTime = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(startTime);
        calendar.add(Calendar.MONTH, _durationInMonths);
        long duration = (calendar.getTimeInMillis() - startTime)/1000;

        final SSLUtil.KeyCertPair keyCertPair = SSLUtil.generateSelfSignedCertificate(_keyAlgorithm,
                                                                                      _signatureAlgorithm,
                                                                                      _keyLength,
                                                                                      startTime,
                                                                                      duration,
                                                                                      "CN=Qpid",
                                                                                      dnsNames,
                                                                                      addresses);

        _privateKey = keyCertPair.getPrivateKey();
        _certificate = keyCertPair.getCertificate();
        _generated = true;

    }
    catch (InstantiationException | IllegalAccessException | InvocationTargetException | IOException e)
    {
        throw new IllegalConfigurationException("Unable to construct keystore", e);
    }
}