1 /*
  2  * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.net;
 27 
 28 import java.io.IOException;
 29 import java.nio.channels.DatagramChannel;
 30 import java.nio.channels.MulticastChannel;
 31 
 32 /**
 33  * A {@code MulticastSocket} is a datagram socket that is
 34  * convenient for sending and receiving IP multicast datagrams.
 35  * The {@code MulticastSocket} constructors create a socket
 36  * with appropriate socket options enabled that make
 37  * it suitable for receiving multicast datagrams.
 38  * The {@code MulticastSocket} class additionally defines
 39  * convenient setter and getter methods for socket options
 40  * that are commonly used by multicasting applications.
 41  * <P>
 42  * Joining one or more multicast groups makes it possible to
 43  * receive multicast datagrams sent to these groups.
 44  * <P>
 45  * An IPv4 multicast group is specified by a class D IP address
 46  * and by a standard UDP port number. Class D IP addresses
 47  * are in the range {@code 224.0.0.0} to {@code 239.255.255.255},
 48  * inclusive. The address 224.0.0.0 is reserved and should not be used.
 49  * <P>
 50  * One would join a multicast group by first creating a MulticastSocket
 51  * with the desired port, then invoking the
 52  * <CODE>joinGroup</CODE> method, specifying the group address and
 53  * the network interface through which multicast datagrams will be
 54  * received:
 55  * <PRE>{@code
 56  * // join a Multicast group and send the group salutations
 57  * ...
 58  * String msg = "Hello";
 59  * InetAddress mcastaddr = InetAddress.getByName("228.5.6.7");
 60  * InetSocketAddress group = new InetSocketAddress(mcastaddr, 6789);
 61  * NetworkInterface netIf = NetworkInterface.getByName("bge0");
 62  * MulticastSocket s = new MulticastSocket(6789);
 63  *
 64  * s.joinGroup(new InetSocketAddress(mcastaddr, 0), netIf);
 65  * byte[] msgBytes = msg.getBytes(StandardCharsets.UTF_8);
 66  * DatagramPacket hi = new DatagramPacket(msgBytes, msgBytes.length, group);
 67  * s.send(hi);
 68  * // get their responses!
 69  * byte[] buf = new byte[1000];
 70  * DatagramPacket recv = new DatagramPacket(buf, buf.length);
 71  * s.receive(recv);
 72  * ...
 73  * // OK, I'm done talking - leave the group...
 74  * s.leaveGroup(group, netIf);
 75  * }</PRE>
 76  *
 77  * When one sends a message to a multicast group, <B>all</B> subscribing
 78  * recipients to that host and port receive the message (within the
 79  * time-to-live range of the packet, see below). The socket needn't
 80  * be a member of the multicast group to send messages to it.
 81  * <P>
 82  * When a socket subscribes to a multicast group/port, it receives
 83  * datagrams sent by other hosts to the group/port, as do all other
 84  * members of the group and port.  A socket relinquishes membership
 85  * in a group by the leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf)
 86  * method.
 87  * <B>Multiple MulticastSockets</B> may subscribe to a multicast group
 88  * and port concurrently, and they will all receive group datagrams.
 89  *
 90  * <p> The {@code DatagramSocket} and {@code MulticastSocket}
 91  * classes define convenience methods to set and get several
 92  * socket options. Like {@code DatagramSocket} this class also
 93  * supports the {@link #setOption(SocketOption, Object) setOption}
 94  * and {@link #getOption(SocketOption) getOption} methods to set
 95  * and query socket options.
 96  * <a id="MulticastOptions"></a>The set of supported socket options
 97  * is defined in <a href="DatagramSocket.html#SocketOptions">{@code DatagramSocket}</a>.
 98  * Additional (implementation specific) options may also be supported.
 99  *
100  * @apiNote {@link DatagramSocket} may be used directly for
101  *          sending and receiving multicast datagrams.
102  *          {@link DatagramChannel} implements the {@link MulticastChannel} interface
103  *          and provides an alternative API for sending and receiving multicast datagrams.
104  *          The {@link MulticastChannel} API supports both {@linkplain
105  *          MulticastChannel#join(InetAddress, NetworkInterface) any-source} and
106  *          {@linkplain MulticastChannel#join(InetAddress, NetworkInterface, InetAddress)
107  *          source-specific} multicast. Consider using {@link DatagramChannel} for
108  *          multicasting.
109  *
110  * @author Pavani Diwanji
111  * @since 1.1
112  */
113 public class MulticastSocket extends DatagramSocket {
114 
115     @Override
116     final MulticastSocket delegate() {
117         return (MulticastSocket) super.delegate();
118     }
119 
120     /**
121      * Create a MulticastSocket that delegates to the given delegate if not null.
122      * @param delegate the delegate, can be null.
123      */
124     MulticastSocket(MulticastSocket delegate) {
125         super(delegate);
126     }
127 
128     /**
129      * Constructs a multicast socket and binds it to any available port
130      * on the local host machine.  The socket will be bound to the
131      * {@link InetAddress#isAnyLocalAddress wildcard} address.
132      *
133      * <p>
134      * If there is a security manager, its {@code checkListen} method is first
135      * called with 0 as its argument to ensure the operation is allowed. This
136      * could result in a SecurityException.
137      * <p>
138      * When the socket is created the
139      * {@link DatagramSocket#setReuseAddress(boolean)} method is called to
140      * enable the SO_REUSEADDR socket option.
141      *
142      * @throws    IOException if an I/O exception occurs while creating the
143      * MulticastSocket
144      * @throws    SecurityException if a security manager exists and its
145      * {@code checkListen} method doesn't allow the operation.
146      * @see SecurityManager#checkListen
147      * @see java.net.DatagramSocket#setReuseAddress(boolean)
148      * @see java.net.DatagramSocketImpl#setOption(SocketOption, Object)
149      */
150     public MulticastSocket() throws IOException {
151         this(new InetSocketAddress(0));
152     }
153 
154     /**
155      * Constructs a multicast socket and binds it to the specified port
156      * on the local host machine. The socket will be bound to the
157      * {@link InetAddress#isAnyLocalAddress wildcard} address.
158      *
159      * <p>If there is a security manager,
160      * its {@code checkListen} method is first called
161      * with the {@code port} argument
162      * as its argument to ensure the operation is allowed.
163      * This could result in a SecurityException.
164      * <p>
165      * When the socket is created the
166      * {@link DatagramSocket#setReuseAddress(boolean)} method is
167      * called to enable the SO_REUSEADDR socket option.
168      *
169      * @param     port port to use
170      * @throws    IOException if an I/O exception occurs
171      *            while creating the MulticastSocket
172      * @throws    SecurityException  if a security manager exists and its
173      *            {@code checkListen} method doesn't allow the operation.
174      * @throws    IllegalArgumentException  if port is  <a href="DatagramSocket.html#PortRange">
175      *            out of range.</a>
176      *
177      * @see       SecurityManager#checkListen
178      * @see       java.net.DatagramSocket#setReuseAddress(boolean)
179      */
180     public MulticastSocket(int port) throws IOException {
181         this(new InetSocketAddress(port));
182     }
183 
184     /**
185      * Creates a multicast socket, bound to the specified local
186      * socket address.
187      * <p>
188      * If the address is {@code null} an unbound socket will be created.
189      *
190      * <p>If there is a security manager,
191      * its {@code checkListen} method is first called
192      * with the SocketAddress port as its argument to ensure the operation is allowed.
193      * This could result in a SecurityException.
194      * <p>
195      * When the socket is created the
196      * {@link DatagramSocket#setReuseAddress(boolean)} method is
197      * called to enable the SO_REUSEADDR socket option.
198      *
199      * @param    bindaddr Socket address to bind to, or {@code null} for
200      *           an unbound socket.
201      * @throws   IOException if an I/O exception occurs
202      *           while creating the MulticastSocket
203      * @throws   SecurityException  if a security manager exists and its
204      *           {@code checkListen} method doesn't allow the operation.
205      * @see      SecurityManager#checkListen
206      * @see      java.net.DatagramSocket#setReuseAddress(boolean)
207      *
208      * @since 1.4
209      */
210     public MulticastSocket(SocketAddress bindaddr) throws IOException {
211         this(createDelegate(bindaddr, MulticastSocket.class));
212     }
213 
214     /**
215      * Set the default time-to-live for multicast packets sent out
216      * on this {@code MulticastSocket} in order to control the
217      * scope of the multicasts.
218      *
219      * <p>The ttl is an <b>unsigned</b> 8-bit quantity, and so <B>must</B> be
220      * in the range {@code 0 <= ttl <= 0xFF }.
221      *
222      * @param      ttl the time-to-live
223      * @throws     IOException if an I/O exception occurs
224      *             while setting the default time-to-live value
225      * @deprecated use the {@link #setTimeToLive(int)} method instead, which uses
226      *             <b>int</b> instead of <b>byte</b> as the type for ttl.
227      * @see #getTTL()
228      */
229     @Deprecated
230     public void setTTL(byte ttl) throws IOException {
231         delegate().setTTL(ttl);
232     }
233 
234     /**
235      * Set the default time-to-live for multicast packets sent out
236      * on this {@code MulticastSocket} in order to control the
237      * scope of the multicasts.
238      *
239      * <P> The ttl <B>must</B> be in the range {@code  0 <= ttl <=
240      * 255} or an {@code IllegalArgumentException} will be thrown.
241      * Multicast packets sent with a TTL of {@code 0} are not transmitted
242      * on the network but may be delivered locally.
243      *
244      * @apiNote
245      * This method is equivalent to calling {@link #setOption(SocketOption, Object)
246      * setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl)}.
247      *
248      * @param  ttl
249      *         the time-to-live
250      *
251      * @throws  IOException
252      *          if an I/O exception occurs while setting the
253      *          default time-to-live value
254      *
255      * @see #getTimeToLive()
256      * @see StandardSocketOptions#IP_MULTICAST_TTL
257      * @since 1.2
258      */
259     public void setTimeToLive(int ttl) throws IOException {
260         delegate().setTimeToLive(ttl);
261     }
262 
263     /**
264      * Get the default time-to-live for multicast packets sent out on
265      * the socket.
266      *
267      * @throws    IOException if an I/O exception occurs
268      * while getting the default time-to-live value
269      * @return the default time-to-live value
270      * @deprecated use the {@link #getTimeToLive()} method instead,
271      * which returns an <b>int</b> instead of a <b>byte</b>.
272      * @see #setTTL(byte)
273      */
274     @Deprecated
275     public byte getTTL() throws IOException {
276         return delegate().getTTL();
277     }
278 
279     /**
280      * Get the default time-to-live for multicast packets sent out on
281      * the socket.
282      *
283      * @apiNote
284      * This method is equivalent to calling {@link #getOption(SocketOption)
285      * getOption(StandardSocketOptions.IP_MULTICAST_TTL)}.
286      *
287      * @throws    IOException if an I/O exception occurs while
288      * getting the default time-to-live value
289      * @return the default time-to-live value
290      * @see #setTimeToLive(int)
291      * @see StandardSocketOptions#IP_MULTICAST_TTL
292      * @since 1.2
293      */
294     public int getTimeToLive() throws IOException {
295         return delegate().getTimeToLive();
296     }
297 
298     /**
299      * Joins a multicast group. Its behavior may be affected by
300      * {@code setInterface} or {@code setNetworkInterface}.
301      *
302      * <p>If there is a security manager, this method first
303      * calls its {@code checkMulticast} method with the
304      * {@code mcastaddr} argument as its argument.
305      *
306      * @apiNote
307      * Calling this method is equivalent to calling
308      * {@link #joinGroup(SocketAddress, NetworkInterface)
309      * joinGroup(new InetSocketAddress(mcastaddr, 0), null)}.
310      *
311      * @param      mcastaddr is the multicast address to join
312      * @throws     IOException if there is an error joining,
313      *             or when the address is not a multicast address,
314      *             or the platform does not support multicasting
315      * @throws     SecurityException if a security manager exists and its
316      *             {@code checkMulticast} method doesn't allow the join.
317      * @deprecated This method does not accept the network interface on
318      *             which to join the multicast group. Use
319      *             {@link #joinGroup(SocketAddress, NetworkInterface)} instead.
320      * @see        SecurityManager#checkMulticast(InetAddress)
321      */
322     @Deprecated(since="14")
323     public void joinGroup(InetAddress mcastaddr) throws IOException {
324         delegate().joinGroup(mcastaddr);
325     }
326 
327     /**
328      * Leave a multicast group. Its behavior may be affected by
329      * {@code setInterface} or {@code setNetworkInterface}.
330      *
331      * <p>If there is a security manager, this method first
332      * calls its {@code checkMulticast} method with the
333      * {@code mcastaddr} argument as its argument.
334      *
335      * @apiNote
336      * Calling this method is equivalent to calling
337      * {@link #leaveGroup(SocketAddress, NetworkInterface)
338      * leaveGroup(new InetSocketAddress(mcastaddr, 0), null)}.
339      *
340      * @param      mcastaddr is the multicast address to leave
341      * @throws     IOException if there is an error leaving
342      *             or when the address is not a multicast address.
343      * @throws     SecurityException if a security manager exists and its
344      *             {@code checkMulticast} method doesn't allow the operation.
345      * @deprecated This method does not accept the network interface on which
346      *             to leave the multicast group. Use
347      *             {@link #leaveGroup(SocketAddress, NetworkInterface)} instead.
348      * @see        SecurityManager#checkMulticast(InetAddress)
349      */
350     @Deprecated(since="14")
351     public void leaveGroup(InetAddress mcastaddr) throws IOException {
352         delegate().leaveGroup(mcastaddr);
353     }
354 
355     /**
356      * {@inheritDoc}
357      * @throws IOException {@inheritDoc}
358      * @throws SecurityException {@inheritDoc}
359      * @throws IllegalArgumentException {@inheritDoc}
360      * @see    SecurityManager#checkMulticast(InetAddress)
361      * @see    DatagramChannel#join(InetAddress, NetworkInterface)
362      * @see    StandardSocketOptions#IP_MULTICAST_IF
363      * @see    #setNetworkInterface(NetworkInterface)
364      * @see    #setInterface(InetAddress)
365      * @since 1.4
366      */
367     @Override
368     public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf)
369             throws IOException {
370         super.joinGroup(mcastaddr, netIf);
371     }
372 
373     /**
374      * {@inheritDoc}
375      * @apiNote {@inheritDoc}
376      * @throws IOException {@inheritDoc}
377      * @throws SecurityException {@inheritDoc}
378      * @throws IllegalArgumentException {@inheritDoc}
379      * @see    SecurityManager#checkMulticast(InetAddress)
380      * @see    #joinGroup(SocketAddress, NetworkInterface)
381      * @since 1.4
382      */
383     @Override
384     public void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf)
385             throws IOException {
386         super.leaveGroup(mcastaddr, netIf);
387     }
388 
389     /**
390      * Set the multicast network interface used by methods
391      * whose behavior would be affected by the value of the
392      * network interface. Useful for multihomed hosts.
393      *
394      * @param      inf the InetAddress
395      * @throws     SocketException if there is an error in
396      *             the underlying protocol, such as a TCP error.
397      * @deprecated The InetAddress may not uniquely identify
398      *             the network interface. Use
399      *             {@link #setNetworkInterface(NetworkInterface)} instead.
400      * @see        #getInterface()
401      */
402     @Deprecated(since="14")
403     public void setInterface(InetAddress inf) throws SocketException {
404         delegate().setInterface(inf);
405     }
406 
407     /**
408      * Retrieve the address of the network interface used for
409      * multicast packets.
410      *
411      * @return     An {@code InetAddress} representing the address
412      *             of the network interface used for multicast packets,
413      *             or if no interface has been set, an {@code InetAddress}
414      *             representing any local address.
415      * @throws     SocketException if there is an error in the
416      *             underlying protocol, such as a TCP error.
417      * @deprecated The network interface may not be uniquely identified by
418      *             the InetAddress returned.
419      *             Use {@link #getNetworkInterface()} instead.
420      * @see        #setInterface(java.net.InetAddress)
421      */
422     @Deprecated(since="14")
423     public InetAddress getInterface() throws SocketException {
424         return delegate().getInterface();
425     }
426 
427     /**
428      * Specify the network interface for outgoing multicast datagrams
429      * sent on this socket.
430      *
431      * @apiNote
432      * This method is equivalent to calling {@link #setOption(SocketOption, Object)
433      * setOption(StandardSocketOptions.IP_MULTICAST_IF, netIf)}.
434      *
435      * @param netIf the interface
436      * @throws    SocketException if there is an error in
437      * the underlying protocol, such as a TCP error.
438      * @see #getNetworkInterface()
439      * @see StandardSocketOptions#IP_MULTICAST_IF
440      * @since 1.4
441      */
442     public void setNetworkInterface(NetworkInterface netIf)
443         throws SocketException {
444         delegate().setNetworkInterface(netIf);
445     }
446 
447     /**
448      * Get the multicast network interface set for outgoing multicast
449      * datagrams sent from this socket.
450      *
451      * @apiNote
452      * When an interface is set, this method is equivalent
453      * to calling {@link #getOption(SocketOption)
454      * getOption(StandardSocketOptions.IP_MULTICAST_IF)}.
455      *
456      * @throws SocketException if there is an error in
457      *         the underlying protocol, such as a TCP error.
458      * @return The multicast {@code NetworkInterface} currently set. A placeholder
459      *         NetworkInterface is returned when there is no interface set; it has
460      *         a single InetAddress to represent any local address.
461      * @see    #setNetworkInterface(NetworkInterface)
462      * @see    StandardSocketOptions#IP_MULTICAST_IF
463      * @since  1.4
464      */
465     public NetworkInterface getNetworkInterface() throws SocketException {
466         return delegate().getNetworkInterface();
467     }
468 
469     /**
470      * Disable/Enable local loopback of multicast datagrams.
471      * The option is used by the platform's networking code as a hint
472      * for setting whether multicast data will be looped back to
473      * the local socket.
474      *
475      * <p>Because this option is a hint, applications that want to
476      * verify what loopback mode is set to should call
477      * {@link #getLoopbackMode()}
478      * @param      disable {@code true} to disable the LoopbackMode
479      * @throws     SocketException if an error occurs while setting the value
480      * @since      1.4
481      * @deprecated Use {@link #setOption(SocketOption, Object)} with
482      *             {@link java.net.StandardSocketOptions#IP_MULTICAST_LOOP}
483      *             instead. The loopback mode is enabled by default,
484      *             {@code MulticastSocket.setOption(StandardSocketOptions.IP_MULTICAST_LOOP, false)}
485      *             disables it.
486      * @see        #getLoopbackMode
487      */
488     @Deprecated(since="14")
489     public void setLoopbackMode(boolean disable) throws SocketException {
490         delegate().setLoopbackMode(disable);
491     }
492 
493     /**
494      * Get the setting for local loopback of multicast datagrams.
495      *
496      * @throws     SocketException if an error occurs while getting the value
497      * @return     true if the LoopbackMode has been disabled
498      * @since      1.4
499      * @deprecated Use {@link #getOption(SocketOption)} with
500      *             {@link java.net.StandardSocketOptions#IP_MULTICAST_LOOP}
501      *             instead.
502      * @see        #setLoopbackMode
503      */
504     @Deprecated(since="14")
505     public boolean getLoopbackMode() throws SocketException {
506         return delegate().getLoopbackMode();
507     }
508 
509     /**
510      * Sends a datagram packet to the destination, with a TTL (time-to-live)
511      * other than the default for the socket.  This method
512      * need only be used in instances where a particular TTL is desired;
513      * otherwise it is preferable to set a TTL once on the socket, and
514      * use that default TTL for all packets.  This method does <B>not
515      * </B> alter the default TTL for the socket. Its behavior may be
516      * affected by {@code setInterface}.
517      *
518      * <p>If there is a security manager, this method first performs some
519      * security checks. First, if {@code p.getAddress().isMulticastAddress()}
520      * is true, this method calls the
521      * security manager's {@code checkMulticast} method
522      * with {@code p.getAddress()} and {@code ttl} as its arguments.
523      * If the evaluation of that expression is false,
524      * this method instead calls the security manager's
525      * {@code checkConnect} method with arguments
526      * {@code p.getAddress().getHostAddress()} and
527      * {@code p.getPort()}. Each call to a security manager method
528      * could result in a SecurityException if the operation is not allowed.
529      *
530      * @param p is the packet to be sent. The packet should contain
531      * the destination multicast ip address and the data to be sent.
532      * One does not need to be the member of the group to send
533      * packets to a destination multicast address.
534      * @param ttl optional time to live for multicast packet.
535      * default ttl is 1.
536      *
537      * @throws     IOException is raised if an error occurs i.e
538      *             error while setting ttl.
539      * @throws     SecurityException  if a security manager exists and its
540      *             {@code checkMulticast} or {@code checkConnect}
541      *             method doesn't allow the send.
542      * @throws     PortUnreachableException may be thrown if the socket is connected
543      *             to a currently unreachable destination. Note, there is no
544      *             guarantee that the exception will be thrown.
545      * @throws     IllegalArgumentException if the socket is connected,
546      *             and connected address and packet address differ, or
547      *             if the socket is not connected and the packet address
548      *             is not set or if its port is out of range.
549      *
550      *
551      * @deprecated Use the following code or its equivalent instead:
552      *  <pre>{@code   ......
553      *  int ttl = mcastSocket.getOption(StandardSocketOptions.IP_MULTICAST_TTL);
554      *  mcastSocket.setOption(StandardSocketOptions.IP_MULTICAST_TTL, newttl);
555      *  mcastSocket.send(p);
556      *  mcastSocket.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
557      *  ......}</pre>
558      *
559      * @see DatagramSocket#send
560      * @see DatagramSocket#receive
561      * @see SecurityManager#checkMulticast(java.net.InetAddress, byte)
562      * @see SecurityManager#checkConnect
563      */
564     @Deprecated
565     public void send(DatagramPacket p, byte ttl)
566         throws IOException {
567         delegate().send(p, ttl);
568     }
569 }