DatagramSocket

public class DatagramSocket
extends Object implements Closeable

java.lang.Object
   ↳ java.net.DatagramSocket
MulticastSocket The multicast datagram socket class is useful for sending and receiving IP multicast packets. 


This class represents a socket for sending and receiving datagram packets.

A datagram socket is the sending or receiving point for a packet delivery service. Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may be routed differently, and may arrive in any order.

Where possible, a newly constructed DatagramSocket has the SO_BROADCAST socket option enabled so as to allow the transmission of broadcast datagrams. In order to receive broadcast packets a DatagramSocket should be bound to the wildcard address. In some implementations, broadcast packets may also be received when a DatagramSocket is bound to a more specific address.

Example: DatagramSocket s = new DatagramSocket(null); s.bind(new InetSocketAddress(8888)); Which is equivalent to: DatagramSocket s = new DatagramSocket(8888); Both cases will create a DatagramSocket able to receive broadcasts on UDP port 8888.

Summary

Public constructors

DatagramSocket()

Constructs a datagram socket and binds it to any available port on the local host machine.

DatagramSocket(SocketAddress bindaddr)

Creates a datagram socket, bound to the specified local socket address.

DatagramSocket(int port)

Constructs a datagram socket and binds it to the specified port on the local host machine.

DatagramSocket(int port, InetAddress laddr)

Creates a datagram socket, bound to the specified local address.

Protected constructors

DatagramSocket(DatagramSocketImpl impl)

Creates an unbound datagram socket with the specified DatagramSocketImpl.

Public methods

void bind(SocketAddress addr)

Binds this DatagramSocket to a specific address and port.

void close()

Closes this datagram socket.

void connect(InetAddress address, int port)

Connects the socket to a remote address for this socket.

void connect(SocketAddress addr)

Connects this socket to a remote socket address (IP address + port number).

void disconnect()

Disconnects the socket.

boolean getBroadcast()

Tests if SO_BROADCAST is enabled.

DatagramChannel getChannel()

Returns the unique DatagramChannel object associated with this datagram socket, if any.

InetAddress getInetAddress()

Returns the address to which this socket is connected.

InetAddress getLocalAddress()

Gets the local address to which the socket is bound.

int getLocalPort()

Returns the port number on the local host to which this socket is bound.

SocketAddress getLocalSocketAddress()

Returns the address of the endpoint this socket is bound to.

<T> T getOption(SocketOption<T> name)

Returns the value of a socket option.

int getPort()

Returns the port number to which this socket is connected.

int getReceiveBufferSize()

Get value of the SO_RCVBUF option for this DatagramSocket, that is the buffer size used by the platform for input on this DatagramSocket.

SocketAddress getRemoteSocketAddress()

Returns the address of the endpoint this socket is connected to, or null if it is unconnected.

boolean getReuseAddress()

Tests if SO_REUSEADDR is enabled.

int getSendBufferSize()

Get value of the SO_SNDBUF option for this DatagramSocket, that is the buffer size used by the platform for output on this DatagramSocket.

int getSoTimeout()

Retrieve setting for SO_TIMEOUT.

int getTrafficClass()

Gets traffic class or type-of-service in the IP datagram header for packets sent from this DatagramSocket.

boolean isBound()

Returns the binding state of the socket.

boolean isClosed()

Returns whether the socket is closed or not.

boolean isConnected()

Returns the connection state of the socket.

void receive(DatagramPacket p)

Receives a datagram packet from this socket.

void send(DatagramPacket p)

Sends a datagram packet from this socket.

void setBroadcast(boolean on)

Enable/disable SO_BROADCAST.

static void setDatagramSocketImplFactory(DatagramSocketImplFactory fac)

Sets the datagram socket implementation factory for the application.

<T> DatagramSocket setOption(SocketOption<T> name, T value)

Sets the value of a socket option.

void setReceiveBufferSize(int size)

Sets the SO_RCVBUF option to the specified value for this DatagramSocket.

void setReuseAddress(boolean on)

Enable/disable the SO_REUSEADDR socket option.

void setSendBufferSize(int size)

Sets the SO_SNDBUF option to the specified value for this DatagramSocket.

void setSoTimeout(int timeout)

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

void setTrafficClass(int tc)

Sets traffic class or type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket.

Set<SocketOption<?>> supportedOptions()

Returns a set of the socket options supported by this socket.

Inherited methods

Object clone()

Creates and returns a copy of this object.

boolean equals(Object obj)

Indicates whether some other object is "equal to" this one.

void finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

final Class<?> getClass()

Returns the runtime class of this Object.

int hashCode()

Returns a hash code value for the object.

final void notify()

Wakes up a single thread that is waiting on this object's monitor.

final void notifyAll()

Wakes up all threads that are waiting on this object's monitor.

String toString()

Returns a string representation of the object.

final void wait(long timeoutMillis, int nanos)

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

final void wait(long timeoutMillis)

Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed.

final void wait()

Causes the current thread to wait until it is awakened, typically by being notified or interrupted.

abstract void close()

Closes this stream and releases any system resources associated with it.

abstract void close()

Closes this resource, relinquishing any underlying resources.

Public constructors

DatagramSocket

Added in API level 1
public DatagramSocket ()

Constructs a datagram socket and binds it to any available port on the local host machine. The socket will be bound to the wildcard address, an IP address chosen by the kernel.

If there is a security manager, its checkListen method is first called with 0 as its argument to ensure the operation is allowed. This could result in a SecurityException.

Throws
SocketException if the socket could not be opened, or the socket could not bind to the specified local port.
SecurityException if a security manager exists and its checkListen method doesn't allow the operation.

DatagramSocket

Added in API level 1
public DatagramSocket (SocketAddress bindaddr)

Creates a datagram socket, bound to the specified local socket address.

If, if the address is null, creates an unbound socket.

If there is a security manager, its checkListen method is first called with the port from the socket address as its argument to ensure the operation is allowed. This could result in a SecurityException.

Parameters
bindaddr SocketAddress: local socket address to bind, or null for an unbound socket.

Throws
SocketException if the socket could not be opened, or the socket could not bind to the specified local port.
SecurityException if a security manager exists and its checkListen method doesn't allow the operation.

DatagramSocket

Added in API level 1
public DatagramSocket (int port)

Constructs a datagram socket and binds it to the specified port on the local host machine. The socket will be bound to the wildcard address, an IP address chosen by the kernel.

If there is a security manager, its checkListen method is first called with the port argument as its argument to ensure the operation is allowed. This could result in a SecurityException.

Parameters
port int: port to use.

Throws
SocketException if the socket could not be opened, or the socket could not bind to the specified local port.
SecurityException if a security manager exists and its checkListen method doesn't allow the operation.

DatagramSocket

Added in API level 1
public DatagramSocket (int port, 
                InetAddress laddr)

Creates a datagram socket, bound to the specified local address. The local port must be between 0 and 65535 inclusive. If the IP address is 0.0.0.0, the socket will be bound to the wildcard address, an IP address chosen by the kernel.

If there is a security manager, its checkListen method is first called with the port argument as its argument to ensure the operation is allowed. This could result in a SecurityException.

Parameters
port int: local port to use

laddr InetAddress: local address to bind

Throws
SocketException if the socket could not be opened, or the socket could not bind to the specified local port.
SecurityException if a security manager exists and its checkListen method doesn't allow the operation.

Protected constructors

DatagramSocket

Added in API level 1
protected DatagramSocket (DatagramSocketImpl impl)

Creates an unbound datagram socket with the specified DatagramSocketImpl.

Parameters
impl DatagramSocketImpl: an instance of a DatagramSocketImpl the subclass wishes to use on the DatagramSocket.

Public methods

bind

Added in API level 1
public void bind (SocketAddress addr)

Binds this DatagramSocket to a specific address and port.

If the address is null, then the system will pick up an ephemeral port and a valid local address to bind the socket.

Parameters
addr SocketAddress: The address and port to bind to.

Throws
SocketException if any error happens during the bind, or if the socket is already bound.
SecurityException if a security manager exists and its checkListen method doesn't allow the operation.
IllegalArgumentException if addr is a SocketAddress subclass not supported by this socket.

close

Added in API level 1
public void close ()

Closes this datagram socket.

Any thread currently blocked in receive(DatagramPacket) upon this socket will throw a SocketException.

If this socket has an associated channel then the channel is closed as well.

connect

Added in API level 1
public void connect (InetAddress address, 
                int port)

Connects the socket to a remote address for this socket. When a socket is connected to a remote address, packets may only be sent to or received from that address. By default a datagram socket is not connected.

If the remote destination to which the socket is connected does not exist, or is otherwise unreachable, and if an ICMP destination unreachable packet has been received for that address, then a subsequent call to send or receive may throw a PortUnreachableException. Note, there is no guarantee that the exception will be thrown.

If a security manager has been installed then it is invoked to check access to the remote address. Specifically, if the given address is a multicast address, the security manager's checkMulticast method is invoked with the given address. Otherwise, the security manager's checkConnect and checkAccept methods are invoked, with the given address and port, to verify that datagrams are permitted to be sent and received respectively.

When a socket is connected, receive and send will not perform any security checks on incoming and outgoing packets, other than matching the packet's and the socket's address and port. On a send operation, if the packet's address is set and the packet's address and the socket's address do not match, an IllegalArgumentException will be thrown. A socket connected to a multicast address may only be used to send packets.

Parameters
address InetAddress: the remote address for the socket

port int: the remote port for the socket.

Throws
IllegalArgumentException if the address is null, or the port is out of range.
SecurityException if a security manager has been installed and it does not permit access to the given remote address

See also:

connect

Added in API level 1
public void connect (SocketAddress addr)

Connects this socket to a remote socket address (IP address + port number).

If given an InetSocketAddress, this method behaves as if invoking connect(InetAddress,int) with the given socket addresses IP address and port number.

Parameters
addr SocketAddress: The remote address.

Throws
SocketException if the connect fails
IllegalArgumentException if addr is null, or addr is a SocketAddress subclass not supported by this socket
SecurityException if a security manager has been installed and it does not permit access to the given remote address

disconnect

Added in API level 1
public void disconnect ()

Disconnects the socket. If the socket is closed or not connected, then this method has no effect.

getBroadcast

Added in API level 1
public boolean getBroadcast ()

Tests if SO_BROADCAST is enabled.

Returns
boolean a boolean indicating whether or not SO_BROADCAST is enabled.

Throws
SocketException if there is an error in the underlying protocol, such as an UDP error.

getChannel

Added in API level 1
public DatagramChannel getChannel ()

Returns the unique DatagramChannel object associated with this datagram socket, if any.

A datagram socket will have a channel if, and only if, the channel itself was created via the DatagramChannel.open method.

Returns
DatagramChannel the datagram channel associated with this datagram socket, or null if this socket was not created for a channel

getInetAddress

Added in API level 1
public InetAddress getInetAddress ()

Returns the address to which this socket is connected. Returns null if the socket is not connected.

If the socket was connected prior to being closed, then this method will continue to return the connected address after the socket is closed.

Returns
InetAddress the address to which this socket is connected.

getLocalAddress

Added in API level 1
public InetAddress getLocalAddress ()

Gets the local address to which the socket is bound.

If there is a security manager, its checkConnect method is first called with the host address and -1 as its arguments to see if the operation is allowed.

Returns
InetAddress the local address to which the socket is bound, null if the socket is closed, or an InetAddress representing wildcard address if either the socket is not bound, or the security manager checkConnect method does not allow the operation

getLocalPort

Added in API level 1
public int getLocalPort ()

Returns the port number on the local host to which this socket is bound.

Returns
int the port number on the local host to which this socket is bound, -1 if the socket is closed, or 0 if it is not bound yet.

getLocalSocketAddress

Added in API level 1
public SocketAddress getLocalSocketAddress ()

Returns the address of the endpoint this socket is bound to.

Returns
SocketAddress a SocketAddress representing the local endpoint of this socket, or null if it is closed or not bound yet.

getOption

Added in API level 33
public T getOption (SocketOption<T> name)

Returns the value of a socket option.

Parameters
name SocketOption: The socket option

Returns
T The value of the socket option.

Throws
UnsupportedOperationException if the datagram socket does not support the option.
IOException if an I/O error occurs, or if the socket is closed.
NullPointerException if name is null
SecurityException if a security manager is set and if the socket option requires a security permission and if the caller does not have the required permission. StandardSocketOptions do not require any security permission.

getPort

Added in API level 1
public int getPort ()

Returns the port number to which this socket is connected. Returns -1 if the socket is not connected.

If the socket was connected prior to being closed, then this method will continue to return the connected port number after the socket is closed.

Returns
int the port number to which this socket is connected.

getReceiveBufferSize

Added in API level 1
public int getReceiveBufferSize ()

Get value of the SO_RCVBUF option for this DatagramSocket, that is the buffer size used by the platform for input on this DatagramSocket.

Returns
int the value of the SO_RCVBUF option for this DatagramSocket

Throws
SocketException if there is an error in the underlying protocol, such as an UDP error.

getRemoteSocketAddress

Added in API level 1
public SocketAddress getRemoteSocketAddress ()

Returns the address of the endpoint this socket is connected to, or null if it is unconnected.

If the socket was connected prior to being closed, then this method will continue to return the connected address after the socket is closed.

Returns
SocketAddress a SocketAddress representing the remote endpoint of this socket, or null if it is not connected yet.

getReuseAddress

Added in API level 1
public boolean getReuseAddress ()

Tests if SO_REUSEADDR is enabled.

Returns
boolean a boolean indicating whether or not SO_REUSEADDR is enabled.

Throws
SocketException if there is an error in the underlying protocol, such as an UDP error.

getSendBufferSize

Added in API level 1
public int getSendBufferSize ()

Get value of the SO_SNDBUF option for this DatagramSocket, that is the buffer size used by the platform for output on this DatagramSocket.

Returns
int the value of the SO_SNDBUF option for this DatagramSocket

Throws
SocketException if there is an error in the underlying protocol, such as an UDP error.

getSoTimeout

Added in API level 1
public int getSoTimeout ()

Retrieve setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity).

Returns
int the setting for SO_TIMEOUT

Throws
SocketException if there is an error in the underlying protocol, such as an UDP error.

See also:

getTrafficClass

Added in API level 1
public int getTrafficClass ()

Gets traffic class or type-of-service in the IP datagram header for packets sent from this DatagramSocket.

As the underlying network implementation may ignore the traffic class or type-of-service set using setTrafficClass(int) this method may return a different value than was previously set using the setTrafficClass(int) method on this DatagramSocket.

Returns
int the traffic class or type-of-service already set

Throws
SocketException if there is an error obtaining the traffic class or type-of-service value.

isBound

Added in API level 1
public boolean isBound ()

Returns the binding state of the socket.

If the socket was bound prior to being closed, then this method will continue to return true after the socket is closed.

Returns
boolean true if the socket successfully bound to an address

isClosed

Added in API level 1
public boolean isClosed ()

Returns whether the socket is closed or not.

Returns
boolean true if the socket has been closed

isConnected

Added in API level 1
public boolean isConnected ()

Returns the connection state of the socket.

If the socket was connected prior to being closed, then this method will continue to return true after the socket is closed.

Returns
boolean true if the socket successfully connected to a server

receive

Added in API level 1
public void receive (DatagramPacket p)

Receives a datagram packet from this socket. When this method returns, the DatagramPacket's buffer is filled with the data received. The datagram packet also contains the sender's IP address, and the port number on the sender's machine.

This method blocks until a datagram is received. The length field of the datagram packet object contains the length of the received message. If the message is longer than the packet's length, the message is truncated.

If there is a security manager, a packet cannot be received if the security manager's checkAccept method does not allow it.

Parameters
p DatagramPacket: the DatagramPacket into which to place the incoming data.

Throws
IOException if an I/O error occurs.
SocketTimeoutException if setSoTimeout was previously called and the timeout has expired.
PortUnreachableException may be thrown if the socket is connected to a currently unreachable destination. Note, there is no guarantee that the exception will be thrown.
IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode.

send

Added in API level 1
public void send (DatagramPacket p)

Sends a datagram packet from this socket. The DatagramPacket includes information indicating the data to be sent, its length, the IP address of the remote host, and the port number on the remote host.

If there is a security manager, and the socket is not currently connected to a remote address, this method first performs some security checks. First, if p.getAddress().isMulticastAddress() is true, this method calls the security manager's checkMulticast method with p.getAddress() as its argument. If the evaluation of that expression is false, this method instead calls the security manager's checkConnect method with arguments p.getAddress().getHostAddress() and p.getPort(). Each call to a security manager method could result in a SecurityException if the operation is not allowed.

Parameters
p DatagramPacket: the DatagramPacket to be sent.

Throws
IOException if an I/O error occurs.
SecurityException if a security manager exists and its checkMulticast or checkConnect method doesn't allow the send.
PortUnreachableException may be thrown if the socket is connected to a currently unreachable destination. Note, there is no guarantee that the exception will be thrown.
IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode.
IllegalArgumentException if the socket is connected, and connected address and packet address differ.

setBroadcast

Added in API level 1
public void setBroadcast (boolean on)

Enable/disable SO_BROADCAST.

Some operating systems may require that the Java virtual machine be started with implementation specific privileges to enable this option or send broadcast datagrams.

Parameters
on boolean: whether or not to have broadcast turned on.

Throws
SocketException if there is an error in the underlying protocol, such as an UDP error.

See also:

setDatagramSocketImplFactory

Added in API level 1
public static void setDatagramSocketImplFactory (DatagramSocketImplFactory fac)

Sets the datagram socket implementation factory for the application. The factory can be specified only once.

When an application creates a new datagram socket, the socket implementation factory's createDatagramSocketImpl method is called to create the actual datagram socket implementation.

Passing null to the method is a no-op unless the factory was already set.

If there is a security manager, this method first calls the security manager's checkSetFactory method to ensure the operation is allowed. This could result in a SecurityException.

Parameters
fac DatagramSocketImplFactory: the desired factory.

Throws
IOException if an I/O error occurs when setting the datagram socket factory.
SocketException if the factory is already defined.
SecurityException if a security manager exists and its checkSetFactory method doesn't allow the operation.

setOption

Added in API level 33
public DatagramSocket setOption (SocketOption<T> name, 
                T value)

Sets the value of a socket option.

Parameters
name SocketOption: The socket option

value T: The value of the socket option. A value of null may be valid for some options.

Returns
DatagramSocket this DatagramSocket

Throws
UnsupportedOperationException if the datagram socket does not support the option.
IllegalArgumentException if the value is not valid for the option.
IOException if an I/O error occurs, or if the socket is closed.
SecurityException if a security manager is set and if the socket option requires a security permission and if the caller does not have the required permission. StandardSocketOptions do not require any security permission.
NullPointerException if name is null

setReceiveBufferSize

Added in API level 1
public void setReceiveBufferSize (int size)

Sets the SO_RCVBUF option to the specified value for this DatagramSocket. The SO_RCVBUF option is used by the network implementation as a hint to size the underlying network I/O buffers. The SO_RCVBUF setting may also be used by the network implementation to determine the maximum size of the packet that can be received on this socket.

Because SO_RCVBUF is a hint, applications that want to verify what size the buffers were set to should call getReceiveBufferSize().

Increasing SO_RCVBUF may allow the network implementation to buffer multiple packets when packets arrive faster than are being received using receive(java.net.DatagramPacket).

Note: It is implementation specific if a packet larger than SO_RCVBUF can be received.

Parameters
size int: the size to which to set the receive buffer size. This value must be greater than 0.

Throws
SocketException if there is an error in the underlying protocol, such as an UDP error.
IllegalArgumentException if the value is 0 or is negative.

setReuseAddress

Added in API level 1
public void setReuseAddress (boolean on)

Enable/disable the SO_REUSEADDR socket option.

For UDP sockets it may be necessary to bind more than one socket to the same socket address. This is typically for the purpose of receiving multicast packets (See MulticastSocket). The SO_REUSEADDR socket option allows multiple sockets to be bound to the same socket address if the SO_REUSEADDR socket option is enabled prior to binding the socket using bind(java.net.SocketAddress).

Note: This functionality is not supported by all existing platforms, so it is implementation specific whether this option will be ignored or not. However, if it is not supported then getReuseAddress() will always return false.

When a DatagramSocket is created the initial setting of SO_REUSEADDR is disabled.

The behaviour when SO_REUSEADDR is enabled or disabled after a socket is bound (See isBound()) is not defined.

Parameters
on boolean: whether to enable or disable the

Throws
SocketException if an error occurs enabling or disabling the SO_RESUEADDR socket option, or the socket is closed.

setSendBufferSize

Added in API level 1
public void setSendBufferSize (int size)

Sets the SO_SNDBUF option to the specified value for this DatagramSocket. The SO_SNDBUF option is used by the network implementation as a hint to size the underlying network I/O buffers. The SO_SNDBUF setting may also be used by the network implementation to determine the maximum size of the packet that can be sent on this socket.

As SO_SNDBUF is a hint, applications that want to verify what size the buffer is should call getSendBufferSize().

Increasing the buffer size may allow multiple outgoing packets to be queued by the network implementation when the send rate is high.

Note: If send(java.net.DatagramPacket) is used to send a DatagramPacket that is larger than the setting of SO_SNDBUF then it is implementation specific if the packet is sent or discarded.

Parameters
size int: the size to which to set the send buffer size. This value must be greater than 0.

Throws
SocketException if there is an error in the underlying protocol, such as an UDP error.
IllegalArgumentException if the value is 0 or is negative.

setSoTimeout

Added in API level 1
public void setSoTimeout (int timeout)

Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a call to receive() for this DatagramSocket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the DatagramSocket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

Parameters
timeout int: the specified timeout in milliseconds.

Throws
SocketException if there is an error in the underlying protocol, such as an UDP error.

See also:

setTrafficClass

Added in API level 1
public void setTrafficClass (int tc)

Sets traffic class or type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket. As the underlying network implementation may ignore this value applications should consider it a hint.

The tc must be in the range 0 <= tc <= 255 or an IllegalArgumentException will be thrown.

Notes:

For Internet Protocol v4 the value consists of an integer, the least significant 8 bits of which represent the value of the TOS octet in IP packets sent by the socket. RFC 1349 defines the TOS values as follows:

  • IPTOS_LOWCOST (0x02)
  • IPTOS_RELIABILITY (0x04)
  • IPTOS_THROUGHPUT (0x08)
  • IPTOS_LOWDELAY (0x10)
The last low order bit is always ignored as this corresponds to the MBZ (must be zero) bit.

Setting bits in the precedence field may result in a SocketException indicating that the operation is not permitted.

for Internet Protocol v6 tc is the value that would be placed into the sin6_flowinfo field of the IP header.

Parameters
tc int: an int value for the bitset.

Throws
SocketException if there is an error setting the traffic class or type-of-service

See also:

supportedOptions

Added in API level 33
public Set<SocketOption<?>> supportedOptions ()

Returns a set of the socket options supported by this socket. This method will continue to return the set of options even after the socket has been closed.

Returns
Set<SocketOption<?>> A set of the socket options supported by this socket. This set may be empty if the socket's DatagramSocketImpl cannot be created.