class in Java

Datagram socket is a type of network socket which provides connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can also be used for sending and receiving broadcast messages. Datagram Sockets is the java’s mechanism for providing network communication via UDP instead of TCP.
Constructors :

  1. DatagramSocket() : Creates a datagramSocket and binds it to any available port on local machine. If this constructor is used, the OS would assign any port to this socket.
    Syntax :public DatagramSocket()
                   throws SocketException
    Throws :
    SocketException : if the socket could not be opened
  2. DatagramSocket(DatagramSocketImpl impl) : Creates an unbound datagram socket with given datagramImpl.
    Syntax :protected DatagramSocket(DatagramSocketImpl impl)
    Parameters :
    impl : instance of datagramScketImpl
  3. DatagramSocket(int port) : Creates and binds the datagram socket to the specified port. The socket will be bound to the a wildcard address chosen by kernel.
    Syntax : public DatagramSocket(int port)
                   throws SocketException
    Parameters : 
    port : port number to bind this socket to
  4. DatagramSocket(int port, InetAddress laddr) : Constructs a datagram socket and binds it to specified port and inetaddress.
    Syntax : public DatagramSocket(int port,
                  InetAddress laddr)
                   throws SocketException
    Parameters :
    port : local port to bind
    laddr : local address to bind
    Throws :
    SocketException : If the socket could not be opened
  5. DatagramSocket(SocketAddress bindaddr) : Constructs a new socket object and binds it the specified socket address(IP address+port number).
    Syntax :public DatagramSocket(SocketAddress bindaddr)
                   throws SocketException
    Parameters :
    bindaddr : socket address to bind to
    Throws : 
    SocketException : If socket could not be opened

Methods :

  1. bind() : Binds this socket to specified address and port number.
    Syntax : public void bind(SocketAddress addr)
    Parameters : 
    addr : socket address to bind to
  2. connect() : Connects to the specified address and port. After connecting to the remote host, this socket can send or receive packet from this remote host only. If a connection cannot be made to the specified remote host, the calls to send() or receive() would throw PortUnreachable Exception.
    Syntax :public void connect(InetAddress address,
               int port)
    Parameters :
    address : address of remote host
    port : port number of remote host

    Another overloaded method takes socket address as a parameter.

    Syntax :public void connect(SocketAddress address)
    Parameters :
    address : socket address of remote host
  3. disconnect() : Disconnects the socket. If the socket is not connected, then this method has no effect.
    Syntax :public void disconnect()
  4. isBound() : Returns a boolean value indicating whether this socket is bound or not.
    Syntax :public boolean isBound()

    isConnected() : Returns a boolean value indicating whether this socket is connected or not.

    Syntax :public boolean isConnected()
  5. isConnected() : Returns boolean value representing connection state of the socket. Please note that even after closing the socket, this method will continue to return true if this socket was connected prior to closing the socket.
    Syntax :public boolean isConnected()
  6. getInetAddress() : Returns the address to which this socket is connected.

    Syntax : public InetAddress getInetAddress()
  7. getPort() : Returns the port on the machine to which this socket is connected.
    Syntax : public int getPort()
  8. getRemoteSocketAddress() : Returns the socket address (IP address+port number) to which this socket is connected.
    Syntax : public SocketAddress getRemoteSocketAddress()
  9. getLocalSocketAddress() : Returns the address of the machine this socket is bound to, i.e. local machine socket address.
    public SocketAddress getLocalSocketAddress()
  10. send() : Sends a datagram packet from this socket. It should be noted that the information about the data to be sent, the address to which it is sent etc are all handled by packet itself.
    Syntax : public void send(DatagramPacket p)
    Parameters :
    p : packet to send
  11. receive() : It is used to receive the packet from a sender. When a packet is successfully received, the buffer of the packet is filled with received message. The packet also contains valuable information like the senders address and the port number. This method waits till a packet is received.

    Syntax : public void receive(DatagramPacket p)
    Parameters : 
    p : datagram packet into which incoming data is filled
  12. getLocalAddress() : Returns the local address to which this socket is bound.
    Syntax : public InetAddress getLocalAddress()
  13. getLocalPort() : Returns the port on local machine to which this socket is bound.
    Syntax : public int getLocalPort()
  14. setSOTimeout() : This is used to set the waiting time for receiving a datagram packet. As a call to receive() method blocks execution of the program indefinitely until a packet is received, this method can be used to limit that time. Once the time specified expires, is thrown.
    Syntax : public void setSoTimeout(int timeout)
    Parameters :
    timeout : time to wait
  15. getSoTimeout() : Returns the timeout parameter if specified, or 0 which indicates infinite time.
    Syntax : public int getSoTimeout()
  16. setSendBufferSize() : Used to set a limit to maximum size of the packet that can be sent from this socket. It sets the SO_SNDBUF option, which is used by network implementation to set size of underlying network buffers. Increasing the size may allow to queue the packets before sending when send rate is high.
    Syntax : public void setSendBufferSize(int size)
    Parameters : 
    size : size of send buffer to set
  17. Java Implementation :

    import java.util.Arrays;
    public class datasocket 
        public static void main(String[] args) throws IOException 
            // Constructor to create a datagram socket
            DatagramSocket socket = new DatagramSocket();
            InetAddress address = InetAddress.getByName("localhost");
            int port = 5252;
            byte buf[] = { 12, 13 };
            byte buf1[] = new byte[2];
            DatagramPacket dp = new DatagramPacket(buf, 2, address, port);
            DatagramPacket dptorec = new DatagramPacket(buf1, 2);
            // connect() method
            socket.connect(address, port);
            // isBound() method
            System.out.println("IsBound : " + socket.isBound());
            // isConnected() method
            System.out.println("isConnected : " + socket.isConnected());
            // getInetAddress() method
            System.out.println("InetAddress : " + socket.getInetAddress());
            // getPort() method
            System.out.println("Port : " + socket.getPort());
            // getRemoteSocketAddress() method
            System.out.println("Remote socket address : " + 
            // getLocalSocketAddress() method
            System.out.println("Local socket address : " + 
            // send() method
            System.out.println("...packet sent successfully....");
            // receive() method
            System.out.println("Received packet data : " + 
            // getLocalPort() method
            System.out.println("Local Port : " + socket.getLocalPort());
            // getLocalAddress() method
            System.out.println("Local Address : " + socket.getLocalAddress());
            // setSOTimeout() method
            // getSOTimeout() method
            System.out.println("SO Timeout : " + socket.getSoTimeout());

    To test the above program, a small server program is required for receiving the sent packet and for implementing receive() method. Its implementation is given below.

    public class smallserver {
        public static void main(String[] args) throws IOException {
            DatagramSocket ds = new DatagramSocket(5252);
            byte buf[] = new byte[2];
            byte send[] = { 13, 18 };
            DatagramPacket dp = new DatagramPacket(buf, 2);
            DatagramPacket senddp = new DatagramPacket(send, 2, 
                                   dp.getAddress(), dp.getPort());

    Output : On the client side

    IsBound : true
    isConnected : true
    InetAddress : localhost/
    Port : 5252
    Remote socket address : localhost/
    Local socket address : /
    packet sent successfully
    Received packet data : [13, 18]
    Local Port : 59498
    Local Address : /
    SO Timeout : 50
  18. getSendBufferSize() : Returns the value of SO_SNDBUF option of this socket.
    Syntax : public int getSendBufferSize()
  19. setReceiveBufferSize() : Used to set a limit to maximum size of the packet that is received on this socket. It sets the SO_RCVBUF option, which is used by network implementation to set size of underlying network buffers. Increasing the size may allow to queue the packets on receiving end when packets are sent faster than they are consumed.
    Syntax : public void setReceiveBufferSize(int size)
    Parameters : 
    size : size of receive buffer to set
  20. getReceiveBufferSize() : Returns the value of SO_RCVBUF option of this socket.
    Syntax : public int getReceiveBufferSize()
  21. setReuseAddress() : Sometimes it may be necessary to bind multiple sockets to the same address. Enabling this option enables other socket to bind to same address as this. It must be set before a call to bind() is made. It sets the value of SO_REUSEADDR socket option.
    Syntax : public void setReuseAddress(boolean on)
    Parameters : 
    on : true for enable, false otherwise
  22. getReuseAddress() : Returns boolean value indicating the setting of SO_REUSEADDR socket option.
    Syntax : public boolean getReuseAddress()
  23. setBroadcast() : Sets the value of SO_BROADCAST socket option.
    Syntax : public void setBroadcast(boolean on)
    Paramters : 
    on : true to allow bradcast, false otherwise
  24. getBroadcast() : Returns true if broadcast is enabled, false otherwise.
    Syntax : public boolean getBroadcast()
  25. setTrafficClass() : used to set the type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket. For more details about traffic class refer to Wikipedia
    Syntax : public void setTrafficClass(int tc)
    Parameters : 
    tc : int value of bitset, 0<=tc<=255
  26. getTrafficClass() : Gets traffic class or type of service from the IP header of packets sent from this socket.
    Syntax : public int getTrafficClass()
  27. close() : Closes this datagram socket. Any pending receive call will throw SocketException.
    Syntax : public void close()
  28. isClosed() : Returns the boolean value indicating if the socket is closed or not.

    Syntax : public boolean isClosed()
  29. getChannel() : Returns a data channel if any associated with this socket. More details about Datagram channels can be found on Official Java Documentation.
    Syntax : public DatagramChannel getChannel()
  30. setDatagramSocketImplFactory() : Sets the datagram socket implementation factory for the application.
    Syntax :public static void setDatagramSocketImplFactory(
                                     DatagramSocketImplFactory fac)
    Parameters : 
    fac - the desired factory.
    Throws : 
    IOException - if an I/O error occurs when setting the datagram socket factory.
    SocketException - if the factory is already defined.
  31. Java Implementation :

    public class datasock2 {
        public static void main(String[] args) throws IOException {
            // Constructor
            DatagramSocket socket = new DatagramSocket(1235);
            // setSendBufferSize() method
            // getSendBufferSize() method
            System.out.println("Send buffer size : " + 
            // setReceiveBufferSize() method
            // getReceiveBufferSize() method
            System.out.println("Receive buffer size : " + 
            // setReuseAddress() method
            // getReuseAddress() method
            System.out.println("SetReuse address : " + 
            // setBroadcast() method
            // getBroadcast() method
            System.out.println("setBroadcast : " + 
            // setTrafficClass() method
            // getTrafficClass() method
            System.out.println("Traffic class : " + 
            // getChannel() method
            System.out.println("Channel : " + 
            // setSocketImplFactory() method
            // close() method
            // isClosed() method
            System.out.println("Is Closed : " + socket.isClosed());

    Output :

    Send buffer size : 20
    Receive buffer size : 20
    SetReuse address : true
    setBroadcast : false
    Traffic class : 44
    Channel : null
    Is Closed : true

References : Official Java Documentation
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at to report any issue with the above content.

Recommended Posts:

0 Average Difficulty : 0/5.0
No votes yet.