1 /*
   2  * Copyright (c) 2000, 2013, 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.nio.channels;
  27 
  28 import java.io.IOException;
  29 import java.net.ProtocolFamily;
  30 import java.net.DatagramSocket;
  31 import java.net.SocketOption;
  32 import java.net.SocketAddress;
  33 import java.nio.ByteBuffer;
  34 import java.nio.channels.spi.AbstractSelectableChannel;
  35 import java.nio.channels.spi.SelectorProvider;
  36 
  37 /**
  38  * A selectable channel for datagram-oriented sockets.
  39  *
  40  * <p> A datagram channel is created by invoking one of the {@link #open open} methods
  41  * of this class. It is not possible to create a channel for an arbitrary,
  42  * pre-existing datagram socket. A newly-created datagram channel is open but not
  43  * connected. A datagram channel need not be connected in order for the {@link #send
  44  * send} and {@link #receive receive} methods to be used.  A datagram channel may be
  45  * connected, by invoking its {@link #connect connect} method, in order to
  46  * avoid the overhead of the security checks are otherwise performed as part of
  47  * every send and receive operation.  A datagram channel must be connected in
  48  * order to use the {@link #read(java.nio.ByteBuffer) read} and {@link
  49  * #write(java.nio.ByteBuffer) write} methods, since those methods do not
  50  * accept or return socket addresses.
  51  *
  52  * <p> Once connected, a datagram channel remains connected until it is
  53  * disconnected or closed.  Whether or not a datagram channel is connected may
  54  * be determined by invoking its {@link #isConnected isConnected} method.
  55  *
  56  * <p> Socket options are configured using the {@link #setOption(SocketOption,Object)
  57  * setOption} method. A datagram channel to an Internet Protocol socket supports
  58  * the following options:
  59  * <blockquote>
  60  * <table class="striped">
  61  * <caption style="display:none">Socket options</caption>
  62  * <thead>
  63  *   <tr>
  64  *     <th>Option Name</th>
  65  *     <th>Description</th>
  66  *   </tr>
  67  * </thead>
  68  * <tbody>
  69  *   <tr>
  70  *     <td> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </td>
  71  *     <td> The size of the socket send buffer </td>
  72  *   </tr>
  73  *   <tr>
  74  *     <td> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </td>
  75  *     <td> The size of the socket receive buffer </td>
  76  *   </tr>
  77  *   <tr>
  78  *     <td> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </td>
  79  *     <td> Re-use address </td>
  80  *   </tr>
  81  *   <tr>
  82  *     <td> {@link java.net.StandardSocketOptions#SO_BROADCAST SO_BROADCAST} </td>
  83  *     <td> Allow transmission of broadcast datagrams </td>
  84  *   </tr>
  85  *   <tr>
  86  *     <td> {@link java.net.StandardSocketOptions#IP_TOS IP_TOS} </td>
  87  *     <td> The Type of Service (ToS) octet in the Internet Protocol (IP) header </td>
  88  *   </tr>
  89  *   <tr>
  90  *     <td> {@link java.net.StandardSocketOptions#IP_MULTICAST_IF IP_MULTICAST_IF} </td>
  91  *     <td> The network interface for Internet Protocol (IP) multicast datagrams </td>
  92  *   </tr>
  93  *   <tr>
  94  *     <td> {@link java.net.StandardSocketOptions#IP_MULTICAST_TTL
  95  *       IP_MULTICAST_TTL} </td>
  96  *     <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast
  97  *       datagrams </td>
  98  *   </tr>
  99  *   <tr>
 100  *     <td> {@link java.net.StandardSocketOptions#IP_MULTICAST_LOOP
 101  *       IP_MULTICAST_LOOP} </td>
 102  *     <td> Loopback for Internet Protocol (IP) multicast datagrams </td>
 103  *   </tr>
 104  * </tbody>
 105  * </table>
 106  * </blockquote>
 107  * Additional (implementation specific) options may also be supported.
 108  *
 109  * <p> Datagram channels are safe for use by multiple concurrent threads.  They
 110  * support concurrent reading and writing, though at most one thread may be
 111  * reading and at most one thread may be writing at any given time.  </p>
 112  *
 113  * @author Mark Reinhold
 114  * @author JSR-51 Expert Group
 115  * @since 1.4
 116  */
 117 
 118 public abstract class DatagramChannel
 119     extends AbstractSelectableChannel
 120     implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, MulticastChannel
 121 {
 122 
 123     /**
 124      * Initializes a new instance of this class.
 125      *
 126      * @param  provider
 127      *         The provider that created this channel
 128      */
 129     protected DatagramChannel(SelectorProvider provider) {
 130         super(provider);
 131     }
 132 
 133     /**
 134      * Opens a datagram channel.
 135      *
 136      * <p> The new channel is created by invoking the {@link
 137      * java.nio.channels.spi.SelectorProvider#openDatagramChannel()
 138      * openDatagramChannel} method of the system-wide default {@link
 139      * java.nio.channels.spi.SelectorProvider} object.  The channel will not be
 140      * connected.
 141      *
 142      * <p> The {@link ProtocolFamily ProtocolFamily} of the channel's socket
 143      * is platform (and possibly configuration) dependent and therefore unspecified.
 144      * The {@link #open(ProtocolFamily) open} allows the protocol family to be
 145      * selected when opening a datagram channel, and should be used to open
 146      * datagram channels that are intended for Internet Protocol multicasting.
 147      *
 148      * @return  A new datagram channel
 149      *
 150      * @throws  IOException
 151      *          If an I/O error occurs
 152      */
 153     public static DatagramChannel open() throws IOException {
 154         return SelectorProvider.provider().openDatagramChannel();
 155     }
 156 
 157     /**
 158      * Opens a datagram channel.
 159      *
 160      * <p> The {@code family} parameter is used to specify the {@link
 161      * ProtocolFamily}. If the datagram channel is to be used for IP multicasting
 162      * then this should correspond to the address type of the multicast groups
 163      * that this channel will join.
 164      *
 165      * <p> The new channel is created by invoking the {@link
 166      * java.nio.channels.spi.SelectorProvider#openDatagramChannel(ProtocolFamily)
 167      * openDatagramChannel} method of the system-wide default {@link
 168      * java.nio.channels.spi.SelectorProvider} object.  The channel will not be
 169      * connected.
 170      *
 171      * @param   family
 172      *          The protocol family
 173      *
 174      * @return  A new datagram channel
 175      *
 176      * @throws  UnsupportedOperationException
 177      *          If the specified protocol family is not supported. For example,
 178      *          suppose the parameter is specified as {@link
 179      *          java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6}
 180      *          but IPv6 is not enabled on the platform.
 181      * @throws  IOException
 182      *          If an I/O error occurs
 183      *
 184      * @since   1.7
 185      */
 186     public static DatagramChannel open(ProtocolFamily family) throws IOException {
 187         return SelectorProvider.provider().openDatagramChannel(family);
 188     }
 189 
 190     /**
 191      * Returns an operation set identifying this channel's supported
 192      * operations.
 193      *
 194      * <p> Datagram channels support reading and writing, so this method
 195      * returns {@code (}{@link SelectionKey#OP_READ} {@code |}&nbsp;{@link
 196      * SelectionKey#OP_WRITE}{@code )}.
 197      *
 198      * @return  The valid-operation set
 199      */
 200     public final int validOps() {
 201         return (SelectionKey.OP_READ
 202                 | SelectionKey.OP_WRITE);
 203     }
 204 
 205 
 206     // -- Socket-specific operations --
 207 
 208     /**
 209      * @throws  AlreadyBoundException               {@inheritDoc}
 210      * @throws  UnsupportedAddressTypeException     {@inheritDoc}
 211      * @throws  ClosedChannelException              {@inheritDoc}
 212      * @throws  IOException                         {@inheritDoc}
 213      * @throws  SecurityException
 214      *          If a security manager has been installed and its {@link
 215      *          SecurityManager#checkListen checkListen} method denies the
 216      *          operation
 217      *
 218      * @since 1.7
 219      */
 220     public abstract DatagramChannel bind(SocketAddress local)
 221         throws IOException;
 222 
 223     /**
 224      * @throws  UnsupportedOperationException           {@inheritDoc}
 225      * @throws  IllegalArgumentException                {@inheritDoc}
 226      * @throws  ClosedChannelException                  {@inheritDoc}
 227      * @throws  IOException                             {@inheritDoc}
 228      *
 229      * @since 1.7
 230      */
 231     public abstract <T> DatagramChannel setOption(SocketOption<T> name, T value)
 232         throws IOException;
 233 
 234     /**
 235      * Retrieves a datagram socket associated with this channel.
 236      *
 237      * <p> The returned object will not declare any public methods that are not
 238      * declared in the {@link java.net.DatagramSocket} class.  </p>
 239      *
 240      * @return  A datagram socket associated with this channel
 241      */
 242     public abstract DatagramSocket socket();
 243 
 244     /**
 245      * Tells whether or not this channel's socket is connected.
 246      *
 247      * @return  {@code true} if, and only if, this channel's socket
 248      *          is {@link #isOpen open} and connected
 249      */
 250     public abstract boolean isConnected();
 251 
 252     /**
 253      * Connects this channel's socket.
 254      *
 255      * <p> The channel's socket is configured so that it only receives
 256      * datagrams from, and sends datagrams to, the given remote <i>peer</i>
 257      * address.  Once connected, datagrams may not be received from or sent to
 258      * any other address.  A datagram socket remains connected until it is
 259      * explicitly disconnected or until it is closed.
 260      *
 261      * <p> This method performs exactly the same security checks as the {@link
 262      * java.net.DatagramSocket#connect connect} method of the {@link
 263      * java.net.DatagramSocket} class.  That is, if a security manager has been
 264      * installed then this method verifies that its {@link
 265      * java.lang.SecurityManager#checkAccept checkAccept} and {@link
 266      * java.lang.SecurityManager#checkConnect checkConnect} methods permit
 267      * datagrams to be received from and sent to, respectively, the given
 268      * remote address.
 269      *
 270      * <p> This method may be invoked at any time.  It will not have any effect
 271      * on read or write operations that are already in progress at the moment
 272      * that it is invoked. If this channel's socket is not bound then this method
 273      * will first cause the socket to be bound to an address that is assigned
 274      * automatically, as if invoking the {@link #bind bind} method with a
 275      * parameter of {@code null}. </p>
 276      *
 277      * @param  remote
 278      *         The remote address to which this channel is to be connected
 279      *
 280      * @return  This datagram channel
 281      *
 282      * @throws  ClosedChannelException
 283      *          If this channel is closed
 284      *
 285      * @throws  AsynchronousCloseException
 286      *          If another thread closes this channel
 287      *          while the connect operation is in progress
 288      *
 289      * @throws  ClosedByInterruptException
 290      *          If another thread interrupts the current thread
 291      *          while the connect operation is in progress, thereby
 292      *          closing the channel and setting the current thread's
 293      *          interrupt status
 294      *
 295      * @throws  SecurityException
 296      *          If a security manager has been installed
 297      *          and it does not permit access to the given remote address
 298      *
 299      * @throws  IOException
 300      *          If some other I/O error occurs
 301      */
 302     public abstract DatagramChannel connect(SocketAddress remote)
 303         throws IOException;
 304 
 305     /**
 306      * Disconnects this channel's socket.
 307      *
 308      * <p> The channel's socket is configured so that it can receive datagrams
 309      * from, and sends datagrams to, any remote address so long as the security
 310      * manager, if installed, permits it.
 311      *
 312      * <p> This method may be invoked at any time.  It will not have any effect
 313      * on read or write operations that are already in progress at the moment
 314      * that it is invoked.
 315      *
 316      * <p> If this channel's socket is not connected, or if the channel is
 317      * closed, then invoking this method has no effect.  </p>
 318      *
 319      * @return  This datagram channel
 320      *
 321      * @throws  IOException
 322      *          If some other I/O error occurs
 323      */
 324     public abstract DatagramChannel disconnect() throws IOException;
 325 
 326     /**
 327      * Returns the remote address to which this channel's socket is connected.
 328      *
 329      * @return  The remote address; {@code null} if the channel's socket is not
 330      *          connected
 331      *
 332      * @throws  ClosedChannelException
 333      *          If the channel is closed
 334      * @throws  IOException
 335      *          If an I/O error occurs
 336      *
 337      * @since 1.7
 338      */
 339     public abstract SocketAddress getRemoteAddress() throws IOException;
 340 
 341     /**
 342      * Receives a datagram via this channel.
 343      *
 344      * <p> If a datagram is immediately available, or if this channel is in
 345      * blocking mode and one eventually becomes available, then the datagram is
 346      * copied into the given byte buffer and its source address is returned.
 347      * If this channel is in non-blocking mode and a datagram is not
 348      * immediately available then this method immediately returns
 349      * {@code null}.
 350      *
 351      * <p> The datagram is transferred into the given byte buffer starting at
 352      * its current position, as if by a regular {@link
 353      * ReadableByteChannel#read(java.nio.ByteBuffer) read} operation.  If there
 354      * are fewer bytes remaining in the buffer than are required to hold the
 355      * datagram then the remainder of the datagram is silently discarded.
 356      *
 357      * <p> This method performs exactly the same security checks as the {@link
 358      * java.net.DatagramSocket#receive receive} method of the {@link
 359      * java.net.DatagramSocket} class.  That is, if the socket is not connected
 360      * to a specific remote address and a security manager has been installed
 361      * then for each datagram received this method verifies that the source's
 362      * address and port number are permitted by the security manager's {@link
 363      * java.lang.SecurityManager#checkAccept checkAccept} method.  The overhead
 364      * of this security check can be avoided by first connecting the socket via
 365      * the {@link #connect connect} method.
 366      *
 367      * <p> This method may be invoked at any time.  If another thread has
 368      * already initiated a read operation upon this channel, however, then an
 369      * invocation of this method will block until the first operation is
 370      * complete. If this channel's socket is not bound then this method will
 371      * first cause the socket to be bound to an address that is assigned
 372      * automatically, as if invoking the {@link #bind bind} method with a
 373      * parameter of {@code null}. </p>
 374      *
 375      * @param  dst
 376      *         The buffer into which the datagram is to be transferred
 377      *
 378      * @return  The datagram's source address,
 379      *          or {@code null} if this channel is in non-blocking mode
 380      *          and no datagram was immediately available
 381      *
 382      * @throws  ClosedChannelException
 383      *          If this channel is closed
 384      *
 385      * @throws  AsynchronousCloseException
 386      *          If another thread closes this channel
 387      *          while the read operation is in progress
 388      *
 389      * @throws  ClosedByInterruptException
 390      *          If another thread interrupts the current thread
 391      *          while the read operation is in progress, thereby
 392      *          closing the channel and setting the current thread's
 393      *          interrupt status
 394      *
 395      * @throws  SecurityException
 396      *          If a security manager has been installed
 397      *          and it does not permit datagrams to be accepted
 398      *          from the datagram's sender
 399      *
 400      * @throws  IOException
 401      *          If some other I/O error occurs
 402      */
 403     public abstract SocketAddress receive(ByteBuffer dst) throws IOException;
 404 
 405     /**
 406      * Sends a datagram via this channel.
 407      *
 408      * <p> If this channel is in non-blocking mode and there is sufficient room
 409      * in the underlying output buffer, or if this channel is in blocking mode
 410      * and sufficient room becomes available, then the remaining bytes in the
 411      * given buffer are transmitted as a single datagram to the given target
 412      * address.
 413      *
 414      * <p> The datagram is transferred from the byte buffer as if by a regular
 415      * {@link WritableByteChannel#write(java.nio.ByteBuffer) write} operation.
 416      *
 417      * <p> This method performs exactly the same security checks as the {@link
 418      * java.net.DatagramSocket#send send} method of the {@link
 419      * java.net.DatagramSocket} class.  That is, if the socket is not connected
 420      * to a specific remote address and a security manager has been installed
 421      * then for each datagram sent this method verifies that the target address
 422      * and port number are permitted by the security manager's {@link
 423      * java.lang.SecurityManager#checkConnect checkConnect} method.  The
 424      * overhead of this security check can be avoided by first connecting the
 425      * socket via the {@link #connect connect} method.
 426      *
 427      * <p> This method may be invoked at any time.  If another thread has
 428      * already initiated a write operation upon this channel, however, then an
 429      * invocation of this method will block until the first operation is
 430      * complete. If this channel's socket is not bound then this method will
 431      * first cause the socket to be bound to an address that is assigned
 432      * automatically, as if by invoking the {@link #bind bind} method with a
 433      * parameter of {@code null}. </p>
 434      *
 435      * @param  src
 436      *         The buffer containing the datagram to be sent
 437      *
 438      * @param  target
 439      *         The address to which the datagram is to be sent
 440      *
 441      * @return   The number of bytes sent, which will be either the number
 442      *           of bytes that were remaining in the source buffer when this
 443      *           method was invoked or, if this channel is non-blocking, may be
 444      *           zero if there was insufficient room for the datagram in the
 445      *           underlying output buffer
 446      *
 447      * @throws  ClosedChannelException
 448      *          If this channel is closed
 449      *
 450      * @throws  AsynchronousCloseException
 451      *          If another thread closes this channel
 452      *          while the read operation is in progress
 453      *
 454      * @throws  ClosedByInterruptException
 455      *          If another thread interrupts the current thread
 456      *          while the read operation is in progress, thereby
 457      *          closing the channel and setting the current thread's
 458      *          interrupt status
 459      *
 460      * @throws  SecurityException
 461      *          If a security manager has been installed
 462      *          and it does not permit datagrams to be sent
 463      *          to the given address
 464      *
 465      * @throws  IOException
 466      *          If some other I/O error occurs
 467      */
 468     public abstract int send(ByteBuffer src, SocketAddress target)
 469         throws IOException;
 470 
 471 
 472     // -- ByteChannel operations --
 473 
 474     /**
 475      * Reads a datagram from this channel.
 476      *
 477      * <p> This method may only be invoked if this channel's socket is
 478      * connected, and it only accepts datagrams from the socket's peer.  If
 479      * there are more bytes in the datagram than remain in the given buffer
 480      * then the remainder of the datagram is silently discarded.  Otherwise
 481      * this method behaves exactly as specified in the {@link
 482      * ReadableByteChannel} interface.  </p>
 483      *
 484      * @throws  NotYetConnectedException
 485      *          If this channel's socket is not connected
 486      */
 487     public abstract int read(ByteBuffer dst) throws IOException;
 488 
 489     /**
 490      * Reads a datagram from this channel.
 491      *
 492      * <p> This method may only be invoked if this channel's socket is
 493      * connected, and it only accepts datagrams from the socket's peer.  If
 494      * there are more bytes in the datagram than remain in the given buffers
 495      * then the remainder of the datagram is silently discarded.  Otherwise
 496      * this method behaves exactly as specified in the {@link
 497      * ScatteringByteChannel} interface.  </p>
 498      *
 499      * @throws  NotYetConnectedException
 500      *          If this channel's socket is not connected
 501      */
 502     public abstract long read(ByteBuffer[] dsts, int offset, int length)
 503         throws IOException;
 504 
 505     /**
 506      * Reads a datagram from this channel.
 507      *
 508      * <p> This method may only be invoked if this channel's socket is
 509      * connected, and it only accepts datagrams from the socket's peer.  If
 510      * there are more bytes in the datagram than remain in the given buffers
 511      * then the remainder of the datagram is silently discarded.  Otherwise
 512      * this method behaves exactly as specified in the {@link
 513      * ScatteringByteChannel} interface.  </p>
 514      *
 515      * @throws  NotYetConnectedException
 516      *          If this channel's socket is not connected
 517      */
 518     public final long read(ByteBuffer[] dsts) throws IOException {
 519         return read(dsts, 0, dsts.length);
 520     }
 521 
 522     /**
 523      * Writes a datagram to this channel.
 524      *
 525      * <p> This method may only be invoked if this channel's socket is
 526      * connected, in which case it sends datagrams directly to the socket's
 527      * peer.  Otherwise it behaves exactly as specified in the {@link
 528      * WritableByteChannel} interface.  </p>
 529      *
 530      * @throws  NotYetConnectedException
 531      *          If this channel's socket is not connected
 532      */
 533     public abstract int write(ByteBuffer src) throws IOException;
 534 
 535     /**
 536      * Writes a datagram to this channel.
 537      *
 538      * <p> This method may only be invoked if this channel's socket is
 539      * connected, in which case it sends datagrams directly to the socket's
 540      * peer.  Otherwise it behaves exactly as specified in the {@link
 541      * GatheringByteChannel} interface.  </p>
 542      *
 543      * @return   The number of bytes sent, which will be either the number
 544      *           of bytes that were remaining in the source buffer when this
 545      *           method was invoked or, if this channel is non-blocking, may be
 546      *           zero if there was insufficient room for the datagram in the
 547      *           underlying output buffer
 548      *
 549      * @throws  NotYetConnectedException
 550      *          If this channel's socket is not connected
 551      */
 552     public abstract long write(ByteBuffer[] srcs, int offset, int length)
 553         throws IOException;
 554 
 555     /**
 556      * Writes a datagram to this channel.
 557      *
 558      * <p> This method may only be invoked if this channel's socket is
 559      * connected, in which case it sends datagrams directly to the socket's
 560      * peer.  Otherwise it behaves exactly as specified in the {@link
 561      * GatheringByteChannel} interface.  </p>
 562      *
 563      * @return   The number of bytes sent, which will be either the number
 564      *           of bytes that were remaining in the source buffer when this
 565      *           method was invoked or, if this channel is non-blocking, may be
 566      *           zero if there was insufficient room for the datagram in the
 567      *           underlying output buffer
 568      *
 569      * @throws  NotYetConnectedException
 570      *          If this channel's socket is not connected
 571      */
 572     public final long write(ByteBuffer[] srcs) throws IOException {
 573         return write(srcs, 0, srcs.length);
 574     }
 575 
 576     /**
 577      * {@inheritDoc}
 578      * <p>
 579      * If there is a security manager set, its {@code checkConnect} method is
 580      * called with the local address and {@code -1} as its arguments to see
 581      * if the operation is allowed. If the operation is not allowed,
 582      * a {@code SocketAddress} representing the
 583      * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the
 584      * local port of the channel's socket is returned.
 585      *
 586      * @return  The {@code SocketAddress} that the socket is bound to, or the
 587      *          {@code SocketAddress} representing the loopback address if
 588      *          denied by the security manager, or {@code null} if the
 589      *          channel's socket is not bound
 590      *
 591      * @throws  ClosedChannelException     {@inheritDoc}
 592      * @throws  IOException                {@inheritDoc}
 593      */
 594     @Override
 595     public abstract SocketAddress getLocalAddress() throws IOException;
 596 
 597 }