Java Reference
In-Depth Information
Mode()
method returns
true
if packets are not looped back and
false
if they are. (This
feels backward to me. I suspect this method was written by a programmer following the
ill-advised convention that defaults should always be true.)
If the system is looping packets back and you don't want it to, you'll need to recognize
the packets somehow and discard them. If the system is not looping the packets back
and you do want it to, store copies of the packets you send and inject them into your
internal data structures manually at the same time you send them. You can ask for the
behavior you want with
setLoopback()
, but you can't count on it.
Network interfaces
On a multihomed host, the
setInterface()
and
setNetworkInterface()
methods
choose the network interface used for multicast sending and receiving:
public
void
setInterface
(
InetAddress
address
)
throws
SocketException
public
InetAddress
getInterface
()
throws
SocketException
public
void
setNetworkInterface
(
NetworkInterface
interface
)
throws
SocketException
public
NetworkInterface
getNetworkInterface
()
throws
SocketException
The setter methods throw a
SocketException
if the argument is not the address of a
network interface on the local machine. It is unclear why the network interface is im‐
mutably set in the constructor for unicast
Socket
and
DatagramSocket
objects but is
variable and set with a separate method for
MulticastSocket
objects. To be safe, set the
interface immediately after constructing a
MulticastSocket
and don't change it there‐
after. Here's how you might use
setInterface()
:
try
{
InetAddress
ia
=
InetAddress
.
getByName
(
"www.ibiblio.org"
);
MulticastSocket
ms
=
new
MulticastSocket
(
2048
);
ms
.
setInterface
(
ia
);
// send and receive data...
}
catch
(
UnknownHostException
ue
)
{
System
.
err
.
println
(
ue
);
}
catch
(
SocketException
se
)
{
System
.
err
.
println
(
se
);
}
The
setNetworkInterface()
method serves the same purpose as the
setInter
face()
method; that is, it chooses the network interface used for multicast sending and
receiving. However, it does so based on the local name of a network interface such as
“eth0” (as encapsulated in a
NetworkInterface
object) rather than on the IP address
bound to that network interface (as encapsulated in an
InetAddress
object).
setNet
workInterface()
throws a
SocketException
if the
NetworkInterface
passed as an
argument is not a network interface on the local machine.
The
getNetworkInterface()
method returns a
NetworkInterface
object representing
the network interface on which this
MulticastSocket
is listening for data. If no network