Example #1
0
  private static void collectIpv4Address(
      String interfaceName, List<InetAddress> addresses, List<InterfaceAddress> interfaceAddresses)
      throws SocketException {
    FileDescriptor fd = null;
    try {
      fd = Libcore.os.socket(AF_INET, SOCK_DGRAM, 0);
      InetAddress address = Libcore.os.ioctlInetAddress(fd, SIOCGIFADDR, interfaceName);
      InetAddress broadcast = Inet4Address.ANY;
      try {
        broadcast = Libcore.os.ioctlInetAddress(fd, SIOCGIFBRDADDR, interfaceName);
      } catch (ErrnoException e) {
        if (e.errno != EINVAL) {
          throw e;
        }
      }
      InetAddress netmask = Libcore.os.ioctlInetAddress(fd, SIOCGIFNETMASK, interfaceName);
      if (broadcast.equals(Inet4Address.ANY)) {
        broadcast = null;
      }

      addresses.add(address);
      interfaceAddresses.add(
          new InterfaceAddress(
              (Inet4Address) address, (Inet4Address) broadcast, (Inet4Address) netmask));
    } catch (ErrnoException errnoException) {
      if (errnoException.errno != EADDRNOTAVAIL && errnoException.errno != EOPNOTSUPP) {
        // EADDRNOTAVAIL just means no IPv4 address for this interface.
        // EOPNOTSUPP means the interface doesn't have an address, such as the lo interface.
        // Anything else is a real error.
        throw rethrowAsSocketException(errnoException);
      }
    } catch (Exception ex) {
      throw rethrowAsSocketException(ex);
    } finally {
      IoUtils.closeQuietly(fd);
    }
  }