Package java.net

Class DatagramSocket

java.lang.Object
java.net.DatagramSocket
All Implemented Interfaces:
Closeable, AutoCloseable
Direct Known Subclasses:
MulticastSocket

public class DatagramSocket
extends Object
implements Closeable
This class implements a UDP socket for sending and receiving DatagramPacket. A DatagramSocket object can be used for both endpoints of a connection for a packet delivery service.
See Also:
DatagramPacket, DatagramSocketImplFactory
  • Constructor Details

    • DatagramSocket

      public DatagramSocket() throws SocketException
      Constructs a UDP datagram socket which is bound to any available port on the localhost.
      Throws:
      SocketException - if an error occurs while creating or binding the socket.
    • DatagramSocket

      public DatagramSocket​(int aPort) throws SocketException
      Constructs a UDP datagram socket which is bound to the specific port aPort on the localhost. Valid values for aPort are between 0 and 65535 inclusive.
      Parameters:
      aPort - the port to bind on the localhost.
      Throws:
      SocketException - if an error occurs while creating or binding the socket.
    • DatagramSocket

      public DatagramSocket​(int aPort, InetAddress addr) throws SocketException
      Constructs a UDP datagram socket which is bound to the specific local address addr on port aPort. Valid values for aPort are between 0 and 65535 inclusive.
      Parameters:
      aPort - the port to bind on the localhost.
      addr - the address to bind on the localhost.
      Throws:
      SocketException - if an error occurs while creating or binding the socket.
    • DatagramSocket

      protected DatagramSocket​(DatagramSocketImpl socketImpl)
      Constructs a new DatagramSocket using the specific datagram socket implementation socketImpl. The created DatagramSocket will not be bound.
      Parameters:
      socketImpl - the DatagramSocketImpl to use.
    • DatagramSocket

      public DatagramSocket​(SocketAddress localAddr) throws SocketException
      Constructs a new DatagramSocket bound to the host/port specified by the SocketAddress localAddr or an unbound DatagramSocket if the SocketAddress is null.
      Parameters:
      localAddr - the local machine address and port to bind to.
      Throws:
      IllegalArgumentException - if the SocketAddress is not supported
      SocketException - if a problem occurs creating or binding the socket.
  • Method Details

    • close

      public void close()
      Closes this UDP datagram socket and all possibly associated channels.
      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
    • disconnect

      public void disconnect()
      Disconnects this UDP datagram socket from the remote host. This method called on an unconnected socket does nothing.
    • getInetAddress

      public InetAddress getInetAddress()
      Gets the InetAddress instance representing the remote address to which this UDP datagram socket is connected.
      Returns:
      the remote address this socket is connected to or null if this socket is not connected.
    • getLocalAddress

      public InetAddress getLocalAddress()
      Returns the local address to which this socket is bound, or null if this socket is closed.
    • getLocalPort

      public int getLocalPort()
      Gets the local port which this socket is bound to.
      Returns:
      the local port of this socket or -1 if this socket is closed and 0 if it is unbound.
    • getPort

      public int getPort()
      Gets the remote port which this socket is connected to.
      Returns:
      the remote port of this socket. The return value -1 indicates that this socket is not connected.
    • getReceiveBufferSize

      public int getReceiveBufferSize() throws SocketException
      Returns this socket's receive buffer size.
      Throws:
      SocketException
    • getSendBufferSize

      public int getSendBufferSize() throws SocketException
      Returns this socket's send buffer size.
      Throws:
      SocketException
    • getSoTimeout

      public int getSoTimeout() throws SocketException
      Gets the socket receive timeout.
      Throws:
      SocketException - if an error occurs while getting the option value.
    • receive

      public void receive​(DatagramPacket pack) throws IOException
      Receives a packet from this socket and stores it in the argument pack. All fields of pack must be set according to the data received. If the received data is longer than the packet buffer size it is truncated. This method blocks until a packet is received or a timeout has expired.
      Parameters:
      pack - the DatagramPacket to store the received data.
      Throws:
      IOException - if an error occurs while receiving the packet.
    • send

      public void send​(DatagramPacket pack) throws IOException
      Sends a packet over this socket.
      Parameters:
      pack - the DatagramPacket which has to be sent.
      Throws:
      IOException - if an error occurs while sending the packet.
    • setNetworkInterface

      public void setNetworkInterface​(NetworkInterface netInterface) throws SocketException
      Sets the network interface used by this socket. Any packets sent via this socket are transmitted via the specified interface. Any packets received by this socket will come from the specified interface. Broadcast datagrams received on this interface will be processed by this socket. This corresponds to Linux's SO_BINDTODEVICE.
      Throws:
      SocketException
    • setSendBufferSize

      public void setSendBufferSize​(int size) throws SocketException
      Sets this socket's send buffer size.
      Throws:
      SocketException
    • setReceiveBufferSize

      public void setReceiveBufferSize​(int size) throws SocketException
      Sets this socket's receive buffer size.
      Throws:
      SocketException
    • setSoTimeout

      public void setSoTimeout​(int timeout) throws SocketException
      Sets the read timeout in milliseconds for this socket. This receive timeout defines the period the socket will block waiting to receive data before throwing an InterruptedIOException. The value 0 (default) is used to set an infinite timeout. To have effect this option must be set before the blocking method was called.
      Parameters:
      timeout - the timeout in milliseconds or 0 for no timeout.
      Throws:
      SocketException - if an error occurs while setting the option.
    • setDatagramSocketImplFactory

      public static void setDatagramSocketImplFactory​(DatagramSocketImplFactory fac) throws IOException
      Sets the socket implementation factory. This may only be invoked once over the lifetime of the application. This factory is used to create a new datagram socket implementation.
      Parameters:
      fac - the socket factory to use.
      Throws:
      IOException - if the factory has already been set.
      See Also:
      DatagramSocketImplFactory
    • bind

      public void bind​(SocketAddress localAddr) throws SocketException
      Binds this socket to the local address and port specified by localAddr. If this value is null any free port on a valid local address is used.
      Parameters:
      localAddr - the local machine address and port to bind on.
      Throws:
      IllegalArgumentException - if the SocketAddress is not supported
      SocketException - if the socket is already bound or a problem occurs during binding.
    • connect

      public void connect​(SocketAddress peer) throws SocketException
      Connects this datagram socket to the address and port specified by peer. Future calls to send(java.net.DatagramPacket) will use this as the default target, and receive(java.net.DatagramPacket) will only accept packets from this source.
      Throws:
      SocketException - if an error occurs.
    • connect

      public void connect​(InetAddress address, int port)
      Connects this datagram socket to the specific address and port. Future calls to send(java.net.DatagramPacket) will use this as the default target, and receive(java.net.DatagramPacket) will only accept packets from this source.

      Beware: because it can't throw, this method silently ignores failures. Use connect(SocketAddress) instead.

    • isBound

      public boolean isBound()
      Returns true if this socket is bound to a local address. See bind(java.net.SocketAddress).
    • isConnected

      public boolean isConnected()
      Returns true if this datagram socket is connected to a remote address. See connect(java.net.SocketAddress).
    • getRemoteSocketAddress

      public SocketAddress getRemoteSocketAddress()
      Returns the SocketAddress this socket is connected to, or null for an unconnected socket.
    • getLocalSocketAddress

      public SocketAddress getLocalSocketAddress()
      Returns the SocketAddress this socket is bound to, or null for an unbound socket.
    • setReuseAddress

      public void setReuseAddress​(boolean reuse) throws SocketException
      Sets the socket option SocketOptions.SO_REUSEADDR. This option has to be enabled if more than one UDP socket wants to be bound to the same address. That could be needed for receiving multicast packets.

      There is an undefined behavior if this option is set after the socket is already bound.

      Parameters:
      reuse - the socket option value to enable or disable this option.
      Throws:
      SocketException - if the socket is closed or the option could not be set.
    • getReuseAddress

      public boolean getReuseAddress() throws SocketException
      Gets the state of the socket option SocketOptions.SO_REUSEADDR.
      Returns:
      true if the option is enabled, false otherwise.
      Throws:
      SocketException - if the socket is closed or the option is invalid.
    • setBroadcast

      public void setBroadcast​(boolean broadcast) throws SocketException
      Sets the socket option SocketOptions.SO_BROADCAST. This option must be enabled to send broadcast messages.
      Parameters:
      broadcast - the socket option value to enable or disable this option.
      Throws:
      SocketException - if the socket is closed or the option could not be set.
    • getBroadcast

      public boolean getBroadcast() throws SocketException
      Gets the state of the socket option SocketOptions.SO_BROADCAST.
      Returns:
      true if the option is enabled, false otherwise.
      Throws:
      SocketException - if the socket is closed or the option is invalid.
    • setTrafficClass

      public void setTrafficClass​(int value) throws SocketException
      Sets the {@see SocketOptions#IP_TOS} value for every packet sent by this socket.
      Throws:
      SocketException - if the socket is closed or the option could not be set.
    • getTrafficClass

      public int getTrafficClass() throws SocketException
      Returns this socket's {@see SocketOptions#IP_TOS} setting.
      Throws:
      SocketException - if the socket is closed or the option is invalid.
    • isClosed

      public boolean isClosed()
      Gets the state of this socket.
      Returns:
      true if the socket is closed, false otherwise.
    • getChannel

      public DatagramChannel getChannel()
      Returns this socket's DatagramChannel, if one exists. A channel is available only if this socket wraps a channel. (That is, you can go from a channel to a socket and back again, but you can't go from an arbitrary socket to a channel.) In practice, this means that the socket must have been created by DatagramChannel.open().
    • getFileDescriptor$

      public final FileDescriptor getFileDescriptor$()