Java Reference
In-Depth Information
try {
InetAddress ia = InetAddress . getByName ( "experiment.mcast.net" );
byte [] data = "Here's some multicast data\r\n" . getBytes ();
int port = 4000 ;
DatagramPacket dp = new DatagramPacket ( data , data . length , ia , port );
MulticastSocket ms = new MulticastSocket ();
ms . send ( dp );
} catch ( IOException ex ) {
System . err . println ( ex );
}
By default, multicast sockets uses a TTL of 1 (that is, packets don't travel outside the
local subnet). However, you can change this setting for an individual packet by passing
an integer from 0 to 255 as the first argument to the constructor.
The setTimeToLive() method sets the default TTL value used for packets sent from
the socket using the send(DatagramPacket dp) method inherited from DatagramSock
et (as opposed to the send(DatagramPacket dp, byte ttl) method in Multicast
Socket ). The getTimeToLive() method returns the default TTL value of the Multi
castSocket :
public void setTimeToLive ( int ttl ) throws IOException
public int getTimeToLive () throws IOException
For example, this code fragment sets a TTL of 64:
try {
InetAddress ia = InetAddress . getByName ( "experiment.mcast.net" );
byte [] data = "Here's some multicast data\r\n" . getBytes ();
int port = 4000 ;
DatagramPacket dp = new DatagramPacket ( data , data . length , ia , port );
MulticastSocket ms = new MulticastSocket ();
ms . setTimeToLive ( 64 );
ms . send ( dp );
} catch ( IOException ex ) {
System . err . println ( ex );
}
Loopback mode
Whether or not a host receives the multicast packets it sends is platform dependent—
that is, whether or not they loop back. Passing true to setLoopback() indicates you
don't want to receive the packets you send. Passing false indicates you do want to
receive the packets you send:
public void setLoopbackMode ( boolean disable ) throws SocketException
public boolean getLoopbackMode () throws SocketException
However, this is only a hint. Implementations are not required to do as you request.
Because loopback mode may not be followed on all systems, it's important to check what
the loopback mode is if you're both sending and receiving packets. The getLoopback
Search WWH ::




Custom Search