Java Reference
In-Depth Information
16
17
int TTL;
// Time To Live for datagram
18
if (args.length == 3)
19
TTL = Integer.parseInt(args[2]);
20
else
21
TTL = 1; // Default TTL
22
23
ItemQuote quote = new ItemQuote(1234567890987654L, "5mm Super Widgets",
24
1000, 12999, true, false);
25
26
MulticastSocket sock = new MulticastSocket(); // Multicast socket to sending
27
sock.setTimeToLive(TTL);
// Set TTL for all datagrams
28
29
ItemQuoteEncoder encoder = new ItemQuoteEncoderText(); // Text encoding
30
byte[] codedQuote = encoder.encode(quote);
31
32
// Create and send a datagram
33
DatagramPacket message = new DatagramPacket(codedQuote, codedQuote.length,
34
destAddr, destPort);
35
sock.send(message);
36
37
sock.close();
38
}
39 }
SendUDPMulticast.c
The only significant differences between our unicast and multicast senders are that 1) we
verify that the given address is multicast, and 2) we set the initial Time To Live (TTL) value for
the multicast datagram. Every IP datagram contains a TTL, initialized to some default value and
decremented (usually by one) by each router that forwards the packet. When the TTL reaches
zero, the packet is discarded. By setting the initial value of the TTL, we limit the distance a
packet can travel from the sender. 2
Unlike broadcast, network multicast duplicates the message only to a specific set of
receivers. This set of receivers, called a multicast group , is identified by a shared multicast
(or group) address. Receivers need some mechanism to notify the network of their interest in
receiving data sent to a particular multicast address, so that the network can forward packets
to them. This notification, called joining a group , is accomplished with the joinGroup() method
of MulticastSocket . Our multicast receiver joins a specified group, receives and prints a single
multicast message from that group, and exits.
2 The rules for multicast TTL are actually not quite so simple. It is not necessarily the case that a packet
with TTL = 4 can travel four hops from the sender; however, it will not travel more than four hops.
Search WWH ::




Custom Search