Code example for MulticastSocket

Methods: getInterface, setInterface, setNetworkInterface

0
        Enumeration addresses = networkInterface1.getInetAddresses();
        if (addresses.hasMoreElements()) {
            InetAddress firstAddress = (InetAddress) addresses.nextElement();
            mss.setInterface(firstAddress);
            assertEquals("getNetworkInterface did not return interface set by setInterface", firstAddress, mss.getInterface());
 
            groupPort = Support_PortManager.getNextPortForUDP();
            mss = new MulticastSocket(groupPort);
            mss.setNetworkInterface(networkInterface1);
            assertEquals("getInterface did not return interface set by setNetworkInterface", networkInterface1, NetworkInterface.getByInetAddress(mss.getInterface()));
        } 
 
        mss.close();
    } 
 
    public void test_getNetworkInterface() throws IOException { 
        int groupPort = Support_PortManager.getNextPortForUDP();
 
        // validate that we get the expected response when one was not set 
        MulticastSocket mss = new MulticastSocket(groupPort);
        NetworkInterface theInterface = mss.getNetworkInterface();
        assertTrue("network interface returned wrong network interface when not set:" + theInterface,
                theInterface.getInetAddresses().hasMoreElements());
        InetAddress firstAddress = (InetAddress) theInterface.getInetAddresses().nextElement();
        // validate we the first address in the network interface is the ANY address 
        assertTrue(firstAddress.isAnyLocalAddress());
 
        mss.setNetworkInterface(networkInterface1);
        assertEquals("getNetworkInterface did not return interface set by setNeworkInterface",
                networkInterface1, mss.getNetworkInterface());
 
        if (atLeastTwoInterfaces) {
            mss.setNetworkInterface(networkInterface2);
            assertEquals("getNetworkInterface did not return network interface set by second setNetworkInterface call",
                    networkInterface2, mss.getNetworkInterface());
        } 
        mss.close();
 
        groupPort = Support_PortManager.getNextPortForUDP();