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 ClosedChannelException 407 * If this channel is closed 408 * 409 * @throws AsynchronousCloseException 410 * If another thread closes this channel 411 * while the read operation is in progress 412 * 413 * @throws ClosedByInterruptException 414 * If another thread interrupts the current thread 415 * while the read operation is in progress, thereby 416 * closing the channel and setting the current thread's 417 * interrupt status 418 * 419 * @throws SecurityException 420 * If unbound, and a security manager has been installed and 421 * its {@link SecurityManager#checkListen checkListen} method 422 * denies the operation 423 * 424 * @throws IOException 425 * If some other I/O error occurs 426 */ 427 public abstract SocketAddress receive(ByteBuffer dst) throws IOException; 428 429 /** 430 * Sends a datagram via this channel. 431 * 432 * <p> If this channel is in non-blocking mode and there is sufficient room 433 * in the underlying output buffer, or if this channel is in blocking mode 434 * and sufficient room becomes available, then the remaining bytes in the 435 * given buffer are transmitted as a single datagram to the given target 436 * address. 437 * 438 * <p> The datagram is transferred from the byte buffer as if by a regular 439 * {@link WritableByteChannel#write(java.nio.ByteBuffer) write} operation. 440 * 441 * <p> This method performs exactly the same security checks as the {@link 442 * java.net.DatagramSocket#send send} method of the {@link 443 * java.net.DatagramSocket} class. That is, if the socket is not connected 444 * to a specific remote address and a security manager has been installed 445 * then for each datagram sent this method verifies that the target address 446 * and port number are permitted by the security manager's {@link 447 * java.lang.SecurityManager#checkConnect checkConnect} method. The 448 * overhead of this security check can be avoided by first connecting the 449 * socket via the {@link #connect connect} method. 450 * 451 * <p> This method may be invoked at any time. If another thread has 452 * already initiated a write operation upon this channel, however, then an 453 * invocation of this method will block until the first operation is 454 * complete. If this channel's socket is not bound then this method will 455 * first cause the socket to be bound to an address that is assigned 456 * automatically, as if by invoking the {@link #bind bind} method with a 457 * parameter of {@code null}. </p> 458 * 459 * @param src 460 * The buffer containing the datagram to be sent 461 * 462 * @param target 463 * The address to which the datagram is to be sent 464 * 465 * @return The number of bytes sent, which will be either the number 466 * of bytes that were remaining in the source buffer when this 467 * method was invoked or, if this channel is non-blocking, may be 468 * zero if there was insufficient room for the datagram in the 469 * underlying output buffer 470 * 471 * @throws AlreadyConnectedException 472 * If this channel is connected to a different address 473 * from that specified by {@code target} 474 * 475 * @throws ClosedChannelException 476 * If this channel is closed 477 * 478 * @throws AsynchronousCloseException 479 * If another thread closes this channel 480 * while the read operation is in progress 481 * 482 * @throws ClosedByInterruptException 483 * If another thread interrupts the current thread 484 * while the read operation is in progress, thereby 485 * closing the channel and setting the current thread's 486 * interrupt status 487 * 488 * @throws UnresolvedAddressException 489 * If the given remote address is not fully resolved 490 * 491 * @throws UnsupportedAddressTypeException 492 * If the type of the given remote address is not supported 493 * 494 * @throws SecurityException 495 * If a security manager has been installed and it does not permit 496 * datagrams to be sent to the given address, or if unbound, and 497 * the security manager's {@link SecurityManager#checkListen checkListen} 498 * method denies the operation 499 * 500 * @throws IOException 501 * If some other I/O error occurs 502 */ 503 public abstract int send(ByteBuffer src, SocketAddress target) 504 throws IOException; 505 506 507 // -- ByteChannel operations -- 508 509 /** 510 * Reads a datagram from this channel. 511 * 512 * <p> This method may only be invoked if this channel's socket is 513 * connected, and it only accepts datagrams from the socket's peer. If 514 * there are more bytes in the datagram than remain in the given buffer 515 * then the remainder of the datagram is silently discarded. Otherwise 516 * this method behaves exactly as specified in the {@link 517 * ReadableByteChannel} interface. </p> 518 * 519 * @throws NotYetConnectedException 520 * If this channel's socket is not connected 521 */ 522 public abstract int read(ByteBuffer dst) throws IOException; 523 524 /** 525 * Reads a datagram from this channel. 526 * 527 * <p> This method may only be invoked if this channel's socket is 528 * connected, and it only accepts datagrams from the socket's peer. If 529 * there are more bytes in the datagram than remain in the given buffers 530 * then the remainder of the datagram is silently discarded. Otherwise 531 * this method behaves exactly as specified in the {@link 532 * ScatteringByteChannel} interface. </p> 533 * 534 * @throws NotYetConnectedException 535 * If this channel's socket is not connected 536 */ 537 public abstract long read(ByteBuffer[] dsts, int offset, int length) 538 throws IOException; 539 540 /** 541 * Reads a datagram from this channel. 542 * 543 * <p> This method may only be invoked if this channel's socket is 544 * connected, and it only accepts datagrams from the socket's peer. If 545 * there are more bytes in the datagram than remain in the given buffers 546 * then the remainder of the datagram is silently discarded. Otherwise 547 * this method behaves exactly as specified in the {@link 548 * ScatteringByteChannel} interface. </p> 549 * 550 * @throws NotYetConnectedException 551 * If this channel's socket is not connected 552 */ 553 public final long read(ByteBuffer[] dsts) throws IOException { 554 return read(dsts, 0, dsts.length); 555 } 556 557 /** 558 * Writes a datagram to this channel. 559 * 560 * <p> This method may only be invoked if this channel's socket is 561 * connected, in which case it sends datagrams directly to the socket's 562 * peer. Otherwise it behaves exactly as specified in the {@link 563 * WritableByteChannel} interface. </p> 564 * 565 * @throws NotYetConnectedException 566 * If this channel's socket is not connected 567 */ 568 public abstract int write(ByteBuffer src) throws IOException; 569 570 /** 571 * Writes a datagram to this channel. 572 * 573 * <p> This method may only be invoked if this channel's socket is 574 * connected, in which case it sends datagrams directly to the socket's 575 * peer. Otherwise it behaves exactly as specified in the {@link 576 * GatheringByteChannel} interface. </p> 577 * 578 * @return The number of bytes sent, which will be either the number 579 * of bytes that were remaining in the source buffer when this 580 * method was invoked or, if this channel is non-blocking, may be 581 * zero if there was insufficient room for the datagram in the 582 * underlying output buffer 583 * 584 * @throws NotYetConnectedException 585 * If this channel's socket is not connected 586 */ 587 public abstract long write(ByteBuffer[] srcs, int offset, int length) 588 throws IOException; 589 590 /** 591 * Writes a datagram to this channel. 592 * 593 * <p> This method may only be invoked if this channel's socket is 594 * connected, in which case it sends datagrams directly to the socket's 595 * peer. Otherwise it behaves exactly as specified in the {@link 596 * GatheringByteChannel} interface. </p> 597 * 598 * @return The number of bytes sent, which will be either the number 599 * of bytes that were remaining in the source buffer when this 600 * method was invoked or, if this channel is non-blocking, may be 601 * zero if there was insufficient room for the datagram in the 602 * underlying output buffer 603 * 604 * @throws NotYetConnectedException 605 * If this channel's socket is not connected 606 */ 607 public final long write(ByteBuffer[] srcs) throws IOException { 608 return write(srcs, 0, srcs.length); 609 } 610 611 /** 612 * {@inheritDoc} 613 * <p> 614 * If there is a security manager set, its {@code checkConnect} method is 615 * called with the local address and {@code -1} as its arguments to see 616 * if the operation is allowed. If the operation is not allowed, 617 * a {@code SocketAddress} representing the 618 * {@link java.net.InetAddress#getLoopbackAddress loopback} address and the 619 * local port of the channel's socket is returned. 620 * 621 * @return The {@code SocketAddress} that the socket is bound to, or the 622 * {@code SocketAddress} representing the loopback address if 623 * denied by the security manager, or {@code null} if the 624 * channel's socket is not bound 625 * 626 * @throws ClosedChannelException {@inheritDoc} 627 * @throws IOException {@inheritDoc} 628 */ 629 @Override 630 public abstract SocketAddress getLocalAddress() throws IOException; 631 632 }