Java.net.MulticastSocket class in Java - GeeksforGeeks

19 Dec, 2021
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 : 
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() 
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
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 :
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
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
getTTL (deprecated): Used to get default time to live for the packets sent from this multicast sockets
Syntax :public byte getTTL()
getTimeToLive() : Returns the default time to live for the packets sent from this multicast socket.
Syntax :public void getTimeToLive()
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.
         Another overloaded method which also specifies the network interface to use while joining the group.
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.
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
         Another overloaded method for leaving the group which also allows for specification of network interface on which to leave the group.
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
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
getInterface() : Returns the network interface used for multicast packets.
Syntax :public InetAddress getInterface()
                         throws SocketException
Throws :
SocketException : if error in underlying protocol
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
getNetworkInterface() : Returns the network interface for outgoing packets on this socket.
Syntax :public NetworkInterface getNetworkInterface()
                                     throws SocketException
Throws :
SocketException : if error in underlying protocol
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
getLoopbackMode() : Returns the setting for loopback mode.
Syntax : public vboolean getLoopbackMode()
                     throws SocketException
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
//Java program to illustrate various//MulticastSocket class methodsimport 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 Interface : " +                           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 Interface : 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 javaReferences : 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 write.geeksforgeeks.org or mail your article to review-team@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.
kalrap615
prachisoda1234
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java