@Override
  public <T> DatagramChannel setOption(SocketOption<T> name, T value) 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; no-op for IPv6
        if (family == StandardProtocolFamily.INET) {
          Net.setSocketOption(fd, family, name, value);
        }
        return this;
      }

      if (name == StandardSocketOptions.IP_MULTICAST_TTL
          || name == StandardSocketOptions.IP_MULTICAST_LOOP) {
        // options are protocol dependent
        Net.setSocketOption(fd, family, name, value);
        return this;
      }

      if (name == StandardSocketOptions.IP_MULTICAST_IF) {
        if (value == null)
          throw new IllegalArgumentException("Cannot set IP_MULTICAST_IF to 'null'");
        NetworkInterface interf = (NetworkInterface) value;
        if (family == StandardProtocolFamily.INET6) {
          int index = interf.getIndex();
          if (index == -1) throw new IOException("Network interface cannot be identified");
          Net.setInterface6(fd, index);
        } else {
          // need IPv4 address to identify interface
          Inet4Address target = Net.anyInet4Address(interf);
          if (target == null) throw new IOException("Network interface not configured for IPv4");
          int targetAddress = Net.inet4AsInt(target);
          Net.setInterface4(fd, targetAddress);
        }
        return this;
      }

      // remaining options don't need any special handling
      Net.setSocketOption(fd, Net.UNSPEC, name, value);
      return this;
    }
  }