8237352: Update DatagramSocket to add support for joining multicast groups

Reviewed-by: alanb
This commit is contained in:
Daniel Fuchs 2021-02-08 12:55:00 +00:00
parent d0a8f2f737
commit 2c28e36454
5 changed files with 931 additions and 111 deletions

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1995, 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -28,6 +28,7 @@ package java.net;
import java.io.IOException; import java.io.IOException;
import java.io.UncheckedIOException; import java.io.UncheckedIOException;
import java.nio.channels.DatagramChannel; import java.nio.channels.DatagramChannel;
import java.nio.channels.MulticastChannel;
import java.security.AccessController; import java.security.AccessController;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.util.Set; import java.util.Set;
@ -81,11 +82,11 @@ import sun.nio.ch.DefaultSelectorProvider;
* <tbody> * <tbody>
* <tr> * <tr>
* <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th> * <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th>
* <td> The size of the socket send buffer </td> * <td> The size of the socket send buffer in bytes </td>
* </tr> * </tr>
* <tr> * <tr>
* <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th> * <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th>
* <td> The size of the socket receive buffer </td> * <td> The size of the socket receive buffer in bytes </td>
* </tr> * </tr>
* <tr> * <tr>
* <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th> * <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th>
@ -102,10 +103,142 @@ import sun.nio.ch.DefaultSelectorProvider;
* </tbody> * </tbody>
* </table> * </table>
* </blockquote> * </blockquote>
* An implementation may also support additional options. In particular an implementation * <p> In addition, the {@code DatagramSocket} class defines methods to {@linkplain
* may support <a href="MulticastSocket.html#MulticastOptions">multicast options</a> which * #joinGroup(SocketAddress, NetworkInterface) join} and {@linkplain
* can be useful when using a plain {@code DatagramSocket} to send datagrams to a * #leaveGroup(SocketAddress, NetworkInterface) leave} a multicast group, and
* multicast group. * supports <a href="DatagramSocket.html#MulticastOptions">multicast options</a> which
* are useful when {@linkplain #joinGroup(SocketAddress, NetworkInterface) joining},
* {@linkplain #leaveGroup(SocketAddress, NetworkInterface) leaving}, or sending datagrams
* to a multicast group.
* The following multicast options are supported:
* <blockquote>
* <a id="MulticastOptions"></a>
* <table class="striped">
* <caption style="display:none">Multicast options</caption>
* <thead>
* <tr>
* <th scope="col">Option Name</th>
* <th scope="col">Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_IF IP_MULTICAST_IF} </th>
* <td> The network interface for Internet Protocol (IP) multicast datagrams </td>
* </tr>
* <tr>
* <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_TTL
* IP_MULTICAST_TTL} </th>
* <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast
* datagrams </td>
* </tr>
* <tr>
* <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_LOOP
* IP_MULTICAST_LOOP} </th>
* <td> Loopback for Internet Protocol (IP) multicast datagrams </td>
* </tr>
* </tbody>
* </table>
* </blockquote>
* An implementation may also support additional options.
*
* @apiNote <a id="Multicasting"></a><b>Multicasting with DatagramSocket</b>
*
* <p> {@link DatagramChannel} implements the {@link MulticastChannel} interface
* and provides an alternative API for sending and receiving multicast datagrams.
* The {@link MulticastChannel} API supports both {@linkplain
* MulticastChannel#join(InetAddress, NetworkInterface) any-source} and
* {@linkplain MulticastChannel#join(InetAddress, NetworkInterface, InetAddress)
* source-specific} multicast. Consider using {@code DatagramChannel} for
* multicasting.
*
* <p> {@code DatagramSocket} can be used directly for multicasting. However,
* contrarily to {@link MulticastSocket}, {@code DatagramSocket} doesn't call the
* {@link DatagramSocket#setReuseAddress(boolean)} method to enable the SO_REUSEADDR
* socket option by default. If creating a {@code DatagramSocket} intended to
* later join a multicast group, the caller should consider explicitly enabling
* the SO_REUSEADDR option.
*
* <p> An instance of {@code DatagramSocket} can be used to send or
* receive multicast datagram packets. It is not necessary to join a multicast
* group in order to send multicast datagrams. Before sending out multicast
* datagram packets however, the default outgoing interface for sending
* multicast datagram should first be configured using
* {@link #setOption(SocketOption, Object) setOption} and
* {@link StandardSocketOptions#IP_MULTICAST_IF}:
*
* <pre>{@code
* DatagramSocket sender = new DatagramSocket(new InetSocketAddress(0));
* NetworkInterface outgoingIf = NetworkInterface.getByName("en0");
* sender.setOption(StandardSocketOptions.IP_MULTICAST_IF, outgoingIf);
*
* // optionally configure multicast TTL; the TTL defines the scope of a
* // multicast datagram, for example, confining it to host local (0) or
* // link local (1) etc...
* int ttl = ...; // a number betwen 0 and 255
* sender.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
*
* // send a packet to a multicast group
* byte[] msgBytes = ...;
* InetAddress mcastaddr = InetAddress.getByName("228.5.6.7");
* int port = 6789;
* InetSocketAddress dest = new InetSocketAddress(mcastaddr, port);
* DatagramPacket hi = new DatagramPacket(msgBytes, msgBytes.length, dest);
* sender.send(hi);
* }</pre>
*
* <p> An instance of {@code DatagramSocket} can also be used to receive
* multicast datagram packets. A {@code DatagramSocket} that is created
* with the intent of receiving multicast datagrams should be created
* <i>unbound</i>. Before binding the socket, {@link #setReuseAddress(boolean)
* setReuseAddress(true)} should be configured:
*
* <pre>{@code
* DatagramSocket socket = new DatagramSocket(null); // unbound
* socket.setReuseAddress(true); // set reuse address before binding
* socket.bind(new InetSocketAddress(6789)); // bind
*
* // joinGroup 228.5.6.7
* InetAddress mcastaddr = InetAddress.getByName("228.5.6.7");
* InetSocketAddress group = new InetSocketAddress(mcastaddr, 0);
* NetworkInterface netIf = NetworkInterface.getByName("en0");
* socket.joinGroup(group, netIf);
* byte[] msgBytes = new byte[1024]; // up to 1024 bytes
* DatagramPacket packet = new DatagramPacket(msgBytes, msgBytes.length);
* socket.receive(packet);
* ....
* // eventually leave group
* socket.leaveGroup(group, netIf);
* }</pre>
*
* <p><a id="PlatformDependencies"></a><b>Platform dependencies</b>
* <p>The multicast implementation is intended to map directly to the native
* multicasting facility. Consequently, the following items should be considered
* when developing an application that receives IP multicast datagrams:
* <ol>
* <li> Contrarily to {@link DatagramChannel}, the constructors of {@code DatagramSocket}
* do not allow to specify the {@link ProtocolFamily} of the underlying socket.
* Consequently, the protocol family of the underlying socket may not
* correspond to the protocol family of the multicast groups that
* the {@code DatagramSocket} will attempt to join.
* <br>
* There is no guarantee that a {@code DatagramSocket} with an underlying
* socket created in one protocol family can join and receive multicast
* datagrams when the address of the multicast group corresponds to
* another protocol family. For example, it is implementation specific if a
* {@code DatagramSocket} to an IPv6 socket can join an IPv4 multicast group
* and receive multicast datagrams sent to the group.
* </li>
* <li> Before joining a multicast group, the {@code DatagramSocket} should be
* bound to the wildcard address.
* If the socket is bound to a specific address, rather than the wildcard address
* then it is implementation specific if multicast datagrams are received
* by the socket.
* </li>
* <li> The SO_REUSEADDR option should be enabled prior to binding the socket.
* This is required to allow multiple members of the group to bind to the same address.
* </li>
* </ol>
* *
* @author Pavani Diwanji * @author Pavani Diwanji
* @see java.net.DatagramPacket * @see java.net.DatagramPacket
@ -655,14 +788,20 @@ public class DatagramSocket implements java.io.Closeable {
* of SO_SNDBUF then it is implementation specific if the * of SO_SNDBUF then it is implementation specific if the
* packet is sent or discarded. * packet is sent or discarded.
* *
* @apiNote
* If {@code size > 0}, this method is equivalent to calling
* {@link #setOption(SocketOption, Object)
* setOption(StandardSocketOptions.SO_SNDBUF, size)}.
*
* @param size the size to which to set the send buffer * @param size the size to which to set the send buffer
* size. This value must be greater than 0. * size, in bytes. This value must be greater than 0.
* *
* @throws SocketException if there is an error * @throws SocketException if there is an error
* in the underlying protocol, such as an UDP error. * in the underlying protocol, such as an UDP error.
* @throws IllegalArgumentException if the value is 0 or is * @throws IllegalArgumentException if the value is 0 or is
* negative. * negative.
* @see #getSendBufferSize() * @see #getSendBufferSize()
* @see StandardSocketOptions#SO_SNDBUF
* @since 1.2 * @since 1.2
*/ */
public void setSendBufferSize(int size) throws SocketException { public void setSendBufferSize(int size) throws SocketException {
@ -671,12 +810,17 @@ public class DatagramSocket implements java.io.Closeable {
/** /**
* Get value of the SO_SNDBUF option for this {@code DatagramSocket}, that is the * Get value of the SO_SNDBUF option for this {@code DatagramSocket}, that is the
* buffer size used by the platform for output on this {@code DatagramSocket}. * buffer size, in bytes, used by the platform for output on this {@code DatagramSocket}.
*
* @apiNote
* This method is equivalent to calling {@link #getOption(SocketOption)
* getOption(StandardSocketOptions.SO_SNDBUF)}.
* *
* @return the value of the SO_SNDBUF option for this {@code DatagramSocket} * @return the value of the SO_SNDBUF option for this {@code DatagramSocket}
* @throws SocketException if there is an error in * @throws SocketException if there is an error in
* the underlying protocol, such as an UDP error. * the underlying protocol, such as an UDP error.
* @see #setSendBufferSize * @see #setSendBufferSize
* @see StandardSocketOptions#SO_SNDBUF
* @since 1.2 * @since 1.2
*/ */
public int getSendBufferSize() throws SocketException { public int getSendBufferSize() throws SocketException {
@ -702,14 +846,20 @@ public class DatagramSocket implements java.io.Closeable {
* Note: It is implementation specific if a packet larger * Note: It is implementation specific if a packet larger
* than SO_RCVBUF can be received. * than SO_RCVBUF can be received.
* *
* @apiNote
* If {@code size > 0}, this method is equivalent to calling
* {@link #setOption(SocketOption, Object)
* setOption(StandardSocketOptions.SO_RCVBUF, size)}.
*
* @param size the size to which to set the receive buffer * @param size the size to which to set the receive buffer
* size. This value must be greater than 0. * size, in bytes. This value must be greater than 0.
* *
* @throws SocketException if there is an error in * @throws SocketException if there is an error in
* the underlying protocol, such as an UDP error. * the underlying protocol, such as an UDP error.
* @throws IllegalArgumentException if the value is 0 or is * @throws IllegalArgumentException if the value is 0 or is
* negative. * negative.
* @see #getReceiveBufferSize() * @see #getReceiveBufferSize()
* @see StandardSocketOptions#SO_RCVBUF
* @since 1.2 * @since 1.2
*/ */
public void setReceiveBufferSize(int size) throws SocketException { public void setReceiveBufferSize(int size) throws SocketException {
@ -718,11 +868,16 @@ public class DatagramSocket implements java.io.Closeable {
/** /**
* Get value of the SO_RCVBUF option for this {@code DatagramSocket}, that is the * Get value of the SO_RCVBUF option for this {@code DatagramSocket}, that is the
* buffer size used by the platform for input on this {@code DatagramSocket}. * buffer size, in bytes, used by the platform for input on this {@code DatagramSocket}.
*
* @apiNote
* This method is equivalent to calling {@link #getOption(SocketOption)
* getOption(StandardSocketOptions.SO_RCVBUF)}.
* *
* @return the value of the SO_RCVBUF option for this {@code DatagramSocket} * @return the value of the SO_RCVBUF option for this {@code DatagramSocket}
* @throws SocketException if there is an error in the underlying protocol, such as an UDP error. * @throws SocketException if there is an error in the underlying protocol, such as an UDP error.
* @see #setReceiveBufferSize(int) * @see #setReceiveBufferSize(int)
* @see StandardSocketOptions#SO_RCVBUF
* @since 1.2 * @since 1.2
*/ */
public int getReceiveBufferSize() throws SocketException { public int getReceiveBufferSize() throws SocketException {
@ -753,6 +908,10 @@ public class DatagramSocket implements java.io.Closeable {
* disabled after a socket is bound (See {@link #isBound()}) * disabled after a socket is bound (See {@link #isBound()})
* is not defined. * is not defined.
* *
* @apiNote
* This method is equivalent to calling {@link #setOption(SocketOption, Object)
* setOption(StandardSocketOptions.SO_REUSEADDR, on)}.
*
* @param on whether to enable or disable the * @param on whether to enable or disable the
* @throws SocketException if an error occurs enabling or * @throws SocketException if an error occurs enabling or
* disabling the {@code SO_REUSEADDR} socket option, * disabling the {@code SO_REUSEADDR} socket option,
@ -762,6 +921,7 @@ public class DatagramSocket implements java.io.Closeable {
* @see #bind(SocketAddress) * @see #bind(SocketAddress)
* @see #isBound() * @see #isBound()
* @see #isClosed() * @see #isClosed()
* @see StandardSocketOptions#SO_REUSEADDR
*/ */
public void setReuseAddress(boolean on) throws SocketException { public void setReuseAddress(boolean on) throws SocketException {
delegate().setReuseAddress(on); delegate().setReuseAddress(on);
@ -770,11 +930,16 @@ public class DatagramSocket implements java.io.Closeable {
/** /**
* Tests if SO_REUSEADDR is enabled. * Tests if SO_REUSEADDR is enabled.
* *
* @apiNote
* This method is equivalent to calling {@link #getOption(SocketOption)
* getOption(StandardSocketOptions.SO_REUSEADDR)}.
*
* @return a {@code boolean} indicating whether or not SO_REUSEADDR is enabled. * @return a {@code boolean} indicating whether or not SO_REUSEADDR is enabled.
* @throws SocketException if there is an error * @throws SocketException if there is an error
* in the underlying protocol, such as an UDP error. * in the underlying protocol, such as an UDP error.
* @since 1.4 * @since 1.4
* @see #setReuseAddress(boolean) * @see #setReuseAddress(boolean)
* @see StandardSocketOptions#SO_REUSEADDR
*/ */
public boolean getReuseAddress() throws SocketException { public boolean getReuseAddress() throws SocketException {
return delegate().getReuseAddress(); return delegate().getReuseAddress();
@ -787,6 +952,10 @@ public class DatagramSocket implements java.io.Closeable {
* started with implementation specific privileges to enable this option or * started with implementation specific privileges to enable this option or
* send broadcast datagrams. * send broadcast datagrams.
* *
* @apiNote
* This method is equivalent to calling {@link #setOption(SocketOption, Object)
* setOption(StandardSocketOptions.SO_BROADCAST, on)}.
*
* @param on * @param on
* whether or not to have broadcast turned on. * whether or not to have broadcast turned on.
* *
@ -796,6 +965,7 @@ public class DatagramSocket implements java.io.Closeable {
* *
* @since 1.4 * @since 1.4
* @see #getBroadcast() * @see #getBroadcast()
* @see StandardSocketOptions#SO_BROADCAST
*/ */
public void setBroadcast(boolean on) throws SocketException { public void setBroadcast(boolean on) throws SocketException {
delegate().setBroadcast(on); delegate().setBroadcast(on);
@ -803,11 +973,17 @@ public class DatagramSocket implements java.io.Closeable {
/** /**
* Tests if SO_BROADCAST is enabled. * Tests if SO_BROADCAST is enabled.
*
* @apiNote
* This method is equivalent to calling {@link #getOption(SocketOption)
* getOption(StandardSocketOptions.SO_BROADCAST)}.
*
* @return a {@code boolean} indicating whether or not SO_BROADCAST is enabled. * @return a {@code boolean} indicating whether or not SO_BROADCAST is enabled.
* @throws SocketException if there is an error * @throws SocketException if there is an error
* in the underlying protocol, such as an UDP error. * in the underlying protocol, such as an UDP error.
* @since 1.4 * @since 1.4
* @see #setBroadcast(boolean) * @see #setBroadcast(boolean)
* @see StandardSocketOptions#SO_BROADCAST
*/ */
public boolean getBroadcast() throws SocketException { public boolean getBroadcast() throws SocketException {
return delegate().getBroadcast(); return delegate().getBroadcast();
@ -844,11 +1020,16 @@ public class DatagramSocket implements java.io.Closeable {
* for Internet Protocol v6 {@code tc} is the value that * for Internet Protocol v6 {@code tc} is the value that
* would be placed into the sin6_flowinfo field of the IP header. * would be placed into the sin6_flowinfo field of the IP header.
* *
* @apiNote
* This method is equivalent to calling {@link #setOption(SocketOption, Object)
* setOption(StandardSocketOptions.IP_TOS, tc)}.
*
* @param tc an {@code int} value for the bitset. * @param tc an {@code int} value for the bitset.
* @throws SocketException if there is an error setting the * @throws SocketException if there is an error setting the
* traffic class or type-of-service * traffic class or type-of-service
* @since 1.4 * @since 1.4
* @see #getTrafficClass * @see #getTrafficClass
* @see StandardSocketOptions#IP_TOS
*/ */
public void setTrafficClass(int tc) throws SocketException { public void setTrafficClass(int tc) throws SocketException {
delegate().setTrafficClass(tc); delegate().setTrafficClass(tc);
@ -864,11 +1045,16 @@ public class DatagramSocket implements java.io.Closeable {
* set using the {@link #setTrafficClass(int)} method on this * set using the {@link #setTrafficClass(int)} method on this
* DatagramSocket. * DatagramSocket.
* *
* @apiNote
* This method is equivalent to calling {@link #getOption(SocketOption)
* getOption(StandardSocketOptions.IP_TOS)}.
*
* @return the traffic class or type-of-service already set * @return the traffic class or type-of-service already set
* @throws SocketException if there is an error obtaining the * @throws SocketException if there is an error obtaining the
* traffic class or type-of-service value. * traffic class or type-of-service value.
* @since 1.4 * @since 1.4
* @see #setTrafficClass(int) * @see #setTrafficClass(int)
* @see StandardSocketOptions#IP_TOS
*/ */
public int getTrafficClass() throws SocketException { public int getTrafficClass() throws SocketException {
return delegate().getTrafficClass(); return delegate().getTrafficClass();
@ -1038,6 +1224,106 @@ public class DatagramSocket implements java.io.Closeable {
return delegate().supportedOptions(); return delegate().supportedOptions();
} }
/**
* Joins a multicast group.
*
* <p> In order to join a multicast group, the caller should specify
* the IP address of the multicast group to join, and the local
* {@linkplain NetworkInterface network interface} to receive multicast
* packets from.
* <ul>
* <li> The {@code mcastaddr} argument indicates the IP address
* of the multicast group to join. For historical reasons this is
* specified as a {@code SocketAddress}.
* The default implementation only supports {@link InetSocketAddress} and
* the {@link InetSocketAddress#getPort() port} information is ignored.
* </li>
* <li> The {@code netIf} argument specifies the local interface to receive
* multicast datagram packets, or {@code null} to defer to the interface
* set for outgoing multicast datagrams.
* If {@code null}, and no interface has been set, the behaviour is
* unspecified: any interface may be selected or the operation may fail
* with a {@code SocketException}.
* </li>
* </ul>
*
* <p> It is possible to call this method several times to join
* several different multicast groups, or join the same group
* in several different networks. However, if the socket is already a
* member of the group, an {@link IOException} will be thrown.
*
* <p>If there is a security manager, this method first
* calls its {@code checkMulticast} method with the {@code mcastaddr}
* argument as its argument.
*
* @apiNote The default interface for sending outgoing multicast datagrams
* can be configured with {@link #setOption(SocketOption, Object)}
* with {@link StandardSocketOptions#IP_MULTICAST_IF}.
*
* @param mcastaddr indicates the multicast address to join.
* @param netIf specifies the local interface to receive multicast
* datagram packets, or {@code null}.
* @throws IOException if there is an error joining, or when the address
* is not a multicast address, or the platform does not support
* multicasting
* @throws SecurityException if a security manager exists and its
* {@code checkMulticast} method doesn't allow the join.
* @throws IllegalArgumentException if mcastaddr is {@code null} or is a
* SocketAddress subclass not supported by this socket
* @see SecurityManager#checkMulticast(InetAddress)
* @see DatagramChannel#join(InetAddress, NetworkInterface)
* @see StandardSocketOptions#IP_MULTICAST_IF
* @since 17
*/
public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
throws IOException {
delegate().joinGroup(mcastaddr, netIf);
}
/**
* Leave a multicast group on a specified local interface.
*
* <p>If there is a security manager, this method first
* calls its {@code checkMulticast} method with the
* {@code mcastaddr} argument as its argument.
*
* @apiNote
* The {@code mcastaddr} and {@code netIf} arguments should identify
* a multicast group that was previously {@linkplain
* #joinGroup(SocketAddress, NetworkInterface) joined} by
* this {@code DatagramSocket}.
* <p> It is possible to call this method several times to leave
* multiple different multicast groups previously joined, or leave
* the same group previously joined in multiple different networks.
* However, if the socket is not a member of the specified group
* in the specified network, an {@link IOException} will be
* thrown.
*
* @param mcastaddr is the multicast address to leave. This should
* contain the same IP address than that used for {@linkplain
* #joinGroup(SocketAddress, NetworkInterface) joining}
* the group.
* @param netIf specifies the local interface or {@code null} to defer
* to the interface set for outgoing multicast datagrams.
* If {@code null}, and no interface has been set, the behaviour
* is unspecified: any interface may be selected or the operation
* may fail with a {@code SocketException}.
* @throws IOException if there is an error leaving or when the address
* is not a multicast address.
* @throws SecurityException if a security manager exists and its
* {@code checkMulticast} method doesn't allow the operation.
* @throws IllegalArgumentException if mcastaddr is {@code null} or is a
* SocketAddress subclass not supported by this socket.
* @see SecurityManager#checkMulticast(InetAddress)
* @see #joinGroup(SocketAddress, NetworkInterface)
* @see StandardSocketOptions#IP_MULTICAST_IF
* @since 17
*/
public void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf)
throws IOException {
delegate().leaveGroup(mcastaddr, netIf);
}
// Temporary solution until JDK-8237352 is addressed // Temporary solution until JDK-8237352 is addressed
private static final SocketAddress NO_DELEGATE = new SocketAddress() {}; private static final SocketAddress NO_DELEGATE = new SocketAddress() {};
private static final boolean USE_PLAINDATAGRAMSOCKET = usePlainDatagramSocketImpl(); private static final boolean USE_PLAINDATAGRAMSOCKET = usePlainDatagramSocketImpl();

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 1995, 2020, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -44,7 +44,7 @@ import java.nio.channels.MulticastChannel;
* with the desired port, then invoking the * with the desired port, then invoking the
* <CODE>joinGroup(InetAddress groupAddr)</CODE> * <CODE>joinGroup(InetAddress groupAddr)</CODE>
* method: * method:
* <PRE> * <PRE>{@code
* // join a Multicast group and send the group salutations * // join a Multicast group and send the group salutations
* ... * ...
* String msg = "Hello"; * String msg = "Hello";
@ -65,7 +65,7 @@ import java.nio.channels.MulticastChannel;
* ... * ...
* // OK, I'm done talking - leave the group... * // OK, I'm done talking - leave the group...
* s.leaveGroup(group, netIf); * s.leaveGroup(group, netIf);
* </PRE> * }</PRE>
* *
* When one sends a message to a multicast group, <B>all</B> subscribing * When one sends a message to a multicast group, <B>all</B> subscribing
* recipients to that host and port receive the message (within the * recipients to that host and port receive the message (within the
@ -86,46 +86,19 @@ import java.nio.channels.MulticastChannel;
* supports the {@link #setOption(SocketOption, Object) setOption} * supports the {@link #setOption(SocketOption, Object) setOption}
* and {@link #getOption(SocketOption) getOption} methods to set * and {@link #getOption(SocketOption) getOption} methods to set
* and query socket options. * and query socket options.
* In addition to the socket options supported by * <a id="MulticastOptions"></a>The set of supported socket options
* <a href="DatagramSocket.html#SocketOptions">{@code DatagramSocket}</a>, a * is defined in <a href="DatagramSocket.html#SocketOptions">{@code DatagramSocket}</a>.
* {@code MulticastSocket} supports the following socket options:
* <blockquote>
* <a id="MulticastOptions"></a>
* <table class="striped">
* <caption style="display:none">Socket options</caption>
* <thead>
* <tr>
* <th scope="col">Option Name</th>
* <th scope="col">Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_IF IP_MULTICAST_IF} </th>
* <td> The network interface for Internet Protocol (IP) multicast datagrams </td>
* </tr>
* <tr>
* <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_TTL
* IP_MULTICAST_TTL} </th>
* <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast
* datagrams </td>
* </tr>
* <tr>
* <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_LOOP
* IP_MULTICAST_LOOP} </th>
* <td> Loopback for Internet Protocol (IP) multicast datagrams </td>
* </tr>
* </tbody>
* </table>
* </blockquote>
* Additional (implementation specific) options may also be supported. * Additional (implementation specific) options may also be supported.
* *
* @apiNote {@link DatagramChannel} implements the {@link MulticastChannel} interface * @apiNote {@link DatagramSocket} may be used directly for
* sending and receiving multicast datagrams.
* {@link DatagramChannel} implements the {@link MulticastChannel} interface
* and provides an alternative API for sending and receiving multicast datagrams. * and provides an alternative API for sending and receiving multicast datagrams.
* The {@link MulticastChannel} API supports both {@linkplain * The {@link MulticastChannel} API supports both {@linkplain
* MulticastChannel#join(InetAddress, NetworkInterface) any-source} and * MulticastChannel#join(InetAddress, NetworkInterface) any-source} and
* {@linkplain MulticastChannel#join(InetAddress, NetworkInterface, InetAddress) * {@linkplain MulticastChannel#join(InetAddress, NetworkInterface, InetAddress)
* source-specific} multicast. * source-specific} multicast. Consider using {@link DatagramChannel} for
* multicasting.
* *
* @author Pavani Diwanji * @author Pavani Diwanji
* @since 1.1 * @since 1.1
@ -243,7 +216,7 @@ public class MulticastSocket extends DatagramSocket {
* @param ttl the time-to-live * @param ttl the time-to-live
* @throws IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
* while setting the default time-to-live value * while setting the default time-to-live value
* @deprecated use the setTimeToLive method instead, which uses * @deprecated use the {@link #setTimeToLive(int)} method instead, which uses
* <b>int</b> instead of <b>byte</b> as the type for ttl. * <b>int</b> instead of <b>byte</b> as the type for ttl.
* @see #getTTL() * @see #getTTL()
*/ */
@ -262,6 +235,10 @@ public class MulticastSocket extends DatagramSocket {
* Multicast packets sent with a TTL of {@code 0} are not transmitted * Multicast packets sent with a TTL of {@code 0} are not transmitted
* on the network but may be delivered locally. * on the network but may be delivered locally.
* *
* @apiNote
* This method is equivalent to calling {@link #setOption(SocketOption, Object)
* setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl)}.
*
* @param ttl * @param ttl
* the time-to-live * the time-to-live
* *
@ -270,6 +247,7 @@ public class MulticastSocket extends DatagramSocket {
* default time-to-live value * default time-to-live value
* *
* @see #getTimeToLive() * @see #getTimeToLive()
* @see StandardSocketOptions#IP_MULTICAST_TTL
* @since 1.2 * @since 1.2
*/ */
public void setTimeToLive(int ttl) throws IOException { public void setTimeToLive(int ttl) throws IOException {
@ -283,8 +261,8 @@ public class MulticastSocket extends DatagramSocket {
* @throws IOException if an I/O exception occurs * @throws IOException if an I/O exception occurs
* while getting the default time-to-live value * while getting the default time-to-live value
* @return the default time-to-live value * @return the default time-to-live value
* @deprecated use the getTimeToLive method instead, which returns * @deprecated use the {@link #getTimeToLive()} method instead,
* an <b>int</b> instead of a <b>byte</b>. * which returns an <b>int</b> instead of a <b>byte</b>.
* @see #setTTL(byte) * @see #setTTL(byte)
*/ */
@Deprecated @Deprecated
@ -295,10 +273,16 @@ public class MulticastSocket extends DatagramSocket {
/** /**
* Get the default time-to-live for multicast packets sent out on * Get the default time-to-live for multicast packets sent out on
* the socket. * the socket.
*
* @apiNote
* This method is equivalent to calling {@link #getOption(SocketOption)
* getOption(StandardSocketOptions.IP_MULTICAST_TTL)}.
*
* @throws IOException if an I/O exception occurs while * @throws IOException if an I/O exception occurs while
* getting the default time-to-live value * getting the default time-to-live value
* @return the default time-to-live value * @return the default time-to-live value
* @see #setTimeToLive(int) * @see #setTimeToLive(int)
* @see StandardSocketOptions#IP_MULTICAST_TTL
* @since 1.2 * @since 1.2
*/ */
public int getTimeToLive() throws IOException { public int getTimeToLive() throws IOException {
@ -313,6 +297,11 @@ public class MulticastSocket extends DatagramSocket {
* calls its {@code checkMulticast} method with the * calls its {@code checkMulticast} method with the
* {@code mcastaddr} argument as its argument. * {@code mcastaddr} argument as its argument.
* *
* @apiNote
* Calling this method is equivalent to calling
* {@link #joinGroup(SocketAddress, NetworkInterface)
* joinGroup(new InetSocketAddress(mcastaddr, 0), null)}.
*
* @param mcastaddr is the multicast address to join * @param mcastaddr is the multicast address to join
* @throws IOException if there is an error joining, * @throws IOException if there is an error joining,
* or when the address is not a multicast address, * or when the address is not a multicast address,
@ -337,6 +326,11 @@ public class MulticastSocket extends DatagramSocket {
* calls its {@code checkMulticast} method with the * calls its {@code checkMulticast} method with the
* {@code mcastaddr} argument as its argument. * {@code mcastaddr} argument as its argument.
* *
* @apiNote
* Calling this method is equivalent to calling
* {@link #leaveGroup(SocketAddress, NetworkInterface)
* leaveGroup(new InetSocketAddress(mcastaddr, 0), null)}.
*
* @param mcastaddr is the multicast address to leave * @param mcastaddr is the multicast address to leave
* @throws IOException if there is an error leaving * @throws IOException if there is an error leaving
* or when the address is not a multicast address. * or when the address is not a multicast address.
@ -353,65 +347,38 @@ public class MulticastSocket extends DatagramSocket {
} }
/** /**
* Joins the specified multicast group at the specified interface. * {@inheritDoc}
* * @throws IOException {@inheritDoc}
* <p>If there is a security manager, this method first * @throws SecurityException {@inheritDoc}
* calls its {@code checkMulticast} method * @throws IllegalArgumentException {@inheritDoc}
* with the {@code mcastaddr} argument
* as its argument.
*
* @param mcastaddr is the multicast address to join
* @param netIf specifies the local interface to receive multicast
* datagram packets, or {@code null} to defer to the interface set by
* {@link MulticastSocket#setInterface(InetAddress)} or
* {@link MulticastSocket#setNetworkInterface(NetworkInterface)}.
* If {@code null}, and no interface has been set, the behaviour is
* unspecified: any interface may be selected or the operation may fail
* with a {@code SocketException}.
* @throws IOException if there is an error joining, or when the address
* is not a multicast address, or the platform does not support
* multicasting
* @throws SecurityException if a security manager exists and its
* {@code checkMulticast} method doesn't allow the join.
* @throws IllegalArgumentException if mcastaddr is {@code null} or is a
* SocketAddress subclass not supported by this socket
* @see SecurityManager#checkMulticast(InetAddress) * @see SecurityManager#checkMulticast(InetAddress)
* @see DatagramChannel#join(InetAddress, NetworkInterface) * @see DatagramChannel#join(InetAddress, NetworkInterface)
* @since 1.4 * @see StandardSocketOptions#IP_MULTICAST_IF
* @see #setNetworkInterface(NetworkInterface)
* @see #setInterface(InetAddress)
* @since 1.4
*/ */
@Override
public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
throws IOException { throws IOException {
delegate().joinGroup(mcastaddr, netIf); super.joinGroup(mcastaddr, netIf);
} }
/** /**
* Leave a multicast group on a specified local interface. * {@inheritDoc}
* * @apiNote {@inheritDoc}
* <p>If there is a security manager, this method first * @throws IOException {@inheritDoc}
* calls its {@code checkMulticast} method with the * @throws SecurityException {@inheritDoc}
* {@code mcastaddr} argument as its argument. * @throws IllegalArgumentException {@inheritDoc}
*
* @param mcastaddr is the multicast address to leave
* @param netIf specifies the local interface or {@code null} to defer
* to the interface set by
* {@link MulticastSocket#setInterface(InetAddress)} or
* {@link MulticastSocket#setNetworkInterface(NetworkInterface)}.
* If {@code null}, and no interface has been set, the behaviour
* is unspecified: any interface may be selected or the operation
* may fail with a {@code SocketException}.
* @throws IOException if there is an error leaving or when the address
* is not a multicast address.
* @throws SecurityException if a security manager exists and its
* {@code checkMulticast} method doesn't allow the operation.
* @throws IllegalArgumentException if mcastaddr is {@code null} or is a
* SocketAddress subclass not supported by this socket.
* @see SecurityManager#checkMulticast(InetAddress) * @see SecurityManager#checkMulticast(InetAddress)
* @since 1.4 * @see #joinGroup(SocketAddress, NetworkInterface)
* @since 1.4
*/ */
@Override
public void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf) public void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf)
throws IOException { throws IOException {
delegate().leaveGroup(mcastaddr, netIf); super.leaveGroup(mcastaddr, netIf);
} }
/** /**
* Set the multicast network interface used by methods * Set the multicast network interface used by methods
@ -455,10 +422,15 @@ public class MulticastSocket extends DatagramSocket {
* Specify the network interface for outgoing multicast datagrams * Specify the network interface for outgoing multicast datagrams
* sent on this socket. * sent on this socket.
* *
* @apiNote
* This method is equivalent to calling {@link #setOption(SocketOption, Object)
* setOption(StandardSocketOptions.IP_MULTICAST_IF, netIf)}.
*
* @param netIf the interface * @param netIf the interface
* @throws SocketException if there is an error in * @throws SocketException if there is an error in
* the underlying protocol, such as a TCP error. * the underlying protocol, such as a TCP error.
* @see #getNetworkInterface() * @see #getNetworkInterface()
* @see StandardSocketOptions#IP_MULTICAST_IF
* @since 1.4 * @since 1.4
*/ */
public void setNetworkInterface(NetworkInterface netIf) public void setNetworkInterface(NetworkInterface netIf)
@ -467,7 +439,13 @@ public class MulticastSocket extends DatagramSocket {
} }
/** /**
* Get the multicast network interface set. * Get the multicast network interface set for outgoing multicast
* datagrams sent from this socket.
*
* @apiNote
* When an interface is set, this method is equivalent
* to calling {@link #getOption(SocketOption)
* getOption(StandardSocketOptions.IP_MULTICAST_IF)}.
* *
* @throws SocketException if there is an error in * @throws SocketException if there is an error in
* the underlying protocol, such as a TCP error. * the underlying protocol, such as a TCP error.
@ -475,6 +453,7 @@ public class MulticastSocket extends DatagramSocket {
* NetworkInterface is returned when there is no interface set; it has * NetworkInterface is returned when there is no interface set; it has
* a single InetAddress to represent any local address. * a single InetAddress to represent any local address.
* @see #setNetworkInterface(NetworkInterface) * @see #setNetworkInterface(NetworkInterface)
* @see StandardSocketOptions#IP_MULTICAST_IF
* @since 1.4 * @since 1.4
*/ */
public NetworkInterface getNetworkInterface() throws SocketException { public NetworkInterface getNetworkInterface() throws SocketException {
@ -564,12 +543,12 @@ public class MulticastSocket extends DatagramSocket {
* *
* *
* @deprecated Use the following code or its equivalent instead: * @deprecated Use the following code or its equivalent instead:
* ...... * <pre>{@code ......
* int ttl = mcastSocket.getTimeToLive(); * int ttl = mcastSocket.getOption(StandardSocketOptions.IP_MULTICAST_TTL);
* mcastSocket.setTimeToLive(newttl); * mcastSocket.setOption(StandardSocketOptions.IP_MULTICAST_TTL, newttl);
* mcastSocket.send(p); * mcastSocket.send(p);
* mcastSocket.setTimeToLive(ttl); * mcastSocket.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
* ...... * ......}</pre>
* *
* @see DatagramSocket#send * @see DatagramSocket#send
* @see DatagramSocket#receive * @see DatagramSocket#receive

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2007, 2019, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -97,10 +97,9 @@ class DefaultDatagramSocketImplFactory
throw new SocketException("can't instantiate DatagramSocketImpl"); throw new SocketException("can't instantiate DatagramSocketImpl");
} }
} else { } else {
if (!preferIPv4Stack && !isMulticast) // Always use TwoStacksPlainDatagramSocketImpl since we need
return new DualStackPlainDatagramSocketImpl(exclusiveBind); // to support multicasting at DatagramSocket level
else return new TwoStacksPlainDatagramSocketImpl(exclusiveBind && !isMulticast, isMulticast);
return new TwoStacksPlainDatagramSocketImpl(exclusiveBind && !isMulticast, isMulticast);
} }
} }
} }

View file

@ -0,0 +1,176 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8237352
* @summary Verifies that the examples using DatagramSocket for
* sending and receiving multicast datagrams are functional.
* See "Multicasting with DatagramSocket" API note in
* DatagramSocket.java
*
* @library /test/lib
* @build jdk.test.lib.NetworkConfiguration
* jdk.test.lib.net.IPSupport
* @run main/othervm DatagramSocketExample
* @run main/othervm -Djava.net.preferIPv4Stack=true DatagramSocketExample
* @run main/othervm -Djdk.usePlainDatagramSocketImpl=true DatagramSocketExample
* @run main/othervm -Djdk.usePlainDatagramSocketImpl=true -Djava.net.preferIPv4Stack=true DatagramSocketExample
*/
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ProtocolFamily;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketOption;
import java.net.SocketTimeoutException;
import java.net.StandardSocketOptions;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import jdk.test.lib.NetworkConfiguration;
import jdk.test.lib.net.IPSupport;
import static java.net.StandardProtocolFamily.INET;
import static java.net.StandardProtocolFamily.INET6;
import static java.net.StandardSocketOptions.IP_MULTICAST_IF;
import static java.net.StandardSocketOptions.IP_MULTICAST_LOOP;
import static java.net.StandardSocketOptions.IP_MULTICAST_TTL;
import static java.net.StandardSocketOptions.SO_REUSEADDR;
public class DatagramSocketExample {
static final ProtocolFamily UNSPEC = () -> "UNSPEC";
public static void main(String[] args) throws IOException {
IPSupport.throwSkippedExceptionIfNonOperational();
// IPv4 and IPv6 interfaces that support multicasting
NetworkConfiguration config = NetworkConfiguration.probe();
List<NetworkInterface> ip4MulticastInterfaces = config.ip4MulticastInterfaces()
.collect(Collectors.toList());
List<NetworkInterface> ip6MulticastInterfaces = config.ip6MulticastInterfaces()
.collect(Collectors.toList());
// multicast groups used for the test
InetAddress ip4Group = InetAddress.getByName("225.4.5.6");
InetAddress ip6Group = InetAddress.getByName("ff02::a");
for (NetworkInterface ni : ip4MulticastInterfaces) {
test(INET, ip4Group, ni);
if (IPSupport.hasIPv6()) {
test(UNSPEC, ip4Group, ni);
test(INET6, ip4Group, ni);
}
}
for (NetworkInterface ni : ip6MulticastInterfaces) {
test(UNSPEC, ip6Group, ni);
test(INET6, ip6Group, ni);
}
}
static void test(ProtocolFamily family, InetAddress mcastaddr, NetworkInterface ni)
throws IOException
{
System.out.format("Test family=%s, multicast group=%s, interface=%s%n",
family.name(), mcastaddr, ni.getName());
// An instance of DatagramSocket can also be used to receive
// multicast datagram packets. A DatagramSocket that is created
// with the intent of receiving multicast datagrams should be
// created unbound. Before binding the socket, setReuseAddress(true)
// should be configured:
try (DatagramSocket socket = new DatagramSocket(null); // unbound
DatagramSocket sender = new DatagramSocket(new InetSocketAddress(0))) {
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(0));
// joinGroup
// InetAddress mcastaddr = InetAddress.getByName("228.5.6.7");
InetSocketAddress group = new InetSocketAddress(mcastaddr, 0);
// NetworkInterface netIf = NetworkInterface.getByName("en0");
NetworkInterface netIf = ni;
socket.joinGroup(group, netIf);
try {
byte[] rcvBytes = new byte[1024]; // up to 1024 bytes
DatagramPacket packet = new DatagramPacket(rcvBytes, rcvBytes.length);
// An instance of DatagramSocket can be used to send or receive
// multicast datagram packets. Before sending out datagram packets,
// the default outgoing interface for sending datagram packets
// should be configured first using setOption and
// StandardSocketOptions.IP_MULTICAST_IF:
// DatagramSocket sender = new DatagramSocket(new InetSocketAddress(0));
// NetworkInterface outgoingIf = NetworkInterface.getByName("en0");
NetworkInterface outgoingIf = ni;
sender.setOption(StandardSocketOptions.IP_MULTICAST_IF, outgoingIf);
// optionally configure multicast TTL
int ttl = 1; // a number betwen 0 and 255
sender.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// send a packet to a multicast group
byte[] msgBytes = "Hello".getBytes(StandardCharsets.UTF_8);
int port = socket.getLocalPort();
InetSocketAddress dest = new InetSocketAddress(mcastaddr, port);
DatagramPacket hi = new DatagramPacket(msgBytes, msgBytes.length, dest);
sender.send(hi);
socket.receive(packet);
byte[] bytes = Arrays.copyOfRange(packet.getData(), 0, packet.getLength());
assertTrue("Hello".equals(new String(bytes, StandardCharsets.UTF_8)));
} finally {
// eventually leave group
socket.leaveGroup(group, netIf);
}
}
}
static void assertTrue(boolean e) {
if (!e) throw new RuntimeException();
}
interface ThrowableRunnable {
void run() throws Exception;
}
static void assertThrows(java.lang.Class<?> exceptionClass, ThrowableRunnable task) {
try {
task.run();
throw new RuntimeException("Exception not thrown");
} catch (Exception e) {
if (!exceptionClass.isInstance(e)) {
throw new RuntimeException("expected: " + exceptionClass + ", actual: " + e);
}
}
}
}

View file

@ -0,0 +1,380 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8237352
* @summary Test DatagramSocket for sending and receiving multicast datagrams
* @library /test/lib
* @build jdk.test.lib.NetworkConfiguration
* jdk.test.lib.net.IPSupport
* @run main/othervm DatagramSocketMulticasting
* @run main/othervm -Djava.net.preferIPv4Stack=true DatagramSocketMulticasting
* @run main/othervm -Djdk.usePlainDatagramSocketImpl=true DatagramSocketMulticasting
* @run main/othervm -Djdk.usePlainDatagramSocketImpl=true -Djava.net.preferIPv4Stack=true DatagramSocketMulticasting
*/
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.ProtocolFamily;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketOption;
import java.net.SocketTimeoutException;
import java.nio.channels.DatagramChannel;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import jdk.test.lib.NetworkConfiguration;
import jdk.test.lib.net.IPSupport;
import static java.net.StandardProtocolFamily.INET;
import static java.net.StandardProtocolFamily.INET6;
import static java.net.StandardSocketOptions.IP_MULTICAST_IF;
import static java.net.StandardSocketOptions.IP_MULTICAST_LOOP;
import static java.net.StandardSocketOptions.IP_MULTICAST_TTL;
import static java.net.StandardSocketOptions.SO_REUSEADDR;
public class DatagramSocketMulticasting {
static final ProtocolFamily UNSPEC = () -> "UNSPEC";
public static void main(String[] args) throws IOException {
IPSupport.throwSkippedExceptionIfNonOperational();
// IPv4 and IPv6 interfaces that support multicasting
NetworkConfiguration config = NetworkConfiguration.probe();
List<NetworkInterface> ip4MulticastInterfaces = config.ip4MulticastInterfaces()
.collect(Collectors.toList());
List<NetworkInterface> ip6MulticastInterfaces = config.ip6MulticastInterfaces()
.collect(Collectors.toList());
// multicast groups used for the test
InetAddress ip4Group = InetAddress.getByName("225.4.5.6");
InetAddress ip6Group = InetAddress.getByName("ff02::a");
for (NetworkInterface ni : ip4MulticastInterfaces) {
test(INET, ip4Group, ni);
if (IPSupport.hasIPv6()) {
test(UNSPEC, ip4Group, ni);
test(INET6, ip4Group, ni);
}
}
for (NetworkInterface ni : ip6MulticastInterfaces) {
test(UNSPEC, ip6Group, ni);
test(INET6, ip6Group, ni);
}
}
static void test(ProtocolFamily family, InetAddress group, NetworkInterface ni)
throws IOException
{
System.out.format("Test family=%s, multicast group=%s, interface=%s%n",
family.name(), group, ni.getName());
// test 2-arg joinGroup/leaveGroup
try (DatagramSocket s = create()) {
testJoinGroup2(family, s, group, ni);
}
// test socket options
try (DatagramSocket s = create()) {
testNetworkInterface(s, ni);
testTimeToLive(s);
testLoopbackMode(s);
}
}
/**
* Creates a MulticastSocket. The SO_REUSEADDR socket option is set and it
* is bound to the wildcard address.
*/
static DatagramSocket create() throws IOException {
DatagramSocket ds = new DatagramSocket(null);
try {
ds.setOption(SO_REUSEADDR, true).bind(new InetSocketAddress(0));
} catch (IOException ioe) {
ds.close();
throw ioe;
}
return ds;
}
/**
* Test 2-arg joinGroup/leaveGroup
*/
static void testJoinGroup2(ProtocolFamily family,
DatagramSocket s,
InetAddress group,
NetworkInterface ni) throws IOException {
System.out.format("testJoinGroup2: local socket address: %s%n", s.getLocalSocketAddress());
// check network interface not set
assertTrue(s.getOption(IP_MULTICAST_IF) == null);
// join on default interface
s.joinGroup(new InetSocketAddress(group, 0), null);
// join should not change the outgoing multicast interface
assertTrue(s.getOption(IP_MULTICAST_IF) == null);
// already a member (exception not specified)
assertThrows(SocketException.class,
() -> s.joinGroup(new InetSocketAddress(group, 0), null));
// leave
s.leaveGroup(new InetSocketAddress(group, 0), null);
// not a member (exception not specified)
assertThrows(SocketException.class,
() -> s.leaveGroup(new InetSocketAddress(group, 0), null));
// join on specified interface
s.joinGroup(new InetSocketAddress(group, 0), ni);
// join should not change the outgoing multicast interface
assertTrue(s.getOption(IP_MULTICAST_IF) == null);
// already a member (exception not specified)
assertThrows(SocketException.class,
() -> s.joinGroup(new InetSocketAddress(group, 0), ni));
// leave
s.leaveGroup(new InetSocketAddress(group, 0), ni);
// not a member (exception not specified)
assertThrows(SocketException.class,
() -> s.leaveGroup(new InetSocketAddress(group, 0), ni));
// join/leave with outgoing multicast interface set and check that
// multicast datagrams can be sent and received
s.setOption(IP_MULTICAST_IF, ni);
s.joinGroup(new InetSocketAddress(group, 0), null);
testSendReceive(s, group);
s.leaveGroup(new InetSocketAddress(group, 0), null);
testSendNoReceive(s, group);
s.joinGroup(new InetSocketAddress(group, 0), ni);
testSendReceive(s, group);
s.leaveGroup(new InetSocketAddress(group, 0), ni);
testSendNoReceive(s, group);
// not a multicast address
var localHost = InetAddress.getLocalHost();
assertThrows(SocketException.class,
() -> s.joinGroup(new InetSocketAddress(localHost, 0), null));
assertThrows(SocketException.class,
() -> s.leaveGroup(new InetSocketAddress(localHost, 0), null));
assertThrows(SocketException.class,
() -> s.joinGroup(new InetSocketAddress(localHost, 0), ni));
assertThrows(SocketException.class,
() -> s.leaveGroup(new InetSocketAddress(localHost, 0), ni));
// not an InetSocketAddress
var customSocketAddress = new SocketAddress() { };
assertThrows(IllegalArgumentException.class,
() -> s.joinGroup(customSocketAddress, null));
assertThrows(IllegalArgumentException.class,
() -> s.leaveGroup(customSocketAddress, null));
assertThrows(IllegalArgumentException.class,
() -> s.joinGroup(customSocketAddress, ni));
assertThrows(IllegalArgumentException.class,
() -> s.leaveGroup(customSocketAddress, ni));
// IPv4 socket cannot join IPv6 group
if (family == INET && !IPSupport.hasIPv6()) {
System.out.println("Test IPv4 can't join IPv6");
InetAddress ip6Group = InetAddress.getByName("ff02::a");
assertThrows(IllegalArgumentException.class,
() -> s.joinGroup(new InetSocketAddress(ip6Group, 0), null));
assertThrows(IllegalArgumentException.class,
() -> s.joinGroup(new InetSocketAddress(ip6Group, 0), ni));
// not a member of IPv6 group (exception not specified)
assertThrows(SocketException.class,
() -> s.leaveGroup(new InetSocketAddress(ip6Group, 0), null));
assertThrows(SocketException.class,
() -> s.leaveGroup(new InetSocketAddress(ip6Group, 0), ni));
}
// null
assertThrows(IllegalArgumentException.class, () -> s.joinGroup(null, null));
assertThrows(IllegalArgumentException.class, () -> s.leaveGroup(null, null));
assertThrows(IllegalArgumentException.class, () -> s.joinGroup(null, ni));
assertThrows(IllegalArgumentException.class, () -> s.leaveGroup(null, ni));
}
/**
* Test getNetworkInterface/setNetworkInterface/getInterface/setInterface
* and IP_MULTICAST_IF socket option.
*/
static void testNetworkInterface(DatagramSocket s,
NetworkInterface ni) throws IOException {
// default value
assertTrue(s.getOption(IP_MULTICAST_IF) == null);
// setOption(IP_MULTICAST_IF)
s.setOption(IP_MULTICAST_IF, ni);
assertTrue(s.getOption(IP_MULTICAST_IF).equals(ni));
// bad values for IP_MULTICAST_IF
assertThrows(IllegalArgumentException.class,
() -> s.setOption(IP_MULTICAST_IF, null));
assertThrows(IllegalArgumentException.class,
() -> s.setOption((SocketOption) IP_MULTICAST_IF, "badValue"));
}
/**
* Test getTimeToLive/setTimeToLive/getTTL/getTTL and IP_MULTICAST_TTL socket
* option.
*/
static void testTimeToLive(DatagramSocket s) throws IOException {
// should be 1 by default
assertTrue(s.getOption(IP_MULTICAST_TTL) == 1);
// setOption(IP_MULTICAST_TTL)
for (int ttl = 0; ttl <= 2; ttl++) {
s.setOption(IP_MULTICAST_TTL, ttl);
assertTrue(s.getOption(IP_MULTICAST_TTL) == ttl);
}
// bad values for IP_MULTICAST_TTL
assertThrows(IllegalArgumentException.class,
() -> s.setOption(IP_MULTICAST_TTL, -1));
assertThrows(IllegalArgumentException.class,
() -> s.setOption(IP_MULTICAST_TTL, null));
assertThrows(IllegalArgumentException.class,
() -> s.setOption((SocketOption) IP_MULTICAST_TTL, "badValue"));
}
/**
* Test getLoopbackMode/setLoopbackMode and IP_MULTICAST_LOOP socket option.
*/
static void testLoopbackMode(DatagramSocket s) throws IOException {
// should be enabled by default
assertTrue(s.getOption(IP_MULTICAST_LOOP) == true);
// setLoopbackMode
// setOption(IP_MULTICAST_LOOP)
s.setOption(IP_MULTICAST_LOOP, false); // disable
assertTrue(s.getOption(IP_MULTICAST_LOOP) == false);
s.setOption(IP_MULTICAST_LOOP, true); // enable
assertTrue(s.getOption(IP_MULTICAST_LOOP) == true);
// bad values for IP_MULTICAST_LOOP
assertThrows(IllegalArgumentException.class,
() -> s.setOption(IP_MULTICAST_LOOP, null));
assertThrows(IllegalArgumentException.class,
() -> s.setOption((SocketOption) IP_MULTICAST_LOOP, "badValue"));
}
/**
* Send a datagram to the given multicast group and check that it is received.
*/
static void testSendReceive(DatagramSocket s, InetAddress group) throws IOException {
System.out.println("testSendReceive");
// outgoing multicast interface needs to be set
assertTrue(s.getOption(IP_MULTICAST_IF) != null);
SocketAddress target = new InetSocketAddress(group, s.getLocalPort());
byte[] message = "hello".getBytes("UTF-8");
// send message to multicast group
DatagramPacket p = new DatagramPacket(message, message.length);
p.setSocketAddress(target);
s.send(p);
// receive message
s.setSoTimeout(0);
p = new DatagramPacket(new byte[1024], 100);
s.receive(p);
assertTrue(p.getLength() == message.length);
assertTrue(p.getPort() == s.getLocalPort());
}
/**
* Send a datagram to the given multicast group and check that it is not
* received.
*/
static void testSendNoReceive(DatagramSocket s, InetAddress group) throws IOException {
System.out.println("testSendNoReceive");
// outgoing multicast interface needs to be set
assertTrue(s.getOption(IP_MULTICAST_IF) != null);
SocketAddress target = new InetSocketAddress(group, s.getLocalPort());
long nano = System.nanoTime();
String text = nano + ": hello";
byte[] message = text.getBytes("UTF-8");
// send datagram to multicast group
DatagramPacket p = new DatagramPacket(message, message.length);
p.setSocketAddress(target);
s.send(p);
// datagram should not be received
s.setSoTimeout(500);
p = new DatagramPacket(new byte[1024], 100);
while (true) {
try {
s.receive(p);
if (Arrays.equals(p.getData(), p.getOffset(), p.getLength(), message, 0, message.length)) {
throw new RuntimeException("message shouldn't have been received");
} else {
System.out.format("Received unexpected message from %s%n", p.getSocketAddress());
}
} catch (SocketTimeoutException expected) {
break;
}
}
}
static void assertTrue(boolean e) {
if (!e) throw new RuntimeException();
}
interface ThrowableRunnable {
void run() throws Exception;
}
static void assertThrows(Class<?> exceptionClass, ThrowableRunnable task) {
try {
task.run();
throw new RuntimeException("Exception not thrown");
} catch (Exception e) {
if (!exceptionClass.isInstance(e)) {
throw new RuntimeException("expected: " + exceptionClass + ", actual: " + e);
}
}
}
}