下面列出了怎么用java.net.ProtocolFamily的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
public static InetAddress getDefaultRoute(Class<? extends InetAddress> type) {
InetAddress target = null;
ProtocolFamily family = type == Inet6Address.class ? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
try(DatagramChannel chan=DatagramChannel.open(family)) {
if(type == Inet4Address.class)
target = InetAddress.getByAddress(new byte[] {8,8,8,8});
if(type == Inet6Address.class)
target = InetAddress.getByName("2001:4860:4860::8888");
chan.connect(new InetSocketAddress(target,63));
InetSocketAddress soa = (InetSocketAddress) chan.getLocalAddress();
InetAddress local = soa.getAddress();
if(type.isInstance(local) && !local.isAnyLocalAddress())
return local;
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Encodes the given InetSocketAddress into this socket address.
* @param protocolFamily protocol family
* @param isa the InetSocketAddress to encode
* @return the size of the socket address (sizeof sockaddr or sockaddr6)
* @throws UnsupportedAddressTypeException if the address type is not supported
*/
int encode(ProtocolFamily protocolFamily, InetSocketAddress isa) {
if (protocolFamily == StandardProtocolFamily.INET) {
// struct sockaddr
InetAddress ia = isa.getAddress();
if (!(ia instanceof Inet4Address))
throw new UnsupportedAddressTypeException();
putFamily(AF_INET);
putAddress(AF_INET, ia);
putPort(AF_INET, isa.getPort());
return SIZEOF_SOCKADDR4;
} else {
// struct sockaddr6
putFamily(AF_INET6);
putAddress(AF_INET6, isa.getAddress());
putPort(AF_INET6, isa.getPort());
UNSAFE.putInt(address + OFFSET_SIN6_FLOWINFO, 0);
return SIZEOF_SOCKADDR6;
}
}
public LocalServiceDiscoveryInfo(
Set<SocketChannelConnectionAcceptor> socketAcceptors,
Collection<AnnounceGroup> announceGroups) {
this.localPorts = unmodifiableSet(collectLocalPorts(socketAcceptors));
Collection<NetworkInterface> networkInterfaces = new HashSet<>();
boolean acceptIP4 = false;
boolean acceptIP6 = false;
for (SocketChannelConnectionAcceptor acceptor : socketAcceptors) {
networkInterfaces.add(acceptor.getNetworkInterface());
InetSocketAddress address = acceptor.getLocalAddress();
ProtocolFamily protocolFamily = InternetProtocolUtils.getProtocolFamily(address.getAddress());
if (protocolFamily == StandardProtocolFamily.INET) {
acceptIP4 = true;
} else {
acceptIP6 = true;
}
if (acceptIP4 && acceptIP6) {
break; // no need to look further
}
}
this.compatibleGroups = unmodifiableCollection(collectCompatibleGroups(announceGroups, acceptIP4, acceptIP6));
this.networkInterfaces = unmodifiableCollection(networkInterfaces);
}
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
DNSDatagramSocketFactory(Random random,
ProtocolFamily family,
int deviation,
int threshold) {
this.random = Objects.requireNonNull(random);
this.history = new PortHistory(HISTORY, random);
this.family = family;
this.deviation = Math.max(1, deviation);
this.thresholdCount = Math.max(2, threshold);
}
private DHTtype(String shortName, int nodeslength, int addresslength, Class<? extends InetAddress> addresstype, int header, int maxSize, ProtocolFamily family) {
this.shortName = shortName;
this.NODES_ENTRY_LENGTH = nodeslength;
this.PREFERRED_ADDRESS_TYPE = addresstype;
this.ADDRESS_ENTRY_LENGTH = addresslength;
this.HEADER_LENGTH = header;
this.MAX_PACKET_SIZE = maxSize;
this.PROTO_FAMILY = family;
}
/**
* Convert the {@link InternetProtocolFamily}. This MUST only be called on jdk version >= 7.
*/
public static ProtocolFamily convert(InternetProtocolFamily family) {
switch (family) {
case IPv4:
return StandardProtocolFamily.INET;
case IPv6:
return StandardProtocolFamily.INET6;
default:
throw new IllegalArgumentException();
}
}
DNSDatagramSocketFactory(Random random,
ProtocolFamily family,
int deviation,
int threshold) {
this.random = Objects.requireNonNull(random);
this.history = new PortHistory(HISTORY, random);
this.family = family;
this.deviation = Math.max(1, deviation);
this.thresholdCount = Math.max(2, threshold);
}
private synchronized DatagramChannel getChannel() throws IOException {
if (channel == null || !channel.isOpen()) {
if (shutdown.get()) {
throw new IllegalStateException("Channel has been shut down");
}
ProtocolFamily protocolFamily = InternetProtocolUtils.getProtocolFamily(group.getAddress().getAddress());
DatagramChannel _channel = selector.provider().openDatagramChannel(protocolFamily);
_channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
// bind to any-local before setting TTL
int port = group.getAddress().getPort();
if (protocolFamily == StandardProtocolFamily.INET) {
_channel.bind(new InetSocketAddress(Inet4Address.getByName("0.0.0.0"), port));
} else {
_channel.bind(new InetSocketAddress(Inet6Address.getByName("[::]"), port));
}
int timeToLive = group.getTimeToLive();
if (timeToLive != 1) {
_channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, timeToLive);
}
for (NetworkInterface iface : networkInterfaces) {
_channel.join(group.getAddress().getAddress(), iface);
}
_channel.configureBlocking(false);
channel = _channel;
}
return channel;
}
/**
* @return {@link StandardProtocolFamily#INET} for IPv4 address or {@link StandardProtocolFamily#INET6} for IPv6 address
* @throws IllegalArgumentException if the address is neither IPv4 or IPv6
* @since 1.6
*/
public static ProtocolFamily getProtocolFamily(InetAddress address) {
if (address.getAddress().length == IP4_BYTES) {
return StandardProtocolFamily.INET;
} else if (address.getAddress().length == IP6_BYTES) {
return StandardProtocolFamily.INET6;
} else {
throw new IllegalArgumentException("Can't determine protocol family for address: " + address);
}
}
DNSDatagramSocketFactory(Random random,
ProtocolFamily family,
int deviation,
int threshold) {
this.random = Objects.requireNonNull(random);
this.history = new PortHistory(HISTORY, random);
this.family = family;
this.deviation = Math.max(1, deviation);
this.thresholdCount = Math.max(2, threshold);
}
DNSDatagramSocketFactory(Random random,
ProtocolFamily family,
int deviation,
int threshold) {
this.random = Objects.requireNonNull(random);
this.history = new PortHistory(HISTORY, random);
this.family = family;
this.deviation = Math.max(1, deviation);
this.thresholdCount = Math.max(2, threshold);
}
/**
* Returns the protocol family to specify to set/getSocketOption for the
* given socket option.
*/
private ProtocolFamily familyFor(SocketOption<?> name) {
assert Thread.holdsLock(stateLock);
// unspecified (most options)
if (SocketOptionRegistry.findOption(name, Net.UNSPEC) != null)
return Net.UNSPEC;
// IPv4 socket
if (family == StandardProtocolFamily.INET)
return StandardProtocolFamily.INET;
// IPv6 socket that is unbound
if (localAddress == null)
return StandardProtocolFamily.INET6;
// IPv6 socket bound to wildcard or IPv6 address
InetAddress address = localAddress.getAddress();
if (address.isAnyLocalAddress() || (address instanceof Inet6Address))
return StandardProtocolFamily.INET6;
// IPv6 socket bound to IPv4 address
if (Net.canUseIPv6OptionsWithIPv4LocalAddress()) {
// IPV6_XXX options can be used
return StandardProtocolFamily.INET6;
} else {
// IPV6_XXX options cannot be used
return StandardProtocolFamily.INET;
}
}
static InetSocketAddress checkAddress(SocketAddress sa, ProtocolFamily family) {
InetSocketAddress isa = checkAddress(sa);
if (family == StandardProtocolFamily.INET) {
InetAddress addr = isa.getAddress();
if (!(addr instanceof Inet4Address))
throw new UnsupportedAddressTypeException();
}
return isa;
}
static Object getSocketOption(FileDescriptor fd, ProtocolFamily family, SocketOption<?> name)
throws IOException
{
Class<?> type = name.type();
if (extendedOptions.isOptionSupported(name)) {
return extendedOptions.getOption(fd, name);
}
// only simple values supported by this method
if (type != Integer.class && type != Boolean.class)
throw new AssertionError("Should not reach here");
// map option name to platform level/name
OptionKey key = SocketOptionRegistry.findOption(name, family);
if (key == null)
throw new AssertionError("Option not found");
boolean mayNeedConversion = (family == UNSPEC);
int value = getIntOption0(fd, mayNeedConversion, key.level(), key.name());
if (type == Integer.class) {
return Integer.valueOf(value);
} else {
return (value == 0) ? Boolean.FALSE : Boolean.TRUE;
}
}
static void bind(ProtocolFamily family, FileDescriptor fd,
InetAddress addr, int port) throws IOException
{
boolean preferIPv6 = isIPv6Available() &&
(family != StandardProtocolFamily.INET);
if (addr.isLinkLocalAddress()) {
addr = IPAddressUtil.toScopedAddress(addr);
}
bind0(fd, preferIPv6, exclusiveBind, addr, port);
}
static int connect(ProtocolFamily family, FileDescriptor fd, InetAddress remote, int remotePort)
throws IOException
{
if (remote.isLinkLocalAddress()) {
remote = IPAddressUtil.toScopedAddress(remote);
}
boolean preferIPv6 = isIPv6Available() &&
(family != StandardProtocolFamily.INET);
return connect0(preferIPv6, fd, remote, remotePort);
}
@Override
@SuppressWarnings("unchecked")
public <T> T getOption(SocketOption<T> name)
throws IOException
{
Objects.requireNonNull(name);
if (!supportedOptions().contains(name))
throw new UnsupportedOperationException("'" + name + "' not supported");
synchronized (stateLock) {
ensureOpen();
if (name == StandardSocketOptions.SO_REUSEADDR && Net.useExclusiveBind()) {
// SO_REUSEADDR emulated when using exclusive bind
return (T)Boolean.valueOf(isReuseAddress);
}
// special handling for IP_TOS: always return 0 when IPv6
if (name == StandardSocketOptions.IP_TOS) {
ProtocolFamily family = Net.isIPv6Available() ?
StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
return (T) Net.getSocketOption(fd, family, name);
}
// no options that require special handling
return (T) Net.getSocketOption(fd, name);
}
}
/**
* Returns the socket protocol family.
*/
private static ProtocolFamily family() {
if (Net.isIPv6Available()) {
return StandardProtocolFamily.INET6;
} else {
return StandardProtocolFamily.INET;
}
}
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
if (interf == null) {
throw new JdpException("Unable to get network interface for " + srcAddress.toString());
}
if (!interf.isUp()) {
throw new JdpException(interf.getName() + " is not up.");
}
if (!interf.supportsMulticast()) {
throw new JdpException(interf.getName() + " does not support multicast.");
}
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
DNSDatagramSocketFactory(Random random,
ProtocolFamily family,
int deviation,
int threshold) {
this.random = Objects.requireNonNull(random);
this.history = new PortHistory(HISTORY, random);
this.family = family;
this.deviation = Math.max(1, deviation);
this.thresholdCount = Math.max(2, threshold);
}
public DatagramChannel openDatagramChannel(ProtocolFamily family) throws IOException {
return new DatagramChannelImpl(this, family);
}
public DatagramChannel openDatagramChannel(ProtocolFamily family)
throws IOException
{
return provider.openDatagramChannel(family);
}
public void setProtocolFamily(ProtocolFamily protocolFamily) {
this.protocolFamily = protocolFamily;
}