Code example for MulticastSocket

Methods: joinGroup, leaveGroup

0
        test_setNetworkInterfaceLjava_net_NetworkInterface(GOOD_IPv4);
    } 
 
    public void test_setNetworkInterfaceLjava_net_NetworkInterface_IPv6() throws Exception { 
        test_setNetworkInterfaceLjava_net_NetworkInterface(GOOD_IPv6);
    } 
 
    private void test_setNetworkInterfaceLjava_net_NetworkInterface(InetAddress group) throws IOException, InterruptedException {
        // set up the server and join the group 
        Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
        while (theInterfaces.hasMoreElements()) {
            NetworkInterface thisInterface = (NetworkInterface) theInterfaces.nextElement();
            if (thisInterface.getInetAddresses().hasMoreElements()) {
                if ((!((InetAddress) thisInterface.getInetAddresses().nextElement()).isLoopbackAddress())) {
                    int[] ports = Support_PortManager.getNextPortsForUDP(2);
                    int serverPort = ports[0];
                    int groupPort = ports[1];
 
                    MulticastServer server = new MulticastServer(group, serverPort);
                    server.start();
                    // give the server some time to start up 
                    Thread.sleep(1000);
 
                    // Send the packets on a particular interface. The 
                    // source address in the received packet 
                    // should be one of the addresses for the interface 
                    // set 
                    MulticastSocket mss = new MulticastSocket(groupPort);
                    mss.setNetworkInterface(thisInterface);
                    String msg = thisInterface.getName();
                    byte theBytes[] = msg.getBytes();
                    DatagramPacket sdp = new DatagramPacket(theBytes, theBytes.length, group, serverPort);
                    mss.send(sdp);
                    Thread.sleep(1000);
                    String receivedMessage = new String(server.rdp.getData(), 0, server.rdp.getLength());
                    assertEquals("Group member did not recv data sent on a specific interface", msg, receivedMessage);