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.

UDP broadcasts sends are always enabled on a DatagramSocket. 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.

@author
Pavani Diwanji
@version
1.96, 03/05/04
@since
JDK1.0
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
SocketExceptionif the socket could not be opened, or the socket could not bind to the specified local port.
SecurityExceptionif a security manager exists and its checkListen method doesn't allow the operation.
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
bindaddrlocal socket address to bind, or null for an unbound socket.
Throws
SocketExceptionif the socket could not be opened, or the socket could not bind to the specified local port.
SecurityExceptionif a security manager exists and its checkListen method doesn't allow the operation.
@since
1.4
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
portport to use.
Throws
SocketExceptionif the socket could not be opened, or the socket could not bind to the specified local port.
SecurityExceptionif a security manager exists and its checkListen method doesn't allow the operation.
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
portlocal port to use
laddrlocal address to bind
Throws
SocketExceptionif the socket could not be opened, or the socket could not bind to the specified local port.
SecurityExceptionif a security manager exists and its checkListen method doesn't allow the operation.
@since
JDK1.1
Binds this DatagramSocket to a specific address & 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
addrThe address & port to bind to.
Throws
SocketExceptionif any error happens during the bind, or if the socket is already bound.
SecurityExceptionif a security manager exists and its checkListen method doesn't allow the operation.
IllegalArgumentExceptionif addr is a SocketAddress subclass not supported by this socket.
@since
1.4
Closes this datagram socket.

Any thread currently blocked in {#link receive} upon this socket will throw a SocketException .

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

@revised
1.4
@spec
JSR-51
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.

A caller's permission to send and receive datagrams to a given host and port are checked at connect time. 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
addressthe remote address for the socket
portthe remote port for the socket.
Throws
IllegalArgumentExceptionif the address is null, or the port is out of range.
SecurityExceptionif the caller is not allowed to send datagrams to and receive datagrams from the address and port.
Connects this socket to a remote socket address (IP address + port number).

Parameters
addrThe remote address.
Throws
SocketExceptionif the connect fails
IllegalArgumentExceptionif addr is null or addr is a SocketAddress subclass not supported by this socket
@since
1.4
See Also
Disconnects the socket. This does nothing if the socket is not connected.
See Also
Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Parameters
objthe reference object with which to compare.
Return
true if this object is the same as the obj argument; false otherwise.
Tests if SO_BROADCAST is enabled.
Return
a boolean indicating whether or not SO_BROADCAST is enabled.
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
@since
1.4
Returns the unique java.nio.channels.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.

Return
the datagram channel associated with this datagram socket, or null if this socket was not created for a channel
@since
1.4
@spec
JSR-51
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Return
The java.lang.Class object that represents the runtime class of the object. The result is of type {@code Class} where X is the erasure of the static type of the expression on which getClass is called.
Returns the address to which this socket is connected. Returns null if the socket is not connected.
Return
the address to which this socket is connected.
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.

Return
the local address to which the socket is bound, or an InetAddress representing any local address if either the socket is not bound, or the security manager checkConnect method does not allow the operation
@since
1.1
Returns the port number on the local host to which this socket is bound.
Return
the port number on the local host to which this socket is bound.
Returns the address of the endpoint this socket is bound to, or null if it is not bound yet.
Return
a SocketAddress representing the local endpoint of this socket, or null if it is not bound yet.
@since
1.4
Returns the port for this socket. Returns -1 if the socket is not connected.
Return
the port to which this socket is connected.
Get value of the SO_RCVBUF option for this DatagramSocket, that is the buffer size used by the platform for input on this DatagramSocket.
Return
the value of the SO_RCVBUF option for this DatagramSocket
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
Returns the address of the endpoint this socket is connected to, or null if it is unconnected.
Return
a SocketAddress representing the remote endpoint of this socket, or null if it is not connected yet.
@since
1.4
Tests if SO_REUSEADDR is enabled.
Return
a boolean indicating whether or not SO_REUSEADDR is enabled.
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
@since
1.4
Get value of the SO_SNDBUF option for this DatagramSocket, that is the buffer size used by the platform for output on this DatagramSocket.
Return
the value of the SO_SNDBUF option for this DatagramSocket
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
Retrive setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity).
Return
the setting for SO_TIMEOUT
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
@since
JDK1.1
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 this method may return a different value than was previously set using the method on this DatagramSocket.

Return
the traffic class or type-of-service already set
Throws
SocketExceptionif there is an error obtaining the traffic class or type-of-service value.
@since
1.4
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

Return
a hash code value for this object.
Returns the binding state of the socket.
Return
true if the socket succesfuly bound to an address
@since
1.4
Returns whether the socket is closed or not.
Return
true if the socket has been closed
@since
1.4
Returns the connection state of the socket.
Return
true if the socket succesfuly connected to a server
@since
1.4
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
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
pthe DatagramPacket into which to place the incoming data.
Throws
IOExceptionif an I/O error occurs.
SocketTimeoutExceptionif setSoTimeout was previously called and the timeout has expired.
PortUnreachableExceptionmay be thrown if the socket is connected to a currently unreachable destination. Note, there is no guarantee that the exception will be thrown.
java.nio.channels.IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode.
@revised
1.4
@spec
JSR-51
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
pthe DatagramPacket to be sent.
Throws
IOExceptionif an I/O error occurs.
SecurityExceptionif a security manager exists and its checkMulticast or checkConnect method doesn't allow the send.
PortUnreachableExceptionmay be thrown if the socket is connected to a currently unreachable destination. Note, there is no guarantee that the exception will be thrown.
java.nio.channels.IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode.
@revised
1.4
@spec
JSR-51
Enable/disable SO_BROADCAST.
Parameters
onwhether or not to have broadcast turned on.
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
@since
1.4
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
facthe desired factory.
Throws
IOExceptionif an I/O error occurs when setting the datagram socket factory.
SocketExceptionif the factory is already defined.
SecurityExceptionif a security manager exists and its checkSetFactory method doesn't allow the operation.
Sets the SO_RCVBUF option to the specified value for this DatagramSocket. The SO_RCVBUF option is used by the 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 .

Increasing SO_RCVBUF may allow the network implementation to buffer multiple packets when packets arrive faster than are being received using .

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

Parameters
sizethe size to which to set the receive buffer size. This value must be greater than 0.
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
IllegalArgumentExceptionif the value is 0 or is negative.
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 java.net.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 .

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 ) is not defined.

Parameters
onwhether to enable or disable the
Throws
SocketExceptionif an error occurs enabling or disabling the SO_RESUEADDR socket option, or the socket is closed.
@since
1.4
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 .

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

Note: If 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
sizethe size to which to set the send buffer size. This value must be greater than 0.
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
IllegalArgumentExceptionif the value is 0 or is negative.
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
timeoutthe specified timeout in milliseconds.
Throws
SocketExceptionif there is an error in the underlying protocol, such as an UDP error.
@since
JDK1.1
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 octet with precedence and TOS fields as detailed in RFC 1349. The TOS field is bitset created by bitwise-or'ing values such the following :-

  • 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
tcan int value for the bitset.
Throws
SocketExceptionif there is an error setting the traffic class or type-of-service
@since
1.4
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())
 
Return
a string representation of the object.
Causes current thread to wait until another thread invokes the method or the method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until either another thread invokes the method or the method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor.

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         ... // Perform action appropriate to condition
     }
 
(For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001).

If the current thread is interrupted by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters
timeoutthe maximum time to wait in milliseconds.
Throws
IllegalArgumentExceptionif the value of timeout is negative.
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until another thread invokes the method or the method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:

 1000000*timeout+nanos

In all other respects, this method does the same thing as the method of one argument. In particular, wait(0, 0) means the same thing as wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout, nanos);
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Parameters
timeoutthe maximum time to wait in milliseconds.
nanosadditional time, in nanoseconds range 0-999999.
Throws
IllegalArgumentExceptionif the value of timeout is negative or the value of nanos is not in the range 0-999999.
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.