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