@Override
  @SuppressWarnings("unchecked")
  public <T> T getOption(SocketOption<T> name) throws IOException {
    if (name == null) throw new NullPointerException();
    if (!supportedOptions().contains(name))
      throw new UnsupportedOperationException("'" + name + "' not supported");

    synchronized (stateLock) {
      ensureOpen();

      if (name == StandardSocketOptions.IP_TOS) {
        // IPv4 only; always return 0 on IPv6
        if (family == StandardProtocolFamily.INET) {
          return (T) Net.getSocketOption(fd, family, name);
        } else {
          return (T) Integer.valueOf(0);
        }
      }

      if (name == StandardSocketOptions.IP_MULTICAST_TTL
          || name == StandardSocketOptions.IP_MULTICAST_LOOP) {
        return (T) Net.getSocketOption(fd, family, name);
      }

      if (name == StandardSocketOptions.IP_MULTICAST_IF) {
        if (family == StandardProtocolFamily.INET) {
          int address = Net.getInterface4(fd);
          if (address == 0) return null; // default interface

          InetAddress ia = Net.inet4FromInt(address);
          NetworkInterface ni = NetworkInterface.getByInetAddress(ia);
          if (ni == null) throw new IOException("Unable to map address to interface");
          return (T) ni;
        } else {
          int index = Net.getInterface6(fd);
          if (index == 0) return null; // default interface

          NetworkInterface ni = NetworkInterface.getByIndex(index);
          if (ni == null) throw new IOException("Unable to map index to interface");
          return (T) ni;
        }
      }

      // no special handling
      return (T) Net.getSocketOption(fd, Net.UNSPEC, name);
    }
  }