java.net.InterfaceAddress Java Examples

The following examples show how to use java.net.InterfaceAddress. 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: NetworkPrefixLength.java    From openjdk-jdk9 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 #2
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 #3
Source File: WifiUtils.java    From FlyWoo with Apache License 2.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) {
                        L.d(TAG, interfaceAddress.getBroadcast().toString().substring(1));
                        return interfaceAddress.getBroadcast().toString().substring(1);
                    }
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example #4
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 #5
Source File: DiscoveryJob.java    From swingsane with Apache License 2.0 6 votes vote down vote up
public final InetAddress getLocalAddress() throws SocketException {
  for (final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces
      .hasMoreElements();) {
    final NetworkInterface networkInterface = interfaces.nextElement();
    if (networkInterface.isLoopback()) {
      continue;
    }
    for (final InterfaceAddress interfaceAddr : networkInterface.getInterfaceAddresses()) {
      final InetAddress inetAddr = interfaceAddr.getAddress();
      if (!(inetAddr instanceof Inet4Address)) {
        continue;
      }
      return inetAddr;
    }
  }
  return null;
}
 
Example #6
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 #7
Source File: NetUtil.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get all broadcast addresses on the current host
 *
 * @return list of broadcast addresses, empty list if no broadcast addresses found
 */
public static List<String> getAllBroadcastAddresses() {
    List<String> broadcastAddresses = new LinkedList<String>();
    try {
        final Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            final NetworkInterface networkInterface = networkInterfaces.nextElement();
            final List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
            for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                final InetAddress addr = interfaceAddress.getAddress();
                if (addr instanceof Inet4Address && !addr.isLinkLocalAddress() && !addr.isLoopbackAddress()) {
                    InetAddress broadcast = interfaceAddress.getBroadcast();
                    if (broadcast != null) {
                        broadcastAddresses.add(broadcast.getHostAddress());
                    }
                }
            }
        }
    } catch (SocketException ex) {
        LOGGER.error("Could not find broadcast address: {}", ex.getMessage(), ex);
    }
    return broadcastAddresses;
}
 
Example #8
Source File: NetworkUtils.java    From AndroidUtilCode with Apache License 2.0 6 votes vote down vote up
/**
 * Return the ip address of broadcast.
 *
 * @return the ip address of broadcast
 */
public static String getBroadcastIpAddress() {
    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        LinkedList<InetAddress> adds = new LinkedList<>();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            if (!ni.isUp() || ni.isLoopback()) continue;
            List<InterfaceAddress> ias = ni.getInterfaceAddresses();
            for (int i = 0, size = ias.size(); i < size; i++) {
                InterfaceAddress ia = ias.get(i);
                InetAddress broadcast = ia.getBroadcast();
                if (broadcast != null) {
                    return broadcast.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example #9
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 #10
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 #11
Source File: MulticastDiscoveryAgent.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private static List<NetworkInterface> findNetworkInterfaces() throws SocketException {
    Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces();
    List<NetworkInterface> interfaces = new ArrayList<NetworkInterface>();
    while (ifcs.hasMoreElements()) {
        NetworkInterface ni = ifcs.nextElement();
        LOG.trace("findNetworkInterfaces checking interface: {}", ni);

        if (ni.supportsMulticast() && ni.isUp()) {
            for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
                if (ia.getAddress() instanceof java.net.Inet4Address &&
                    !ia.getAddress().isLoopbackAddress() &&
                    !DEFAULT_EXCLUSIONS.contains(ni.getName())) {
                    // Add at the start, make usage order consistent with the
                    // existing ActiveMQ releases discovery will be used with.
                    interfaces.add(0, ni);
                    break;
                }
            }
        }
    }

    LOG.trace("findNetworkInterfaces returning: {}", interfaces);

    return interfaces;
}
 
Example #12
Source File: AbstractDhcpServerTest.java    From dhcp4j with Apache License 2.0 6 votes vote down vote up
/**
 * ifconfig br0 10.27.0.1
 * sudo dhcping -h 08:00:20:c0:ff:ee -s 10.27.0.1
 * OR
 * sudo dhclient -d eth0 -n
 */
@Nonnull
public FixedStoreLeaseManager newLeaseManager(@Nonnull String interfaceName) throws Exception {
    NetworkInterface iface = getNetworkInterfaceByName(interfaceName);
    if (iface == null) {
        print(NetworkInterface.getNetworkInterfaces(), 0);
        assertNotNull("No such interface " + interfaceName, iface);
    }
    InterfaceAddress address = Iterables.find(iface.getInterfaceAddresses(), new Predicate<InterfaceAddress>() {
        public boolean apply(InterfaceAddress input) {
            return input.getAddress() instanceof Inet4Address;
        }
    });
    NetworkAddress network = new NetworkAddress(address);
    FixedStoreLeaseManager manager = new FixedStoreLeaseManager();
    manager.addLease(HardwareAddress.fromString("08:00:20:c0:ff:ee"), network.getMachineAddress(42));
    return manager;
}
 
Example #13
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 #14
Source File: NetworkPrefixLength.java    From openjdk-8-source 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 #15
Source File: NetworkAddressFactoryImpl.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
protected InetAddress getBindAddressInSubnetOf(InetAddress inetAddress) {
    synchronized (networkInterfaces) {
        for (NetworkInterface iface : networkInterfaces) {
            for (InterfaceAddress ifaceAddress : getInterfaceAddresses(iface)) {

                synchronized (bindAddresses) {
                    if (ifaceAddress == null || !bindAddresses.contains(ifaceAddress.getAddress())) {
                        continue;
                    }
                }

                if (isInSubnet(
                        inetAddress.getAddress(),
                        ifaceAddress.getAddress().getAddress(),
                        ifaceAddress.getNetworkPrefixLength())
                        ) {
                    return ifaceAddress.getAddress();
                }
            }

        }
    }
    return null;
}
 
Example #16
Source File: NetworkOrganizer.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
protected List<NetworkInformation> buildLocalInformation() {
    List<NetworkInformation> list = new ArrayList<>();
    NetworkInformation netInfo = new NetworkInformation();
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

        for (NetworkInterface networkInterface : interfaces) {
            if (!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);
            }
        }
        list.add(netInfo);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return list;
}
 
Example #17
Source File: NetworkHelper.java    From orWall with GNU General Public License v3.0 6 votes vote down vote up
public static String getMask(String intf){
    try {
        NetworkInterface ntwrk = NetworkInterface.getByName(intf);
        Iterator<InterfaceAddress> addrList = ntwrk.getInterfaceAddresses().iterator();
        while (addrList.hasNext()) {
            InterfaceAddress addr = addrList.next();
            InetAddress ip = addr.getAddress();
            if (ip instanceof Inet4Address) {
                String mask = ip.getHostAddress() + "/" +
                        addr.getNetworkPrefixLength();
                return mask;
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #18
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 #19
Source File: NetWorkUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取广播 IP 地址
 * @return 广播 IP 地址
 */
public static String getBroadcastIpAddress() {
    try {
        Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
        while (nis.hasMoreElements()) {
            NetworkInterface ni = nis.nextElement();
            if (!ni.isUp() || ni.isLoopback()) continue;
            List<InterfaceAddress> ias = ni.getInterfaceAddresses();
            for (int i = 0; i < ias.size(); i++) {
                InterfaceAddress ia = ias.get(i);
                InetAddress broadcast = ia.getBroadcast();
                if (broadcast != null) {
                    return broadcast.getHostAddress();
                }
            }
        }
    } catch (Exception e) {
        LogPrintUtils.eTag(TAG, e, "getBroadcastIpAddress");
    }
    return null;
}
 
Example #20
Source File: VoidParameterServer.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns set of local IP addresses available in system.
 *
 * PLEASE NOTE: loopback, disabled interfaces, IPv6 addresses are ignored here.
 *
 * @return
 */
public static Set<String> getLocalAddresses() {
    try {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());

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

        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;

                result.add(addr);
            }
        }

        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: Docker.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public String getHostIpForContainers() {
  try {
    Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
    while (b.hasMoreElements()) {
      NetworkInterface iface = b.nextElement();
      if (iface.getName().contains("docker")) {
        for (InterfaceAddress f : iface.getInterfaceAddresses()) {
          if (f.getAddress().isSiteLocalAddress()) {
            String addr = f.getAddress().toString();
            log.debug("Host IP for container is {}", addr);
            return addr;
          }
        }
      }
    }
  } catch (SocketException e) {
    // This shouldn't happen
    log.warn("Exception getting docker address", e);
  }

  return null;
}
 
Example #22
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 #23
Source File: NetUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static List<String> getAllDefaultNicIps() {
    final List<String> addrs = new ArrayList<>();
    final String pubNic = getDefaultEthDevice();

    if (pubNic == null) {
        return addrs;
    }

    NetworkInterface nic = null;
    try {
        nic = NetworkInterface.getByName(pubNic);
    } catch (final SocketException e) {
        return addrs;
    }

    for (InterfaceAddress address : nic.getInterfaceAddresses()) {
        addrs.add(address.getAddress().getHostAddress().split("%")[0]);
    }
    return addrs;
}
 
Example #24
Source File: NetworkUtils.java    From logstash with Apache License 2.0 6 votes vote down vote up
private InetAddress getLocalAddress(String adaptorName){
    try {
        Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces();
        while (b.hasMoreElements()) {
            NetworkInterface networkInterface = b.nextElement();
            if (networkInterface.getName().equals(adaptorName)) {
                for (InterfaceAddress f : networkInterface.getInterfaceAddresses()) {
                    if (f.getAddress().isSiteLocalAddress()) {
                        return f.getAddress();
                    }
                }
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #25
Source File: NetworkPrefixLength.java    From openjdk-jdk8u 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 #26
Source File: Tools.java    From AndroidDemo with MIT License 6 votes vote down vote up
public static String getBroadcast() {
    System.setProperty("java.net.preferIPv4Stack", "true");
    try {
        for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum.hasMoreElements(); ) {
            NetworkInterface ni = niEnum.nextElement();
            if (ni.getName().toLowerCase().equals("wlan0")) {
                if (!ni.isLoopback()) {
                    for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                        if (interfaceAddress.getBroadcast() != null) {
                            return interfaceAddress.getBroadcast().toString().substring(1);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        //
    }
    return null;
}
 
Example #27
Source File: Socks5Proxy.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Private constructor.
 */
Socks5Proxy() {
    this.serverProcess = new Socks5ServerProcess();

    allowAllConnections = false;

    Enumeration<NetworkInterface> networkInterfaces;
    try {
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        throw new IllegalStateException(e);
    }
    Set<InetAddress> localAddresses = new HashSet<>();
    for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
        List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
        for (InterfaceAddress interfaceAddress : interfaceAddresses) {
            localAddresses.add(interfaceAddress.getAddress());
        }
    }
    if (localAddresses.isEmpty()) {
        throw new IllegalStateException("Could not determine any local internet address");
    }
    replaceLocalAddresses(localAddresses);
}
 
Example #28
Source File: NetworkUtils.java    From submarine with Apache License 2.0 6 votes vote down vote up
public static String findAvailableHostAddress() throws UnknownHostException, SocketException {
  String submarineServerIP = System.getenv("SUBMARINE_LOCAL_IP");
  if (submarineServerIP != null) {
    return submarineServerIP;
  }

  InetAddress address = InetAddress.getLocalHost();
  if (address.isLoopbackAddress()) {
    for (NetworkInterface networkInterface : Collections
        .list(NetworkInterface.getNetworkInterfaces())) {
      if (!networkInterface.isLoopback()) {
        for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
          InetAddress a = interfaceAddress.getAddress();
          if (a instanceof Inet4Address) {
            return a.getHostAddress();
          }
        }
      }
    }
  }
  return address.getHostAddress();
}
 
Example #29
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 #30
Source File: StorageUtils.java    From incubator-crail with Apache License 2.0 6 votes vote down vote up
public static InetSocketAddress getDataNodeAddress(String ifname, int port) throws IOException {
	NetworkInterface netif = NetworkInterface.getByName(ifname);
	if (netif == null){
		throw new IOException("Cannot find network interface with name " + ifname);
	}
	List<InterfaceAddress> addresses = netif.getInterfaceAddresses();
	InetAddress addr = null;
	for (InterfaceAddress address: addresses){
		if (address.getBroadcast() != null){
			InetAddress _addr = address.getAddress();
			addr = _addr;
		}
	}

	if (addr == null){
		throw new IOException("Network interface with name " + ifname + " has no valid IP address");
	}
	InetSocketAddress inetAddr = new InetSocketAddress(addr, port);
	return inetAddr;
}