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 * @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6"> 155 * java.net.preferIPv4Stack</a> system property 156 */ 157 public static DatagramChannel open() throws IOException { 158 return SelectorProvider.provider().openDatagramChannel(); 159 } 160 161 /** 162 * Opens a datagram channel. 163 * 164 * <p> The {@code family} parameter is used to specify the {@link 165 * ProtocolFamily}. If the datagram channel is to be used for IP multicasting 166 * then this should correspond to the address type of the multicast groups 167 * that this channel will join. 168 * 169 * <p> The new channel is created by invoking the {@link 170 * java.nio.channels.spi.SelectorProvider#openDatagramChannel(ProtocolFamily) 171 * openDatagramChannel} method of the system-wide default {@link 172 * java.nio.channels.spi.SelectorProvider} object. The channel will not be 173 * connected. 174 * 175 * @apiNote <a href="package-summary.html#unixdomain">Unix domain</a> sockets 176 * are not supported by DatagramChannel. 177 * 178 * @param family 179 * The protocol family 180 * 181 * @return A new datagram channel 182 * 183 * @throws UnsupportedOperationException 184 * If the specified protocol family is not supported. For example, 185 * suppose the parameter is specified as {@link 186 * java.net.StandardProtocolFamily#INET6 StandardProtocolFamily.INET6} 187 * but IPv6 is not enabled on the platform. 188 * @throws IOException 189 * If an I/O error occurs 190 * 191 * @see <a href="../../net/doc-files/net-properties.html#Ipv4IPv6"> 192 * java.net.preferIPv4Stack</a> system property 193 * 194 * @since 1.7 195 */ 196 public static DatagramChannel open(ProtocolFamily family) throws IOException { 197 return SelectorProvider.provider().openDatagramChannel(requireNonNull(family)); 198 } 199 200 /** 201 * Returns an operation set identifying this channel's supported 202 * operations. 203 * 204 * <p> Datagram channels support reading and writing, so this method 205 * returns {@code (}{@link SelectionKey#OP_READ} {@code |} {@link 206 * SelectionKey#OP_WRITE}{@code )}. 207 * 208 * @return The valid-operation set 209 */ 210 public final int validOps() { 211 return (SelectionKey.OP_READ 212 | SelectionKey.OP_WRITE); 213 } 214 215 216 // -- Socket-specific operations -- 217 218 /** 219 * @throws AlreadyBoundException {@inheritDoc} 220 * @throws UnsupportedAddressTypeException {@inheritDoc} 221 * @throws ClosedChannelException {@inheritDoc} 222 * @throws IOException {@inheritDoc} 223 * @throws SecurityException 224 * If a security manager has been installed and its {@link 225 * SecurityManager#checkListen checkListen} method denies the 226 * operation 227 * 228 * @since 1.7 229 */ 230 public abstract DatagramChannel bind(SocketAddress local) 231 throws IOException; 232 233 /** 234 * @throws UnsupportedOperationException {@inheritDoc} 235 * @throws IllegalArgumentException {@inheritDoc} 236 * @throws ClosedChannelException {@inheritDoc} 237 * @throws IOException {@inheritDoc} 238 * 239 * @since 1.7 240 */ 241 public abstract <T> DatagramChannel setOption(SocketOption<T> name, T value) 242 throws IOException; 243 244 /** 245 * Retrieves a datagram socket associated with this channel. 246 * 247 * @return A datagram socket associated with this channel 248 */ 249 public abstract DatagramSocket socket(); 250 251 /** 252 * Tells whether or not this channel's socket is connected. 253 * 254 * @return {@code true} if, and only if, this channel's socket 255 * is {@link #isOpen open} and connected 256 */ 257 public abstract boolean isConnected(); 258 259 /** 260 * Connects this channel's socket. 261 * 262 * <p> The channel's socket is configured so that it only receives 263 * datagrams from, and sends datagrams to, the given remote <i>peer</i> 264 * address. Once connected, datagrams may not be received from or sent to 265 * any other address. Datagrams in the channel's {@linkplain 266 * java.net.StandardSocketOptions#SO_RCVBUF socket receive buffer}, which 267 * have not been {@linkplain #receive(ByteBuffer) received} before invoking 268 * this method, may be discarded. The channel's socket remains connected 269 * until it is explicitly disconnected or until it is closed. 270 * 271 * <p> This method performs exactly the same security checks as the {@link 272 * java.net.DatagramSocket#connect connect} method of the {@link 273 * java.net.DatagramSocket} class. That is, if a security manager has been 274 * installed then this method verifies that its {@link 275 * java.lang.SecurityManager#checkAccept checkAccept} and {@link 276 * java.lang.SecurityManager#checkConnect checkConnect} methods permit 277 * datagrams to be received from and sent to, respectively, the given 278 * remote address. Once connected, no further security checks are performed 279 * for datagrams received from, or sent to, the given remote address. Care 280 * should be taken to ensure that a connected datagram channel is not shared 281 * with untrusted code. 282 * 283 * <p> This method may be invoked at any time. If another thread has 284 * already initiated a read or write operation upon this channel, then an 285 * invocation of this method will block until any such operation is 286 * complete. If this channel's socket is not bound then this method will 287 * first cause the socket to be bound to an address that is assigned 288 * automatically, as if invoking the {@link #bind bind} method with a 289 * parameter of {@code null}. </p> 290 * 291 * @param remote 292 * The remote address to which this channel is to be connected 293 * 294 * @return This datagram channel 295 * 296 * @throws AlreadyConnectedException 297 * If this channel is already connected 298 * 299 * @throws ClosedChannelException 300 * If this channel is closed 301 * 302 * @throws AsynchronousCloseException 303 * If another thread closes this channel 304 * while the connect operation is in progress 305 * 306 * @throws ClosedByInterruptException 307 * If another thread interrupts the current thread 308 * while the connect operation is in progress, thereby 309 * closing the channel and setting the current thread's 310 * interrupt status 311 * 312 * @throws UnresolvedAddressException 313 * If the given remote address is not fully resolved 314 * 315 * @throws UnsupportedAddressTypeException 316 * If the type of the given remote address is not supported 317 * 318 * @throws SecurityException 319 * If a security manager has been installed and it does not 320 * permit access to the given remote address, or if unbound, 321 * the security manager {@link SecurityManager#checkListen checkListen} 322 * method denies the operation 323 * 324 * @throws IOException 325 * If some other I/O error occurs 326 */ 327 public abstract DatagramChannel connect(SocketAddress remote) 328 throws IOException; 329 330 /** 331 * Disconnects this channel's socket. 332 * 333 * <p> The channel's socket is configured so that it can receive datagrams 334 * from, and sends datagrams to, any remote address so long as the security 335 * manager, if installed, permits it. 336 * 337 * <p> This method may be invoked at any time. If another thread has 338 * already initiated a read or write operation upon this channel, then an 339 * invocation of this method will block until any such operation is 340 * complete. 341 * 342 * <p> If this channel's socket is not connected, or if the channel is 343 * closed, then invoking this method has no effect. </p> 344 * 345 * @apiNote If this method throws an IOException, the channel's socket 346 * may be left in an unspecified state. It is strongly recommended that 347 * the channel be closed when disconnect fails. 348 * 349 * @return This datagram channel 350 * 351 * @throws IOException 352 * If some other I/O error occurs 353 */ 354 public abstract DatagramChannel disconnect() throws IOException; 355 356 /** 357 * Returns the remote address to which this channel's socket is connected. 358 * 359 * @return The remote address; {@code null} if the channel's socket is not 360 * connected 361 * 362 * @throws ClosedChannelException 363 * If the channel is closed 364 * @throws IOException 365 * If an I/O error occurs 366 * 367 * @since 1.7 368 */ 369 public abstract SocketAddress getRemoteAddress() throws IOException; 370 371 /** 372 * Receives a datagram via this channel. 373 * 374 * <p> If a datagram is immediately available, or if this channel is in 375 * blocking mode and one eventually becomes available, then the datagram is 376 * copied into the given byte buffer and its source address is returned. 377 * If this channel is in non-blocking mode and a datagram is not 378 * immediately available then this method immediately returns 379 * {@code null}. 380 * 381 * <p> The datagram is transferred into the given byte buffer starting at 382 * its current position, as if by a regular {@link 383 * ReadableByteChannel#read(java.nio.ByteBuffer) read} operation. If there 384 * are fewer bytes remaining in the buffer than are required to hold the 385 * datagram then the remainder of the datagram is silently discarded. 386 * 387 * <p> This method performs exactly the same security checks as the {@link 388 * java.net.DatagramSocket#receive receive} method of the {@link 389 * java.net.DatagramSocket} class. That is, if the socket is not connected 390 * to a specific remote address and a security manager has been installed 391 * then for each datagram received this method verifies that the source's 392 * address and port number are permitted by the security manager's {@link 393 * java.lang.SecurityManager#checkAccept checkAccept} method. Datagrams 394 * that are not permitted by the security manager are silently discarded. 395 * The overhead of this security check can be avoided by first connecting 396 * the socket via the {@link #connect connect} method. 397 * 398 * <p> This method may be invoked at any time. If another thread has 399 * already initiated a read operation upon this channel, however, then an 400 * invocation of this method will block until the first operation is 401 * complete. If this channel's socket is not bound then this method will 402 * first cause the socket to be bound to an address that is assigned 403 * automatically, as if invoking the {@link #bind bind} method with a 404 * parameter of {@code null}. </p> 405 * 406 * @param dst 407 * The buffer into which the datagram is to be transferred 408 * 409 * @return The datagram's source address, 410 * or {@code null} if this channel is in non-blocking mode 411 * and no datagram was immediately available 412 * 413 * @throws IllegalArgumentException 414 * If the buffer is read-only 415 * 416 * @throws ClosedChannelException 417 * If this channel is closed 418 * 419 * @throws AsynchronousCloseException 420 * If another thread closes this channel 421 * while the read operation is in progress 422 * 423 * @throws ClosedByInterruptException 424 * If another thread interrupts the current thread 425 * while the read operation is in progress, thereby 426 * closing the channel and setting the current thread's 427 * interrupt status 428 * 429 * @throws SecurityException 430 * If unbound, and a security manager has been installed and 431 * its {@link SecurityManager#checkListen checkListen} method 432 * denies the operation 433 * 434 * @throws IOException 435 * If some other I/O error occurs 436 */ 437 public abstract SocketAddress receive(ByteBuffer dst) throws IOException; 438 439 /** 440 * Sends a datagram via this channel. 441 * 442 * <p> If this channel is in non-blocking mode and there is sufficient room 443 * in the underlying output buffer, or if this channel is in blocking mode 444 * and sufficient room becomes available, then the remaining bytes in the 445 * given buffer are transmitted as a single datagram to the given target 446 * address. 447 * 448 * <p> The datagram is transferred from the byte buffer as if by a regular 449 * {@link WritableByteChannel#write(java.nio.ByteBuffer) write} operation. 450 * 451 * <p> This method performs exactly the same security checks as the {@link 452 * java.net.DatagramSocket#send send} method of the {@link 453 * java.net.DatagramSocket} class. That is, if the socket is not connected 454 * to a specific remote address and a security manager has been installed 455 * then for each datagram sent this method verifies that the target address 456 * and port number are permitted by the security manager's {@link 457 * java.lang.SecurityManager#checkConnect checkConnect} method. The 458 * overhead of this security check can be avoided by first connecting the 459 * socket via the {@link #connect connect} method. 460 * 461 * <p> This method may be invoked at any time. If another thread has 462 * already initiated a write operation upon this channel, however, then an 463 * invocation of this method will block until the first operation is 464 * complete. If this channel's socket is not bound then this method will 465 * first cause the socket to be bound to an address that is assigned 466 * automatically, as if by invoking the {@link #bind bind} method with a 467 * parameter of {@code null}. </p> 468 * 469 * @param src 470 * The buffer containing the datagram to be sent 471 * 472 * @param target 473 * The address to which the datagram is to be sent 474 * 475 * @return The number of bytes sent, which will be either the number 476 * of bytes that were remaining in the source buffer when this 477 * method was invoked or, if this channel is non-blocking, may be 478 * zero if there was insufficient room for the datagram in the 479 * underlying output buffer 480 * 481 * @throws AlreadyConnectedException 482 * If this channel is connected to a different address 483 * from that specified by {@code target} 484 * 485 * @throws ClosedChannelException 486 * If this channel is closed 487 * 488 * @throws AsynchronousCloseException 489 * If another thread closes this channel 490 * while the read operation is in progress 491 * 492 * @throws ClosedByInterruptException 493 * If another thread interrupts the current thread 494 * while the read operation is in progress, thereby 495 * closing the channel and setting the current thread's 496 * interrupt status 497 * 498 * @throws UnresolvedAddressException 499 * If the given remote address is not fully resolved 500 * 501 * @throws UnsupportedAddressTypeException 502 * If the type of the given remote address is not supported 503 * 504 * @throws SecurityException 505 * If a security manager has been installed and it does not permit 506 * datagrams to be sent to the given address, or if unbound, and 507 * the security manager's {@link SecurityManager#checkListen checkListen} 508 * method denies the operation 509 * 510 * @throws IOException 511 * If some other I/O error occurs 512 */ 513 public abstract int send(ByteBuffer src, SocketAddress target) 514 throws IOException; 515 516 517 // -- ByteChannel operations -- 518 519 /** 520 * Reads a datagram from this channel. 521 * 522 * <p> This method may only be invoked if this channel's socket is 523 * connected, and it only accepts datagrams from the socket's peer. If 524 * there are more bytes in the datagram than remain in the given buffer 525 * then the remainder of the datagram is silently discarded. Otherwise 526 * this method behaves exactly as specified in the {@link 527 * ReadableByteChannel} interface. </p> 528 * 529 * @throws NotYetConnectedException 530 * If this channel's socket is not connected 531 */ 532 public abstract int read(ByteBuffer dst) throws IOException; 533 534 /** 535 * Reads a datagram from this channel. 536 * 537 * <p> This method may only be invoked if this channel's socket is 538 * connected, and it only accepts datagrams from the socket's peer. If 539 * there are more bytes in the datagram than remain in the given buffers 540 * then the remainder of the datagram is silently discarded. Otherwise 541 * this method behaves exactly as specified in the {@link 542 * ScatteringByteChannel} interface. </p> 543 * 544 * @throws NotYetConnectedException 545 * If this channel's socket is not connected 546 */ 547 public abstract long read(ByteBuffer[] dsts, int offset, int length) 548 throws IOException; 549 550 /** 551 * Reads a datagram from this channel. 552 * 553 * <p> This method may only be invoked if this channel's socket is 554 * connected, and it only accepts datagrams from the socket's peer. If 555 * there are more bytes in the datagram than remain in the given buffers 556 * then the remainder of the datagram is silently discarded. Otherwise 557 * this method behaves exactly as specified in the {@link 558 * ScatteringByteChannel} interface. </p> 559 * 560 * @throws NotYetConnectedException 561 * If this channel's socket is not connected 562 */ 563 public final long read(ByteBuffer[] dsts) throws IOException { 564 return read(dsts, 0, dsts.length); 565 } 566 567 /** 568 * Writes a datagram to this channel. 569 * 570 * <p> This method may only be invoked if this channel's socket is 571 * connected, in which case it sends datagrams directly to the socket's 572 * peer. Otherwise it behaves exactly as specified in the {@link 573 * WritableByteChannel} interface. </p> 574 * 575 * @throws NotYetConnectedException 576 * If this channel's socket is not connected 577 */ 578 public abstract int write(ByteBuffer src) throws IOException; 579 580 /** 581 * Writes a datagram to this channel. 582 * 583 * <p> This method may only be invoked if this channel's socket is 584 * connected, in which case it sends datagrams directly to the socket's 585 * peer. Otherwise it behaves exactly as specified in the {@link 586 * GatheringByteChannel} interface. </p> 587 * 588 * @return The number of bytes sent, which will be either the number 589 * of bytes that were remaining in the source buffer when this 590 * method was invoked or, if this channel is non-blocking, may be 591 * zero if there was insufficient room for the datagram in the 592 * underlying output buffer 593 * 594 * @throws NotYetConnectedException 595 * If this channel's socket is not connected 596 */ 597 public abstract long write(ByteBuffer[] srcs, int offset, int length) 598 throws IOException; 599 600 /** 601 * Writes a datagram to this channel. 602 * 603 * <p> This method may only be invoked if this channel's socket is 604 * connected, in which case it sends datagrams directly to the socket's 605 * peer. Otherwise it behaves exactly as specified in the {@link 606 * GatheringByteChannel} interface. </p> 607 * 608 * @return The number of bytes sent, which will be either the number 609 * of bytes that were remaining in the source buffer when this 610 * method was invoked or, if this channel is non-blocking, may be 611 * zero if there was insufficient room for the datagram in the 612 * underlying output buffer 613 * 614 * @throws NotYetConnectedException 615 * If this channel's socket is not connected 616 */ 617 public final long write(ByteBuffer[] srcs) throws IOException { 618 return write(srcs, 0, srcs.length); 619 } 620 621 /** 622 * {@inheritDoc} 623 * <p> 624 * If there is a security manager set, its {@code checkConnect} method is 625 * called with the local address and {@code -1} as its arguments to see 626 * if the operation is allowed. If the operation is not allowed, 627 * a {@code SocketAddress} representing the 628 * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the 629 * local port of the channel's socket is returned. 630 * 631 * @return The {@code SocketAddress} that the socket is bound to, or the 632 * {@code SocketAddress} representing the loopback address if 633 * denied by the security manager, or {@code null} if the 634 * channel's socket is not bound 635 * 636 * @throws ClosedChannelException {@inheritDoc} 637 * @throws IOException {@inheritDoc} 638 */ 639 @Override 640 public abstract SocketAddress getLocalAddress() throws IOException; 641 }