Java.net.MulticastSocket class in Java

This class is used for sending and receiving multicast IP packets. It extends DatagramSocket class and provides additional functionality for joining groups. A message sent to the group IP address will be received by all the clients who have joined the group. This must be kept in mind that for sending packets to the group, datagram socket doesn’t have to join the group but for receiving the packets addressed to the group, it must join the group. This class provides various methods for controlling the flow of multicast packets like setting the ttl, network interface to use etc, along with the major functions of joining and leaving a group.

Constructors :

  1. public MulticastSocket() : Creates a multicast socket. When using this constructor, we have to explicitly set all the fields such as group address, port number etc.
    Syntax :public MulticastSocket() 
  2. public MulticastSocket(int port) : Creates a multicast socket bound on the port specified.
    Syntax :public MulticastSocket(int port) 
    Parameters : 
    port : port number to bind this socket to
    
  3. public MulticastSocket(SocketAddress bindaddr) : Creates a multicast socket and binds it to specified socket address. Creates an unbound socket if address is null.
    Syntax :public MulticastSocket(SocketAddress bindaddr) 
    Parameters : 
    bindaddr : Socket address to bind this socket to
    

Methods :

  1. setTTL (deprecated): Used to set the time to live for the packets sent from this multicast sockets, restricting the scope of the packets. This method is deprecated as it uses byte as parameter for setting TTL. setTimeToLive() is used in its place.
    Syntax :public void setTTL(byte ttl)
    Parameters :
    ttl : the time to live
    
  2. setTimeToLive() : This method is used in place of above method as it uses int value as parameter. The specified ttl must be in range 0<=ttl<=255, otherwise illegalArgumentException will be thrown.
    Syntax :public void setTimeToLive(int ttl)
    Parameters :
    ttl : the time to live
    
  3. getTTL (deprecated): Used to get default time to live for the packets sent from this multicast sockets
    Syntax :public byte getTTL()
    
  4. getTimeToLive() : Returns the default time to live for the packets sent from this multicast socket.
    Syntax :public void getTimeToLive()
    
  5. joinGroup() : Used to join a multicast group. After joining the group, the client will start receiving all the packets sent to this multicast group address. This method takes InetAddress of the group to be joined. Further changes to its behavior can be made by using the setInterface() and setNetworkInterface() methods.
    Syntax :public void joinGroup(InetAddress mcastaddr)
                   throws IOException
    Parameters :
    mcastaddr : multicast address to join
    Throws :
    IOException : if error occurs while joining or the address is
    not a multicast address.
    
  6. Another overloaded method which also specifies the network interface to use while joining the group.

  7. Syntax :public void joinGroup(SocketAddress mcastaddr,
                 NetworkInterface netIf)
                   throws IOException
    Parameters :
    mcastaddr : multicast address to join
    netIf : network interface to use while joining
    Throws :
    IOException : if error occurs while joining or the address is
    not a multicast address.
    
  8. leaveGroup() : Used to leave a multicast group. After leaving the group, the client wont be able to receive the packets addressed to this group address.
    Syntax :public void leaveGroup(InetAddress mcastaddr)
                   throws IOException
    Parameters :
    mcastaddr : multicast address to leave
    Throws :
    IOException : if error occurs while leaving
    
  9. Another overloaded method for leaving the group which also allows for specification of network interface on which to leave the group.

  10. Syntax :public void leaveGroup(SocketAddress mcastaddr,
                 NetworkInterface netIf)
                   throws IOException
    Parameters :
    mcastaddr : multicast address to leave
    netIf : network interface on which to leave
    Throws :
    IOException : if error occurs while leaving
    
  11. setInterface() : Used to set the multicast network interface.
    Syntax :public void setInterface(InetAddress inf)
                      throws SocketException
    Parameters :
    inf : the inetaddress
    Throws :
    SocketException : if error in underlying protocol
    
  12. getInterface() : Returns the network interface used for multicast packets.
    Syntax :public InetAddress getInterface()
                             throws SocketException
    Throws :
    SocketException : if error in underlying protocol
    
  13. setNetworkInterface() : Used to specify the network interface for outgoing packets on this socket.
    Syntax :public void setNetworkInterface(NetworkInterface netIf)
                             throws SocketException
    Parameters :
    netIf : network interface to use
    Throws :
    SocketException : if error in underlying protocol
    
  14. getNetworkInterface() : Returns the network interface for outgoing packets on this socket.
    Syntax :public NetworkInterface getNetworkInterface()
                                         throws SocketException
    Throws :
    SocketException : if error in underlying protocol
    
  15. setLoopbackMode() : Used to specify whether the multicast packets will be looped back to local socket.
    Syntax : public void setLoopbackMode(boolean disable)
                         throws SocketException
    Parameters :
    disable : true or false
    
  16. getLoopbackMode() : Returns the setting for loopback mode.
    Syntax : public vboolean getLoopbackMode()
                         throws SocketException
    
  17. send() (deprecated): Used to send the packet to the multicast group. It allows for specification of ttl for the outgoing packet other than the default value specified using setTimeToLive() method. It does not alter this value but uses the specified value only for the current packet. The following lines of code should be used in place of this method.
    int ttl=msock.getTimeToLive();
    msock.setTimeToLive(newttl);
    msock.send(packet);
    msock.setTimetoLive(ttl);

    Syntax :public void send(DatagramPacket p,
                       byte ttl)
              throws IOException
    Parameters :
    p : datagram packet to send
    ttl : hte time to live
    Throws :
    IOException : If error occurs while setting the ttl
    

Java Implementation :

//Java program to illustrate various
//MulticastSocket class methods
import java.io.IOException;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class multisock 
{
    public static void main(String[] args) throws IOException 
    {
        
        MulticastSocket ms = new MulticastSocket();
        InetAddress ip = InetAddress.getByName("224.168.1.124");

        // setTTL() method
        // this method is deprecated and instead
        // use setTimeToLive() method
        // Un-commenting below line would throw
        // a warning as the method is deprecated
        ms.setTTL((byte) 25);

        // setTimeToLive() method, will override
        // setting by setTTL() method
        ms.setTimeToLive(20);

        // getTTL() method
        // deprecated, so use getTimeToLive() method instead
        System.out.println("TTL : " + ms.getTTL());

        // getTimeToLive() method
        System.out.println("Time to Live : " + 
                             ms.getTimeToLive());

        NetworkInterface nif = NetworkInterface.getByIndex(1);
        Enumeration<InetAddress> enu = nif.getInetAddresses();
        InetAddress intadd = enu.nextElement();

        // setInterface() method
        ms.setInterface(intadd);

        // getInterface() method
        System.out.println("Interface : " + ms.getInterface());

        // setNetworkInterface() method
        ms.setNetworkInterface(nif);

        // getNetworkInterface() method
        System.out.println("Network Inteface : " + 
                           ms.getNetworkInterface());

        // setLoopbackMode() method
        ms.setLoopbackMode(true);

        // getLoopbackMode() method
        System.out.println("Loopback mode : " + 
                            ms.getLoopbackMode());
    }

}

Output :

TTL : 20
Time to Live : 20
Interface : /127.0.0.1
Network Inteface : name:lo (Software Loopback Interface 1)
Loopback mode : true

For a detailed implementation of a multicast socket application with methods to joinGroup() and send() packets, please refer to A group chat application in java

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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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 contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.