Java Reference
In-Depth Information
There is no networkwide broadcast address that can be used to send a message to all
hosts. To see why, consider the impact of a broadcast to every host on the Internet. Sending
a single datagram would result in a very, very large number of packet duplications by the
routers, and bandwidth would be consumed on each and every network. The consequences of
misuse (malicious or accidental) are too great, so the designers of IP left such an Internetwide
broadcast facility out on purpose.
Even so, local broadcast can be very useful. Often, it is used in state exchange for network
games where the players are all on the same local (broadcast) network. In Java, the code for
unicasting and broadcasting is the same. To play with broadcasting applications, simply run
SendUDP.java using a broadcast destination address. Run RecvUDP.java as you did before (except
that you can run several receivers at one time). Caveat: Some operating systems do not give
regular users permission to broadcast, in which case this will not work.
4.3.2 Multicast
As with broadcast, the main difference between multicast and unicast is the form of the
address. A multicast address identifies a set of receivers. The designers of IP allocated a range
of the address space (from 224.0.0.0 to 239.255.255.255) dedicated to multicast. With the
exception of a few reserved multicast addresses, a sender can send datagrams addressed
to any address in this range. In Java, multicast applications generally communicate using
an instance of MulticastSocket , a subclass of DatagramSocket . It is important to understand
that a MulticastSocket is actually a UDP socket ( DatagramSocket ), with some extra multicast-
specific attributes that can be controlled. Our next example implements the multicast version
of SendUDP.java (see page 57).
SendUDPMulticast.c
0 import java.net.*; // for MulticastSocket, DatagramPacket, and InetAddress
1 import java.io.*;
// for IOException
2
3 public class SendUDPMulticast {
4
5
public static void main(String args[]) throws Exception {
6
7
if ((args.length < 2) || (args.length > 3)) // Test for correct # of args
8
throw new IllegalArgumentException(
9
"Parameter(s): <Multicast Addr> <Port> [<TTL>]");
10
11
InetAddress destAddr = InetAddress.getByName(args[0]); // Destination address
12
if (!destAddr.isMulticastAddress()) // Test if multicast address
13
throw new IllegalArgumentException("Not a multicast address");
14
15
int destPort = Integer.parseInt(args[1]); // Destination port
 
Search WWH ::




Custom Search