1 /* 2 * Copyright (c) 2000, 2019, 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 scope="col">Option Name</th> 65 * <th scope="col">Description</th> 66 * </tr> 67 * </thead> 68 * <tbody> 69 * <tr> 70 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_SNDBUF SO_SNDBUF} </th> 71 * <td> The size of the socket send buffer </td> 72 * </tr> 73 * <tr> 74 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_RCVBUF SO_RCVBUF} </th> 75 * <td> The size of the socket receive buffer </td> 76 * </tr> 77 * <tr> 78 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_REUSEADDR SO_REUSEADDR} </th> 79 * <td> Re-use address </td> 80 * </tr> 81 * <tr> 82 * <th scope="row"> {@link java.net.StandardSocketOptions#SO_BROADCAST SO_BROADCAST} </th> 83 * <td> Allow transmission of broadcast datagrams </td> 84 * </tr> 85 * <tr> 86 * <th scope="row"> {@link java.net.StandardSocketOptions#IP_TOS IP_TOS} </th> 87 * <td> The Type of Service (ToS) octet in the Internet Protocol (IP) header </td> 88 * </tr> 89 * <tr> 90 * <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_IF IP_MULTICAST_IF} </th> 91 * <td> The network interface for Internet Protocol (IP) multicast datagrams </td> 92 * </tr> 93 * <tr> 94 * <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_TTL 95 * IP_MULTICAST_TTL} </th> 96 * <td> The <em>time-to-live</em> for Internet Protocol (IP) multicast 97 * datagrams </td> 98 * </tr> 99 * <tr> 100 * <th scope="row"> {@link java.net.StandardSocketOptions#IP_MULTICAST_LOOP 101 * IP_MULTICAST_LOOP} </th> 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 |} {@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. Datagrams in the channel's {@linkplain 259 * java.net.StandardSocketOptions#SO_RCVBUF socket receive buffer}, which 260 * have not been {@linkplain #receive(ByteBuffer) received} before invoking 261 * this method, may be discarded. The channel's socket remains connected 262 * until it is explicitly disconnected or until it is closed. 263 * 264 * <p> This method performs exactly the same security checks as the {@link 265 * java.net.DatagramSocket#connect connect} method of the {@link 266 * java.net.DatagramSocket} class. That is, if a security manager has been 267 * installed then this method verifies that its {@link 268 * java.lang.SecurityManager#checkAccept checkAccept} and {@link 269 * java.lang.SecurityManager#checkConnect checkConnect} methods permit 270 * datagrams to be received from and sent to, respectively, the given 271 * remote address. Once connected, no further security checks are performed 272 * for datagrams received from, or sent to, the given remote address. Care 273 * should be taken to ensure that a connected datagram channel is not shared 274 * with untrusted code. 275 * 276 * <p> This method may be invoked at any time. If another thread has 277 * already initiated a read or write operation upon this channel, then an 278 * invocation of this method will block until any such operation is 279 * complete. If this channel's socket is not bound then this method will 280 * first cause the socket to be bound to an address that is assigned 281 * automatically, as if invoking the {@link #bind bind} method with a 282 * parameter of {@code null}. </p> 283 * 284 * @param remote 285 * The remote address to which this channel is to be connected 286 * 287 * @return This datagram channel 288 * 289 * @throws AlreadyConnectedException 290 * If this channel is already connected 291 * 292 * @throws ClosedChannelException 293 * If this channel is closed 294 * 295 * @throws AsynchronousCloseException 296 * If another thread closes this channel 297 * while the connect operation is in progress 298 * 299 * @throws ClosedByInterruptException 300 * If another thread interrupts the current thread 301 * while the connect operation is in progress, thereby 302 * closing the channel and setting the current thread's 303 * interrupt status 304 * 305 * @throws UnresolvedAddressException 306 * If the given remote address is not fully resolved 307 * 308 * @throws UnsupportedAddressTypeException 309 * If the type of the given remote address is not supported 310 * 311 * @throws SecurityException 312 * If a security manager has been installed and it does not 313 * permit access to the given remote address, or if unbound, 314 * the security manager {@link SecurityManager#checkListen checkListen} 315 * method denies the operation 316 * 317 * @throws IOException 318 * If some other I/O error occurs 319 */ 320 public abstract DatagramChannel connect(SocketAddress remote) 321 throws IOException; 322 323 /** 324 * Disconnects this channel's socket. 325 * 326 * <p> The channel's socket is configured so that it can receive datagrams 327 * from, and sends datagrams to, any remote address so long as the security 328 * manager, if installed, permits it. 329 * 330 * <p> This method may be invoked at any time. If another thread has 331 * already initiated a read or write operation upon this channel, then an 332 * invocation of this method will block until any such operation is 333 * complete. 334 * 335 * <p> If this channel's socket is not connected, or if the channel is 336 * closed, then invoking this method has no effect. </p> 337 * 338 * @apiNote If this method throws an IOException, the channel's socket 339 * may be left in an unspecified state. It is strongly recommended that 340 * the channel be closed when disconnect fails. 341 * 342 * @return This datagram channel 343 * 344 * @throws IOException 345 * If some other I/O error occurs 346 */ 347 public abstract DatagramChannel disconnect() throws IOException; 348 349 /** 350 * Returns the remote address to which this channel's socket is connected. 351 * 352 * @return The remote address; {@code null} if the channel's socket is not 353 * connected 354 * 355 * @throws ClosedChannelException 356 * If the channel is closed 357 * @throws IOException 358 * If an I/O error occurs 359 * 360 * @since 1.7 361 */ 362 public abstract SocketAddress getRemoteAddress() throws IOException; 363 364 /** 365 * Receives a datagram via this channel. 366 * 367 * <p> If a datagram is immediately available, or if this channel is in 368 * blocking mode and one eventually becomes available, then the datagram is 369 * copied into the given byte buffer and its source address is returned. 370 * If this channel is in non-blocking mode and a datagram is not 371 * immediately available then this method immediately returns 372 * {@code null}. 373 * 374 * <p> The datagram is transferred into the given byte buffer starting at 375 * its current position, as if by a regular {@link 376 * ReadableByteChannel#read(java.nio.ByteBuffer) read} operation. If there 377 * are fewer bytes remaining in the buffer than are required to hold the 378 * datagram then the remainder of the datagram is silently discarded. 379 * 380 * <p> This method performs exactly the same security checks as the {@link 381 * java.net.DatagramSocket#receive receive} method of the {@link 382 * java.net.DatagramSocket} class. That is, if the socket is not connected 383 * to a specific remote address and a security manager has been installed 384 * then for each datagram received this method verifies that the source's 385 * address and port number are permitted by the security manager's {@link 386 * java.lang.SecurityManager#checkAccept checkAccept} method. Datagrams 387 * that are not permitted by the security manager are silently discarded. 388 * The overhead of this security check can be avoided by first connecting 389 * the socket via the {@link #connect connect} method. 390 * 391 * <p> This method may be invoked at any time. If another thread has 392 * already initiated a read operation upon this channel, however, then an 393 * invocation of this method will block until the first operation is 394 * complete. If this channel's socket is not bound then this method will 395 * first cause the socket to be bound to an address that is assigned 396 * automatically, as if invoking the {@link #bind bind} method with a 397 * parameter of {@code null}. </p> 398 * 399 * @param dst 400 * The buffer into which the datagram is to be transferred 401 * 402 * @return The datagram's source address, 403 * or {@code null} if this channel is in non-blocking mode 404 * and no datagram was immediately available 405 * 406 * @throws IllegalArgumentException 407 * If the buffer is read-only 408 * 409 * @throws ClosedChannelException 410 * If this channel is closed 411 * 412 * @throws AsynchronousCloseException 413 * If another thread closes this channel 414 * while the read operation is in progress 415 * 416 * @throws ClosedByInterruptException 417 * If another thread interrupts the current thread 418 * while the read operation is in progress, thereby 419 * closing the channel and setting the current thread's 420 * interrupt status 421 * 422 * @throws SecurityException 423 * If unbound, and a security manager has been installed and 424 * its {@link SecurityManager#checkListen checkListen} method 425 * denies the operation 426 * 427 * @throws IOException 428 * If some other I/O error occurs 429 */ 430 public abstract SocketAddress receive(ByteBuffer dst) throws IOException; 431 432 /** 433 * Sends a datagram via this channel. 434 * 435 * <p> If this channel is in non-blocking mode and there is sufficient room 436 * in the underlying output buffer, or if this channel is in blocking mode 437 * and sufficient room becomes available, then the remaining bytes in the 438 * given buffer are transmitted as a single datagram to the given target 439 * address. 440 * 441 * <p> The datagram is transferred from the byte buffer as if by a regular 442 * {@link WritableByteChannel#write(java.nio.ByteBuffer) write} operation. 443 * 444 * <p> This method performs exactly the same security checks as the {@link 445 * java.net.DatagramSocket#send send} method of the {@link 446 * java.net.DatagramSocket} class. That is, if the socket is not connected 447 * to a specific remote address and a security manager has been installed 448 * then for each datagram sent this method verifies that the target address 449 * and port number are permitted by the security manager's {@link 450 * java.lang.SecurityManager#checkConnect checkConnect} method. The 451 * overhead of this security check can be avoided by first connecting the 452 * socket via the {@link #connect connect} method. 453 * 454 * <p> This method may be invoked at any time. If another thread has 455 * already initiated a write operation upon this channel, however, then an 456 * invocation of this method will block until the first operation is 457 * complete. If this channel's socket is not bound then this method will 458 * first cause the socket to be bound to an address that is assigned 459 * automatically, as if by invoking the {@link #bind bind} method with a 460 * parameter of {@code null}. </p> 461 * 462 * @param src 463 * The buffer containing the datagram to be sent 464 * 465 * @param target 466 * The address to which the datagram is to be sent 467 * 468 * @return The number of bytes sent, which will be either the number 469 * of bytes that were remaining in the source buffer when this 470 * method was invoked or, if this channel is non-blocking, may be 471 * zero if there was insufficient room for the datagram in the 472 * underlying output buffer 473 * 474 * @throws AlreadyConnectedException 475 * If this channel is connected to a different address 476 * from that specified by {@code target} 477 * 478 * @throws ClosedChannelException 479 * If this channel is closed 480 * 481 * @throws AsynchronousCloseException 482 * If another thread closes this channel 483 * while the read operation is in progress 484 * 485 * @throws ClosedByInterruptException 486 * If another thread interrupts the current thread 487 * while the read operation is in progress, thereby 488 * closing the channel and setting the current thread's 489 * interrupt status 490 * 491 * @throws UnresolvedAddressException 492 * If the given remote address is not fully resolved 493 * 494 * @throws UnsupportedAddressTypeException 495 * If the type of the given remote address is not supported 496 * 497 * @throws SecurityException 498 * If a security manager has been installed and it does not permit 499 * datagrams to be sent to the given address, or if unbound, and 500 * the security manager's {@link SecurityManager#checkListen checkListen} 501 * method denies the operation 502 * 503 * @throws IOException 504 * If some other I/O error occurs 505 */ 506 public abstract int send(ByteBuffer src, SocketAddress target) 507 throws IOException; 508 509 510 // -- ByteChannel operations -- 511 512 /** 513 * Reads a datagram from this channel. 514 * 515 * <p> This method may only be invoked if this channel's socket is 516 * connected, and it only accepts datagrams from the socket's peer. If 517 * there are more bytes in the datagram than remain in the given buffer 518 * then the remainder of the datagram is silently discarded. Otherwise 519 * this method behaves exactly as specified in the {@link 520 * ReadableByteChannel} interface. </p> 521 * 522 * @throws NotYetConnectedException 523 * If this channel's socket is not connected 524 */ 525 public abstract int read(ByteBuffer dst) throws IOException; 526 527 /** 528 * Reads a datagram from this channel. 529 * 530 * <p> This method may only be invoked if this channel's socket is 531 * connected, and it only accepts datagrams from the socket's peer. If 532 * there are more bytes in the datagram than remain in the given buffers 533 * then the remainder of the datagram is silently discarded. Otherwise 534 * this method behaves exactly as specified in the {@link 535 * ScatteringByteChannel} interface. </p> 536 * 537 * @throws NotYetConnectedException 538 * If this channel's socket is not connected 539 */ 540 public abstract long read(ByteBuffer[] dsts, int offset, int length) 541 throws IOException; 542 543 /** 544 * Reads a datagram from this channel. 545 * 546 * <p> This method may only be invoked if this channel's socket is 547 * connected, and it only accepts datagrams from the socket's peer. If 548 * there are more bytes in the datagram than remain in the given buffers 549 * then the remainder of the datagram is silently discarded. Otherwise 550 * this method behaves exactly as specified in the {@link 551 * ScatteringByteChannel} interface. </p> 552 * 553 * @throws NotYetConnectedException 554 * If this channel's socket is not connected 555 */ 556 public final long read(ByteBuffer[] dsts) throws IOException { 557 return read(dsts, 0, dsts.length); 558 } 559 560 /** 561 * Writes a datagram to this channel. 562 * 563 * <p> This method may only be invoked if this channel's socket is 564 * connected, in which case it sends datagrams directly to the socket's 565 * peer. Otherwise it behaves exactly as specified in the {@link 566 * WritableByteChannel} interface. </p> 567 * 568 * @throws NotYetConnectedException 569 * If this channel's socket is not connected 570 */ 571 public abstract int write(ByteBuffer src) throws IOException; 572 573 /** 574 * Writes a datagram to this channel. 575 * 576 * <p> This method may only be invoked if this channel's socket is 577 * connected, in which case it sends datagrams directly to the socket's 578 * peer. Otherwise it behaves exactly as specified in the {@link 579 * GatheringByteChannel} interface. </p> 580 * 581 * @return The number of bytes sent, which will be either the number 582 * of bytes that were remaining in the source buffer when this 583 * method was invoked or, if this channel is non-blocking, may be 584 * zero if there was insufficient room for the datagram in the 585 * underlying output buffer 586 * 587 * @throws NotYetConnectedException 588 * If this channel's socket is not connected 589 */ 590 public abstract long write(ByteBuffer[] srcs, int offset, int length) 591 throws IOException; 592 593 /** 594 * Writes a datagram to this channel. 595 * 596 * <p> This method may only be invoked if this channel's socket is 597 * connected, in which case it sends datagrams directly to the socket's 598 * peer. Otherwise it behaves exactly as specified in the {@link 599 * GatheringByteChannel} interface. </p> 600 * 601 * @return The number of bytes sent, which will be either the number 602 * of bytes that were remaining in the source buffer when this 603 * method was invoked or, if this channel is non-blocking, may be 604 * zero if there was insufficient room for the datagram in the 605 * underlying output buffer 606 * 607 * @throws NotYetConnectedException 608 * If this channel's socket is not connected 609 */ 610 public final long write(ByteBuffer[] srcs) throws IOException { 611 return write(srcs, 0, srcs.length); 612 } 613 614 /** 615 * {@inheritDoc} 616 * <p> 617 * If there is a security manager set, its {@code checkConnect} method is 618 * called with the local address and {@code -1} as its arguments to see 619 * if the operation is allowed. If the operation is not allowed, 620 * a {@code SocketAddress} representing the 621 * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the 622 * local port of the channel's socket is returned. 623 * 624 * @return The {@code SocketAddress} that the socket is bound to, or the 625 * {@code SocketAddress} representing the loopback address if 626 * denied by the security manager, or {@code null} if the 627 * channel's socket is not bound 628 * 629 * @throws ClosedChannelException {@inheritDoc} 630 * @throws IOException {@inheritDoc} 631 */ 632 @Override 633 public abstract SocketAddress getLocalAddress() throws IOException; 634 635 }