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 Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read