Java.net.MulticastSocket class in Java
Last Updated :
19 May, 2022
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 : the time to live
Throws :
IOException : If error occurs while setting the ttl
Java Implementation :
Java
//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 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 java
References :
Official Java Documentation
Similar Reads
java.net.Socket Class in Java
The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class h
5 min read
java.net.SocketOption Class in Java
The java.net.SocketOption is a socket option that is connected with a socket, as the set of channels packages is java.nio.channels.NetworkChannel that this interface has defined the setOption as well as the getOption methods to set and query's the channels within its Socket Options. --> java.net
5 min read
java.net.SocketPermission Class in Java
The java.net.SocketPermisson class represents whether you have permission to access a network via sockets. A SocketPermission consists of a host and a set of actions. Class Declaration: public final class SocketPermission extends Permission implements SerializableConstructor: ConstructorDescriptionM
2 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction wi
5 min read
java.net.SocketImplFactory Class in Java
In Java, SocketImplFactory Class is an interface java.net.SocketImplFactory Class is defining a factory for SocketImpl instances, as this interface is usable by sockets classes to create the sockets execution that implements various policies through it. Interface java.net.SocketImplFactory Class is
2 min read
java.net.Proxy Class in Java
A proxy is an immutable object and type of tool or application or program or system, which helps to protect the information of its users and computers. It acts as a barrier between computer and internet users. A Proxy Object defines the Proxy settings to be used with a connection. Proxy servers are
3 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements Seria
4 min read
Java.io.ObjectInputStream Class in Java | Set 1
ObjectInputStream Class deserializes the primitive data and objects previously written by ObjectOutputStream. Both ObjectOutputStream and ObjectInputStream are used as it provides storage for graphs of object.It ensures that the object it is working for, matches the classes of JVM i.e Java Virtual M
9 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStrea
6 min read
Java.io.ObjectOutputStream Class in Java | Set 1
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. Only objects that support the java.io.Serializable in
9 min read