MulticastSocketTest.java revision a99b695964e28a5906003d40db48cbd550fbcdf4
1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package tests.api.java.net;
19
20import dalvik.annotation.KnownFailure;
21import dalvik.annotation.TestTargetClass;
22import dalvik.annotation.TestLevel;
23import dalvik.annotation.TestTargetNew;
24
25import java.io.IOException;
26import java.net.BindException;
27import java.net.DatagramPacket;
28import java.net.Inet4Address;
29import java.net.Inet6Address;
30import java.net.InetAddress;
31import java.net.InetSocketAddress;
32import java.net.MulticastSocket;
33import java.net.NetworkInterface;
34import java.net.SocketAddress;
35import java.net.SocketException;
36import java.net.UnknownHostException;
37import java.security.Permission;
38import java.util.Enumeration;
39
40import tests.support.Support_NetworkInterface;
41import tests.support.Support_PortManager;
42
43@TestTargetClass(MulticastSocket.class)
44public class MulticastSocketTest extends SocketTestCase {
45
46    Thread t;
47
48    MulticastSocket mss;
49
50    MulticastServer server;
51
52    // private member variables used for tests
53    boolean atLeastOneInterface = false;
54
55    boolean atLeastTwoInterfaces = false;
56
57    private NetworkInterface networkInterface1 = null;
58
59    private NetworkInterface networkInterface2 = null;
60
61    private NetworkInterface IPV6networkInterface1 = null;
62
63    static class MulticastServer extends Thread {
64
65        public MulticastSocket ms;
66
67        boolean running = true;
68
69        volatile public byte[] rbuf = new byte[512];
70
71        volatile DatagramPacket rdp = null;
72
73        public void run() {
74            try {
75                while (running) {
76                    try {
77                        ms.receive(rdp);
78                    } catch (java.io.InterruptedIOException e) {
79                        Thread.yield();
80                    }
81                    ;
82                }
83                ;
84            } catch (java.io.IOException e) {
85                System.out.println("Multicast server failed: " + e);
86            } finally {
87                ms.close();
88            }
89        }
90
91        public synchronized void leaveGroup(InetAddress aGroup)
92                throws java.io.IOException {
93            ms.leaveGroup(aGroup);
94        }
95
96        public void stopServer() {
97            running = false;
98        }
99
100        public MulticastServer(InetAddress anAddress, int aPort)
101                throws java.io.IOException {
102            rbuf = new byte[512];
103            rbuf[0] = -1;
104            rdp = new DatagramPacket(rbuf, rbuf.length);
105            ms = new MulticastSocket(aPort);
106            ms.setSoTimeout(2000);
107            ms.joinGroup(anAddress);
108        }
109
110        public MulticastServer(SocketAddress anAddress, int aPort,
111                NetworkInterface netInterface) throws java.io.IOException {
112            rbuf = new byte[512];
113            rbuf[0] = -1;
114            rdp = new DatagramPacket(rbuf, rbuf.length);
115            ms = new MulticastSocket(aPort);
116            ms.setSoTimeout(2000);
117            ms.joinGroup(anAddress, netInterface);
118        }
119    }
120
121    /**
122     * @tests java.net.MulticastSocket#MulticastSocket()
123     */
124    @TestTargetNew(
125        level = TestLevel.SUFFICIENT,
126        notes = "IOException exception checking missed.",
127        method = "MulticastSocket",
128        args = {}
129    )
130    public void test_Constructor() throws IOException {
131        // regression test for 497
132        MulticastSocket s = new MulticastSocket();
133        // regression test for Harmony-1162
134        assertTrue(s.getReuseAddress());
135
136        SecurityManager sm = new SecurityManager() {
137
138            public void checkPermission(Permission perm) {
139            }
140
141            public void checkListen(int port) {
142                throw new SecurityException();
143            }
144        };
145
146        SecurityManager oldSm = System.getSecurityManager();
147        System.setSecurityManager(sm);
148        try {
149            new MulticastSocket();
150            fail("SecurityException should be thrown.");
151        } catch (SecurityException e) {
152            // expected
153        } catch (SocketException e) {
154            fail("SocketException was thrown.");
155        } catch (IOException e) {
156            fail("IOException was thrown.");
157            e.printStackTrace();
158        } finally {
159            System.setSecurityManager(oldSm);
160        }
161    }
162
163    /**
164     * @tests java.net.MulticastSocket#MulticastSocket(int)
165     */
166    @TestTargetNew(
167        level = TestLevel.SUFFICIENT,
168        notes = "IOException exception checking missed.",
169        method = "MulticastSocket",
170        args = {int.class}
171    )
172    public void test_ConstructorI() {
173        // Test for method java.net.MulticastSocket(int)
174        // Used in tests
175        MulticastSocket dup = null;
176        try {
177            mss = new MulticastSocket();
178            int port = mss.getLocalPort();
179            dup = new MulticastSocket(port);
180            // regression test for Harmony-1162
181            assertTrue(dup.getReuseAddress());
182        } catch (IOException e) {
183            fail("duplicate binding not allowed: " + e);
184        }
185
186
187
188        if (dup != null)
189            dup.close();
190
191        SecurityManager sm = new SecurityManager() {
192
193            public void checkPermission(Permission perm) {
194            }
195
196            public void checkListen(int port) {
197                throw new SecurityException();
198            }
199        };
200
201        SecurityManager oldSm = System.getSecurityManager();
202        System.setSecurityManager(sm);
203        try {
204            new MulticastSocket(1);
205            fail("SecurityException should be thrown.");
206        } catch (SecurityException e) {
207            // expected
208        } catch (SocketException e) {
209            fail("SocketException was thrown.");
210        } catch (IOException e) {
211            fail("IOException was thrown.");
212            e.printStackTrace();
213        } finally {
214            System.setSecurityManager(oldSm);
215        }
216    }
217
218    /**
219     * @tests java.net.MulticastSocket#getInterface()
220     */
221    @TestTargetNew(
222        level = TestLevel.COMPLETE,
223        notes = "",
224        method = "getInterface",
225        args = {}
226    )
227    @KnownFailure("No interfaces if there's no debugger connected")
228    public void test_getInterface() {
229        // Test for method java.net.InetAddress
230        // java.net.MulticastSocket.getInterface()
231        assertTrue("Used for testing.", true);
232
233        int groupPort = Support_PortManager.getNextPortForUDP();
234        try {
235            if (atLeastOneInterface) {
236                // validate that we get the expected response when one was not
237                // set
238                mss = new MulticastSocket(groupPort);
239                String preferIPv4StackValue = System
240                        .getProperty("java.net.preferIPv4Stack");
241                String preferIPv6AddressesValue = System
242                        .getProperty("java.net.preferIPv6Addresses");
243                if (((preferIPv4StackValue == null) || preferIPv4StackValue
244                        .equalsIgnoreCase("false"))
245                        && (preferIPv6AddressesValue != null)
246                        && (preferIPv6AddressesValue.equals("true"))) {
247                    // we expect an IPv6 ANY in this case
248                    assertTrue("inet Address returned when not set:"
249                            + mss.getInterface().toString(), InetAddress
250                            .getByName("::0").equals(mss.getInterface()));
251                } else {
252                    // we expect an IPv4 ANY in this case
253                    assertNotNull("inet Address returned when not set:",
254                            mss.getInterface());
255                }
256
257                // validate that we get the expected response when we set via
258                // setInterface
259                Enumeration addresses = networkInterface1.getInetAddresses();
260                if (addresses != null) {
261                    InetAddress firstAddress = (InetAddress) addresses
262                            .nextElement();
263                    mss.setInterface(firstAddress);
264                    assertTrue(
265                            "getNetworkInterface did not return interface set " +
266                            "by setInterface.  Expected:"
267                                    + firstAddress + " Got:"
268                                    + mss.getInterface(), firstAddress
269                                    .equals(mss.getInterface()));
270
271                    groupPort = Support_PortManager.getNextPortForUDP();
272                    mss = new MulticastSocket(groupPort);
273                    mss.setNetworkInterface(networkInterface1);
274                    InetAddress addr = mss.getInterface();
275                    NetworkInterface if1 = NetworkInterface.getByInetAddress(addr);
276                    assertEquals(
277                            "getInterface did not return interface set by " +
278                            "setNeworkInterface Expected: " + firstAddress
279                                    + "Got:" + mss.getInterface(),
280                                    networkInterface1, if1);
281                }
282                mss.close();
283                try {
284                    mss.getInterface();
285                    fail("SocketException was not thrown.");
286                } catch(SocketException ioe) {
287                    //expected
288                }
289            }
290        } catch (Exception e) {
291            fail("Exception during getInterface test: " + e.toString());
292        }
293    }
294
295    /**
296     * @throws IOException
297     * @tests java.net.MulticastSocket#getNetworkInterface()
298     */
299    @TestTargetNew(
300        level = TestLevel.COMPLETE,
301        notes = "",
302        method = "getNetworkInterface",
303        args = {}
304    )
305    @KnownFailure("No interfaces if there's no debugger connected")
306    public void test_getNetworkInterface() throws IOException {
307        int groupPort = Support_PortManager.getNextPortForUDP();
308        if (atLeastOneInterface) {
309            // validate that we get the expected response when one was not
310            // set
311            mss = new MulticastSocket(groupPort);
312            NetworkInterface theInterface = mss.getNetworkInterface();
313            assertNotNull(
314                    "network interface returned wrong network interface when " +
315                    "not set:"
316                            + theInterface, theInterface.getInetAddresses());
317            InetAddress firstAddress = (InetAddress) theInterface
318                    .getInetAddresses().nextElement();
319            // validate we the first address in the network interface is the
320            // ANY address
321            String preferIPv4StackValue = System
322                    .getProperty("java.net.preferIPv4Stack");
323            String preferIPv6AddressesValue = System
324                    .getProperty("java.net.preferIPv6Addresses");
325            if (((preferIPv4StackValue == null) || preferIPv4StackValue
326                    .equalsIgnoreCase("false"))
327                    && (preferIPv6AddressesValue != null)
328                    && (preferIPv6AddressesValue.equals("true"))) {
329                assertTrue(
330                        "network interface returned wrong network interface " +
331                        "when not set:"
332                                + theInterface, InetAddress.getByName("::0")
333                                .equals(firstAddress));
334
335            } else {
336                assertTrue(
337                        "network interface returned wrong network interface " +
338                        "when not set:"
339                                + theInterface, InetAddress
340                                .getByName("0.0.0.0").equals(firstAddress));
341            }
342
343            mss.setNetworkInterface(networkInterface1);
344            assertTrue(
345                    "getNetworkInterface did not return interface set by " +
346                    "setNeworkInterface",
347                    networkInterface1.equals(mss.getNetworkInterface()));
348
349            if (atLeastTwoInterfaces) {
350                mss.setNetworkInterface(networkInterface2);
351                assertTrue(
352                        "getNetworkInterface did not return network interface " +
353                        "set by second setNetworkInterface call",
354                        networkInterface2.equals(mss.getNetworkInterface()));
355            }
356
357            groupPort = Support_PortManager.getNextPortForUDP();
358            mss = new MulticastSocket(groupPort);
359            if (IPV6networkInterface1 != null) {
360                mss.setNetworkInterface(IPV6networkInterface1);
361                assertTrue(
362                        "getNetworkInterface did not return interface set " +
363                        "by setNeworkInterface",
364                        IPV6networkInterface1.equals(mss.getNetworkInterface()));
365            }
366
367            // validate that we get the expected response when we set via
368            // setInterface
369            groupPort = Support_PortManager.getNextPortForUDP();
370            mss = new MulticastSocket(groupPort);
371            Enumeration addresses = networkInterface1.getInetAddresses();
372            if (addresses != null) {
373                firstAddress = (InetAddress) addresses.nextElement();
374                mss.setInterface(firstAddress);
375                assertTrue(
376                        "getNetworkInterface did not return interface set " +
377                        "by setInterface",
378                        networkInterface1.equals(mss.getNetworkInterface()));
379            }
380
381            mss.close();
382            try {
383                mss.getNetworkInterface();
384                fail("SocketException was not thrown.");
385            } catch(SocketException ioe) {
386                //expected
387            }
388        }
389    }
390
391    /**
392     * @tests java.net.MulticastSocket#getTimeToLive()
393     */
394    @TestTargetNew(
395        level = TestLevel.COMPLETE,
396        notes = "",
397        method = "getTimeToLive",
398        args = {}
399    )
400    public void test_getTimeToLive() {
401        try {
402            mss = new MulticastSocket();
403            mss.setTimeToLive(120);
404            assertTrue("Returned incorrect 1st TTL: " + mss.getTimeToLive(),
405                    mss.getTimeToLive() == 120);
406            mss.setTimeToLive(220);
407            assertTrue("Returned incorrect 2nd TTL: " + mss.getTimeToLive(),
408                    mss.getTimeToLive() == 220);
409            mss.close();
410            try {
411                mss.getTimeToLive();
412                fail("IOException was not thrown.");
413            } catch(IOException ioe) {
414                //expected
415            }
416            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
417        } catch (Exception e) {
418            handleException(e, SO_MULTICAST);
419        }
420    }
421
422    /**
423     * @tests java.net.MulticastSocket#getTTL()
424     */
425    @TestTargetNew(
426        level = TestLevel.COMPLETE,
427        notes = "",
428        method = "getTTL",
429        args = {}
430    )
431    public void test_getTTL() {
432        // Test for method byte java.net.MulticastSocket.getTTL()
433
434        try {
435            mss = new MulticastSocket();
436            mss.setTTL((byte) 120);
437            assertTrue("Returned incorrect TTL: " + mss.getTTL(),
438                    mss.getTTL() == 120);
439            mss.close();
440            try {
441                mss.getTTL();
442                fail("IOException was not thrown.");
443            } catch(IOException ioe) {
444                //expected
445            }
446            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
447        } catch (Exception e) {
448            handleException(e, SO_MULTICAST);
449        }
450    }
451
452    /**
453     * @tests java.net.MulticastSocket#joinGroup(java.net.InetAddress)
454     */
455    @TestTargetNew(
456        level = TestLevel.COMPLETE,
457        notes = "",
458        method = "joinGroup",
459        args = {java.net.InetAddress.class}
460    )
461    public void test_joinGroupLjava_net_InetAddress() {
462        // Test for method void
463        // java.net.MulticastSocket.joinGroup(java.net.InetAddress)
464        String msg = null;
465        InetAddress group = null;
466        int[] ports = Support_PortManager.getNextPortsForUDP(2);
467        int groupPort = ports[0];
468        try {
469            group = InetAddress.getByName("224.0.0.3");
470            server = new MulticastServer(group, groupPort);
471            server.start();
472            Thread.sleep(1000);
473            msg = "Hello World";
474            mss = new MulticastSocket(ports[1]);
475            DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
476                    .length(), group, groupPort);
477            mss.joinGroup(group);
478            mss.send(sdp, (byte) 10);
479            Thread.sleep(1000);
480
481            SecurityManager sm = new SecurityManager() {
482
483                public void checkPermission(Permission perm) {
484                }
485
486                public void checkMulticast(InetAddress maddr) {
487                    throw new SecurityException();
488                }
489            };
490
491            SecurityManager oldSm = System.getSecurityManager();
492            System.setSecurityManager(sm);
493            try {
494                mss.joinGroup(group);
495                fail("SecurityException should be thrown.");
496            } catch (SecurityException e) {
497                // expected
498            } catch (SocketException e) {
499                fail("SocketException was thrown.");
500            } catch (IOException e) {
501                fail("IOException was thrown.");
502                e.printStackTrace();
503            } finally {
504                System.setSecurityManager(oldSm);
505            }
506
507            mss.close();
508            try {
509                mss.joinGroup(group);
510                fail("SocketException was not thrown.");
511            } catch(SocketException ioe) {
512                //expected
513            }
514        } catch (Exception e) {
515            fail("Exception during joinGroup test: " + e.toString());
516        }
517        assertTrue("Group member did not recv data: ", new String(server.rdp
518                .getData(), 0, server.rdp.getLength()).equals(msg));
519
520    }
521
522    /**
523     * @throws IOException
524     * @throws InterruptedException
525     * @tests java.net.MulticastSocket#joinGroup(java.net.SocketAddress,
526     *                                              java.net.NetworkInterface)
527     */
528    @TestTargetNew(
529        level = TestLevel.COMPLETE,
530        notes = "",
531        method = "joinGroup",
532        args = {java.net.SocketAddress.class, java.net.NetworkInterface.class}
533    )
534    @KnownFailure("Needs investigation")
535    public void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface()
536                                    throws IOException, InterruptedException {
537        // security manager that allows us to check that we only return the
538        // addresses that we should
539        class mySecurityManager extends SecurityManager {
540
541            public void checkPermission(Permission perm) {
542            }
543
544            public void checkMulticast(InetAddress address) {
545                throw new SecurityException("not allowed");
546            }
547        }
548
549        String msg = null;
550        InetAddress group = null;
551        SocketAddress groupSockAddr = null;
552        int[] ports = Support_PortManager.getNextPortsForUDP(2);
553        int groupPort = ports[0];
554        int serverPort = ports[1];
555
556            Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
557
558        // first validate that we handle a null group ok
559        mss = new MulticastSocket(groupPort);
560        try {
561            mss.joinGroup(null, null);
562            fail("Did not get exception when group was null");
563        } catch (IllegalArgumentException e) {
564        }
565
566        // now validate we get the expected error if the address specified
567        // is not a multicast group
568        try {
569            groupSockAddr = new InetSocketAddress(InetAddress
570                    .getByName("255.255.255.255"), groupPort);
571            mss.joinGroup(groupSockAddr, null);
572            fail("Did not get exception when group is not a multicast address");
573        } catch (IOException e) {
574        }
575
576        // now try to join a group if we are not authorized
577        // set the security manager that will make the first address not
578        // visible
579        System.setSecurityManager(new mySecurityManager());
580        try {
581            group = InetAddress.getByName("224.0.0.3");
582            groupSockAddr = new InetSocketAddress(group, groupPort);
583            mss.joinGroup(groupSockAddr, null);
584            fail("Did not get exception when joining group is not allowed");
585        } catch (SecurityException e) {
586        }
587        System.setSecurityManager(null);
588
589        if (atLeastOneInterface) {
590            // now validate that we can properly join a group with a null
591            // network interface
592            ports = Support_PortManager.getNextPortsForUDP(2);
593            groupPort = ports[0];
594            serverPort = ports[1];
595            mss = new MulticastSocket(groupPort);
596            mss.joinGroup(groupSockAddr, null);
597            mss.setTimeToLive(2);
598            Thread.sleep(1000);
599
600            // set up the server and join the group on networkInterface1
601            group = InetAddress.getByName("224.0.0.3");
602            groupSockAddr = new InetSocketAddress(group, groupPort);
603            server = new MulticastServer(groupSockAddr, serverPort,
604                    networkInterface1);
605            server.start();
606            Thread.sleep(1000);
607            msg = "Hello World";
608            DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
609                    .length(), group, serverPort);
610            mss.setTimeToLive(2);
611            mss.send(sdp);
612            Thread.sleep(1000);
613            // now vaildate that we received the data as expected
614            assertTrue("Group member did not recv data: ", new String(
615                    server.rdp.getData(), 0, server.rdp.getLength())
616                    .equals(msg));
617            server.stopServer();
618
619            // now validate that we handled the case were we join a
620            // different multicast address.
621            // verify we do not receive the data
622            ports = Support_PortManager.getNextPortsForUDP(2);
623            serverPort = ports[0];
624            server = new MulticastServer(groupSockAddr, serverPort,
625                    networkInterface1);
626            server.start();
627            Thread.sleep(1000);
628
629            groupPort = ports[1];
630            mss = new MulticastSocket(groupPort);
631            InetAddress group2 = InetAddress.getByName("224.0.0.4");
632            mss.setTimeToLive(10);
633            msg = "Hello World - Different Group";
634            sdp = new DatagramPacket(msg.getBytes(), msg.length(), group2,
635                    serverPort);
636            mss.send(sdp);
637            Thread.sleep(1000);
638            assertFalse(
639                    "Group member received data when sent on different group: ",
640                    new String(server.rdp.getData(), 0, server.rdp.getLength())
641                            .equals(msg));
642            server.stopServer();
643
644            // if there is more than one network interface then check that
645            // we can join on specific interfaces and that we only receive
646            // if data is received on that interface
647            if (atLeastTwoInterfaces) {
648                // set up server on first interfaces
649                NetworkInterface loopbackInterface = NetworkInterface
650                        .getByInetAddress(InetAddress.getByName("127.0.0.1"));
651
652                theInterfaces = NetworkInterface.getNetworkInterfaces();
653                while (theInterfaces.hasMoreElements()) {
654
655                    NetworkInterface thisInterface = (NetworkInterface)
656                                                    theInterfaces.nextElement();
657                    if ((thisInterface.getInetAddresses() != null && thisInterface
658                            .getInetAddresses().hasMoreElements())
659                            && (Support_NetworkInterface
660                                    .useInterface(thisInterface) == true)) {
661                        // get the first address on the interface
662
663                        // start server which is joined to the group and has
664                        // only asked for packets on this interface
665                        Enumeration addresses = thisInterface
666                                .getInetAddresses();
667
668                        NetworkInterface sendingInterface = null;
669                        boolean isLoopback = false;
670                        if (addresses != null) {
671                            InetAddress firstAddress = (InetAddress) addresses
672                                    .nextElement();
673                            if (firstAddress.isLoopbackAddress()) {
674                                isLoopback = true;
675                            }
676                            if (firstAddress instanceof Inet4Address) {
677                                group = InetAddress.getByName("224.0.0.4");
678                                if (networkInterface1.equals(NetworkInterface
679                                        .getByInetAddress(InetAddress
680                                                .getByName("127.0.0.1")))) {
681                                    sendingInterface = networkInterface2;
682                                } else {
683                                    sendingInterface = networkInterface1;
684                                }
685                            } else {
686                                // if this interface only seems to support
687                                // IPV6 addresses
688                                group = InetAddress
689                                        .getByName("FF01:0:0:0:0:0:2:8001");
690                                sendingInterface = IPV6networkInterface1;
691                            }
692                        }
693
694                        InetAddress useAddress = null;
695                        addresses = sendingInterface.getInetAddresses();
696                        if ((addresses != null)
697                                && (addresses.hasMoreElements())) {
698                            useAddress = (InetAddress) addresses.nextElement();
699                        }
700
701                        ports = Support_PortManager.getNextPortsForUDP(2);
702                        serverPort = ports[0];
703                        groupPort = ports[1];
704                        groupSockAddr = new InetSocketAddress(group, serverPort);
705                        server = new MulticastServer(groupSockAddr, serverPort,
706                                thisInterface);
707                        server.start();
708                        Thread.sleep(1000);
709
710                        // Now send out a package on interface
711                        // networkInterface 1. We should
712                        // only see the packet if we send it on interface 1
713                        InetSocketAddress theAddress = new InetSocketAddress(
714                                useAddress, groupPort);
715                        mss = new MulticastSocket(groupPort);
716                        mss.setNetworkInterface(sendingInterface);
717                        msg = "Hello World - Again" + thisInterface.getName();
718                        sdp = new DatagramPacket(msg.getBytes(), msg.length(),
719                                group, serverPort);
720                        mss.send(sdp);
721                        Thread.sleep(1000);
722                        if (thisInterface.equals(sendingInterface)) {
723                            assertTrue(
724                                    "Group member did not recv data when " +
725                                    "bound on specific interface: ",
726                                    new String(server.rdp.getData(), 0,
727                                            server.rdp.getLength()).equals(msg));
728                        } else {
729                            assertFalse(
730                                    "Group member received data on other " +
731                                    "interface when only asked for it on one " +
732                                    "interface: ",
733                                    new String(server.rdp.getData(), 0,
734                                            server.rdp.getLength()).equals(msg));
735                        }
736
737                        server.stopServer();
738                    }
739                }
740
741                // validate that we can join the same address on two
742                // different interfaces but not on the same interface
743                groupPort = Support_PortManager.getNextPortForUDP();
744                mss = new MulticastSocket(groupPort);
745                mss.joinGroup(groupSockAddr, networkInterface1);
746                mss.joinGroup(groupSockAddr, networkInterface2);
747                try {
748                    mss.joinGroup(groupSockAddr, networkInterface1);
749                    fail("Did not get expected exception when joining for " +
750                            "second time on same interface");
751                } catch (IOException e) {
752                }
753            }
754        }
755        System.setSecurityManager(null);
756    }
757
758    /**
759     * @tests java.net.MulticastSocket#leaveGroup(java.net.InetAddress)
760     */
761    @TestTargetNew(
762        level = TestLevel.COMPLETE,
763        notes = "",
764        method = "leaveGroup",
765        args = {java.net.InetAddress.class}
766    )
767    public void test_leaveGroupLjava_net_InetAddress() {
768        // Test for method void
769        // java.net.MulticastSocket.leaveGroup(java.net.InetAddress)
770        String msg = null;
771        boolean except = false;
772        InetAddress group = null;
773        int[] ports = Support_PortManager.getNextPortsForUDP(2);
774        int groupPort = ports[0];
775
776        try {
777            group = InetAddress.getByName("224.0.0.3");
778            msg = "Hello World";
779            mss = new MulticastSocket(ports[1]);
780            DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
781                    .length(), group, groupPort);
782            mss.send(sdp, (byte) 10);
783            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
784        } catch (Exception e) {
785            handleException(e, SO_MULTICAST);
786        }
787        try {
788            // Try to leave s group that mss is not a member of
789            mss.leaveGroup(group);
790        } catch (java.io.IOException e) {
791            // Correct
792            except = true;
793        }
794        assertTrue("Failed to throw exception leaving non-member group", except);
795
796        SecurityManager sm = new SecurityManager() {
797
798            public void checkPermission(Permission perm) {
799            }
800
801            public void checkMulticast(InetAddress maddr) {
802                throw new SecurityException();
803            }
804        };
805
806        SecurityManager oldSm = System.getSecurityManager();
807        System.setSecurityManager(sm);
808        try {
809            mss.leaveGroup(group);
810            fail("SecurityException should be thrown.");
811        } catch (SecurityException e) {
812            // expected
813        } catch (SocketException e) {
814            fail("SocketException was thrown.");
815        } catch (IOException e) {
816            fail("IOException was thrown.");
817            e.printStackTrace();
818        } finally {
819            System.setSecurityManager(oldSm);
820        }
821    }
822
823    /**
824     * @tests java.net.MulticastSocket#leaveGroup(java.net.SocketAddress,
825     * java.net.NetworkInterface)
826     */
827    @TestTargetNew(
828        level = TestLevel.COMPLETE,
829        notes = "",
830        method = "leaveGroup",
831        args = {java.net.SocketAddress.class, java.net.NetworkInterface.class}
832    )
833    public void test_leaveGroupLjava_net_SocketAddressLjava_net_NetworkInterface() {
834        // security manager that allows us to check that we only return the
835        // addresses that we should
836        class mySecurityManager extends SecurityManager {
837
838            public void checkPermission(Permission p) {
839            }
840
841            public void checkMulticast(InetAddress address) {
842                throw new SecurityException("not allowed");
843            }
844        }
845
846        String msg = null;
847        InetAddress group = null;
848        int groupPort = Support_PortManager.getNextPortForUDP();
849        SocketAddress groupSockAddr = null;
850        SocketAddress groupSockAddr2 = null;
851
852        try {
853            Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
854
855            // first validate that we handle a null group ok
856            mss = new MulticastSocket(groupPort);
857            try {
858                mss.leaveGroup(null, null);
859                fail("Did not get exception when group was null");
860            } catch (IllegalArgumentException e) {
861            }
862
863            // now validate we get the expected error if the address specified
864            // is not a multicast group
865            try {
866                group = InetAddress.getByName("255.255.255.255");
867                groupSockAddr = new InetSocketAddress(group, groupPort);
868                mss.leaveGroup(groupSockAddr, null);
869                fail("Did not get exception when group is not a " +
870                        "multicast address");
871            } catch (IOException e) {
872            }
873
874            // now try to leave a group if we are not authorized
875            // set the security manager that will make the first address not
876            // visible
877            System.setSecurityManager(new mySecurityManager());
878            try {
879                group = InetAddress.getByName("224.0.0.3");
880                groupSockAddr = new InetSocketAddress(group, groupPort);
881                mss.leaveGroup(groupSockAddr, null);
882                fail("Did not get exception when joining group is " +
883                        "not allowed");
884            } catch (SecurityException e) {
885            }
886            System.setSecurityManager(null);
887
888            if (atLeastOneInterface) {
889
890                // now test that we can join and leave a group successfully
891                groupPort = Support_PortManager.getNextPortForUDP();
892                mss = new MulticastSocket(groupPort);
893                groupSockAddr = new InetSocketAddress(group, groupPort);
894                mss.joinGroup(groupSockAddr, null);
895                mss.leaveGroup(groupSockAddr, null);
896                try {
897                    mss.leaveGroup(groupSockAddr, null);
898                    fail(
899                            "Did not get exception when trying to leave " +
900                            "group that was allready left");
901                } catch (IOException e) {
902                }
903
904                InetAddress group2 = InetAddress.getByName("224.0.0.4");
905                groupSockAddr2 = new InetSocketAddress(group2, groupPort);
906                mss.joinGroup(groupSockAddr, networkInterface1);
907                try {
908                    mss.leaveGroup(groupSockAddr2, networkInterface1);
909                    fail(
910                            "Did not get exception when trying to leave " +
911                            "group that was never joined");
912                } catch (IOException e) {
913                }
914
915                mss.leaveGroup(groupSockAddr, networkInterface1);
916                if (atLeastTwoInterfaces) {
917                    mss.joinGroup(groupSockAddr, networkInterface1);
918                    try {
919                        mss.leaveGroup(groupSockAddr, networkInterface2);
920                        fail(
921                                "Did not get exception when trying to leave " +
922                                "group on wrong interface joined on ["
923                                        + networkInterface1
924                                        + "] left on ["
925                                        + networkInterface2 + "]");
926                    } catch (IOException e) {
927                    }
928                }
929            }
930        } catch (Exception e) {
931            fail("Exception during leaveGroup test: " + e.toString());
932        } finally {
933            System.setSecurityManager(null);
934        }
935    }
936
937    /**
938     * @tests java.net.MulticastSocket#send(java.net.DatagramPacket, byte)
939     */
940    @TestTargetNew(
941        level = TestLevel.COMPLETE,
942        notes = "",
943        method = "send",
944        args = {java.net.DatagramPacket.class, byte.class}
945    )
946    public void test_sendLjava_net_DatagramPacketB() {
947        // Test for method void
948        // java.net.MulticastSocket.send(java.net.DatagramPacket, byte)
949
950        String msg = "Hello World";
951        InetAddress group = null;
952        int[] ports = Support_PortManager.getNextPortsForUDP(2);
953        int groupPort = ports[0];
954
955        try {
956            group = InetAddress.getByName("224.0.0.3");
957            mss = new MulticastSocket(ports[1]);
958            server = new MulticastServer(group, groupPort);
959            server.start();
960            Thread.sleep(200);
961            DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
962                    .length(), group, groupPort);
963            mss.send(sdp, (byte) 10);
964            Thread.sleep(1000);
965            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
966        } catch (Exception e) {
967            handleException(e, SO_MULTICAST);
968            try {
969                mss.close();
970            } catch (Exception ex) {
971            }
972
973            return;
974        }
975
976        DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
977                .length(), group, groupPort);
978
979
980        SecurityManager sm = new SecurityManager() {
981
982            public void checkPermission(Permission perm) {
983            }
984
985            public void checkConnect(String host,
986                    int port) {
987                throw new SecurityException();
988            }
989
990            public void checkMulticast(InetAddress maddr) {
991                throw new SecurityException();
992            }
993        };
994
995        SecurityManager oldSm = System.getSecurityManager();
996        System.setSecurityManager(sm);
997        try {
998            mss.send(sdp);
999            fail("SecurityException should be thrown.");
1000        } catch (SecurityException e) {
1001            // expected
1002        } catch (SocketException e) {
1003            fail("SocketException was thrown.");
1004        } catch (IOException e) {
1005            fail("IOException was thrown.");
1006            e.printStackTrace();
1007        } finally {
1008            System.setSecurityManager(oldSm);
1009        }
1010
1011        mss.close();
1012
1013        try {
1014            mss.send(sdp);
1015            fail("IOException should be thrown.");
1016        } catch(IOException ioe) {
1017            //expected
1018        }
1019
1020        byte[] data = server.rdp.getData();
1021        int length = server.rdp.getLength();
1022        assertTrue("Failed to send data. Received " + length, new String(data,
1023                0, length).equals(msg));
1024    }
1025
1026    /**
1027     * @tests java.net.MulticastSocket#setInterface(java.net.InetAddress)
1028     */
1029    @TestTargetNew(
1030        level = TestLevel.COMPLETE,
1031        notes = "",
1032        method = "setInterface",
1033        args = {java.net.InetAddress.class}
1034    )
1035    public void test_setInterfaceLjava_net_InetAddress() {
1036        // Test for method void
1037        // java.net.MulticastSocket.setInterface(java.net.InetAddress)
1038        // Note that the machine is not multi-homed
1039
1040        try {
1041            mss = new MulticastSocket();
1042            mss.setInterface(InetAddress.getLocalHost());
1043            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST_INTERFACE);
1044        } catch (Exception e) {
1045            //handleException(e, SO_MULTICAST_INTERFACE);
1046            return;
1047        }
1048        try {
1049            InetAddress theInterface = mss.getInterface();
1050            // under IPV6 we are not guarrenteed to get the same address back as
1051            // the address, all we should be guaranteed is that we get an
1052            // address on the same interface
1053            if (theInterface instanceof Inet6Address) {
1054                assertTrue(
1055                        "Failed to return correct interface IPV6",
1056                        NetworkInterface
1057                                .getByInetAddress(mss.getInterface())
1058                                .equals(
1059                                        NetworkInterface
1060                                                .getByInetAddress(theInterface)));
1061            } else {
1062                assertTrue("Failed to return correct interface IPV4 got:"
1063                        + mss.getInterface() + " excpeted: "
1064                        + InetAddress.getLocalHost(), mss.getInterface()
1065                        .equals(InetAddress.getLocalHost()));
1066            }
1067            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
1068        } catch (SocketException e) {
1069            handleException(e, SO_MULTICAST);
1070        } catch (UnknownHostException e) {
1071            fail("Exception during setInterface test: " + e.toString());
1072        }
1073
1074        // Regression test for Harmony-2410
1075        try {
1076            mss = new MulticastSocket();
1077            mss.setInterface(InetAddress.getByName("224.0.0.5"));
1078        } catch (UnknownHostException uhe) {
1079            fail("Unable to get InetAddress by name from '224.0.0.5' addr: "
1080                    + uhe.toString());
1081        } catch (SocketException se) {
1082            // expected
1083        } catch (IOException ioe) {
1084            handleException(ioe, SO_MULTICAST_INTERFACE);
1085            return;
1086        }
1087    }
1088
1089    /**
1090     * @throws IOException
1091     * @throws InterruptedException
1092     * @tests java.net.MulticastSocket#setNetworkInterface(
1093     *                                              java.net.NetworkInterface)
1094     */
1095    @TestTargetNew(
1096        level = TestLevel.COMPLETE,
1097        notes = "",
1098        method = "setNetworkInterface",
1099        args = {java.net.NetworkInterface.class}
1100    )
1101    @KnownFailure("No interfaces if there's no debugger connected")
1102    public void test_setNetworkInterfaceLjava_net_NetworkInterface()
1103                                    throws IOException, InterruptedException {
1104        String msg = null;
1105        InetAddress group = null;
1106        int[] ports = Support_PortManager.getNextPortsForUDP(2);
1107        int groupPort = ports[0];
1108        int serverPort = ports[1];
1109        if (atLeastOneInterface) {
1110            // validate that null interface is handled ok
1111            mss = new MulticastSocket(groupPort);
1112
1113            // this should through a socket exception to be compatible
1114            try {
1115                mss.setNetworkInterface(null);
1116                fail("No socket exception when we set then network " +
1117                        "interface with NULL");
1118            } catch (SocketException ex) {
1119            }
1120
1121            // validate that we can get and set the interface
1122            groupPort = Support_PortManager.getNextPortForUDP();
1123            mss = new MulticastSocket(groupPort);
1124            mss.setNetworkInterface(networkInterface1);
1125            assertTrue(
1126                    "Interface did not seem to be set by setNeworkInterface",
1127                    networkInterface1.equals(mss.getNetworkInterface()));
1128
1129            // set up the server and join the group
1130            group = InetAddress.getByName("224.0.0.3");
1131
1132            Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
1133            while (theInterfaces.hasMoreElements()) {
1134                NetworkInterface thisInterface = (NetworkInterface) theInterfaces
1135                        .nextElement();
1136                if (thisInterface.getInetAddresses() != null
1137                        && thisInterface.getInetAddresses().hasMoreElements()) {
1138                    if ((!((InetAddress) thisInterface.getInetAddresses()
1139                            .nextElement()).isLoopbackAddress())
1140                            &&
1141                            // for windows we cannot use these pseudo
1142                            // interfaces for the test as the packets still
1143                            // come from the actual interface, not the
1144                            // Pseudo interface that was set
1145                            (Support_NetworkInterface
1146                                    .useInterface(thisInterface) == true)) {
1147                        ports = Support_PortManager.getNextPortsForUDP(2);
1148                        serverPort = ports[0];
1149                        server = new MulticastServer(group, serverPort);
1150                        server.start();
1151                        // give the server some time to start up
1152                        Thread.sleep(1000);
1153
1154                        // Send the packets on a particular interface. The
1155                        // source address in the received packet
1156                        // should be one of the addresses for the interface
1157                        // set
1158                        groupPort = ports[1];
1159                        mss = new MulticastSocket(groupPort);
1160                        mss.setNetworkInterface(thisInterface);
1161                        msg = thisInterface.getName();
1162                        byte theBytes[] = msg.getBytes();
1163                        DatagramPacket sdp = new DatagramPacket(theBytes,
1164                                theBytes.length, group, serverPort);
1165                        mss.send(sdp);
1166                        Thread.sleep(1000);
1167                        String receivedMessage = new String(server.rdp
1168                                .getData(), 0, server.rdp.getLength());
1169                        assertTrue(
1170                                "Group member did not recv data when send on " +
1171                                "a specific interface: ",
1172                                receivedMessage.equals(msg));
1173                        assertTrue(
1174                                "Datagram was not received from expected " +
1175                                "interface expected["
1176                                        + thisInterface
1177                                        + "] got ["
1178                                        + NetworkInterface
1179                                                .getByInetAddress(server.rdp
1180                                                        .getAddress()) + "]",
1181                                NetworkInterface.getByInetAddress(
1182                                        server.rdp.getAddress()).equals(
1183                                        thisInterface));
1184
1185                        // stop the server
1186                        server.stopServer();
1187                    }
1188                }
1189            }
1190        }
1191    }
1192
1193    /**
1194     * @tests java.net.MulticastSocket#setTimeToLive(int)
1195     */
1196    @TestTargetNew(
1197        level = TestLevel.COMPLETE,
1198        notes = "",
1199        method = "setTimeToLive",
1200        args = {int.class}
1201    )
1202    public void test_setTimeToLiveI() {
1203        try {
1204            mss = new MulticastSocket();
1205            mss.setTimeToLive(120);
1206            assertTrue("Returned incorrect 1st TTL: " + mss.getTimeToLive(),
1207                    mss.getTimeToLive() == 120);
1208            mss.setTimeToLive(220);
1209            assertTrue("Returned incorrect 2nd TTL: " + mss.getTimeToLive(),
1210                    mss.getTimeToLive() == 220);
1211            mss.close();
1212            try {
1213                mss.setTimeToLive(1);
1214                fail("IOException was not thrown.");
1215            }catch(IOException ioe) {
1216                //expected
1217            }
1218
1219            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
1220        } catch (Exception e) {
1221            handleException(e, SO_MULTICAST);
1222        }
1223    }
1224
1225    /**
1226     * @tests java.net.MulticastSocket#setTTL(byte)
1227     */
1228    @TestTargetNew(
1229        level = TestLevel.COMPLETE,
1230        notes = "",
1231        method = "setTTL",
1232        args = {byte.class}
1233    )
1234    public void test_setTTLB() {
1235        // Test for method void java.net.MulticastSocket.setTTL(byte)
1236        try {
1237            mss = new MulticastSocket();
1238            mss.setTTL((byte) 120);
1239            assertTrue("Failed to set TTL: " + mss.getTTL(),
1240                    mss.getTTL() == 120);
1241
1242            mss.close();
1243            try {
1244                mss.setTTL((byte) 1);
1245                fail("IOException was not thrown.");
1246            } catch(IOException ioe) {
1247                //expected
1248            }
1249            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
1250        } catch (Exception e) {
1251            handleException(e, SO_MULTICAST);
1252        }
1253    }
1254
1255    /**
1256     * @tests java.net.MulticastSocket#MulticastSocket(java.net.SocketAddress)
1257     */
1258    @TestTargetNew(
1259        level = TestLevel.COMPLETE,
1260        notes = "",
1261        method = "MulticastSocket",
1262        args = {java.net.SocketAddress.class}
1263    )
1264    public void test_ConstructorLjava_net_SocketAddress() throws Exception {
1265        MulticastSocket ms = new MulticastSocket((SocketAddress) null);
1266        assertTrue("should not be bound", !ms.isBound() && !ms.isClosed()
1267                && !ms.isConnected());
1268        ms.bind(new InetSocketAddress(InetAddress.getLocalHost(),
1269                Support_PortManager.getNextPortForUDP()));
1270        assertTrue("should be bound", ms.isBound() && !ms.isClosed()
1271                && !ms.isConnected());
1272        ms.close();
1273        assertTrue("should be closed", ms.isClosed());
1274        ms = new MulticastSocket(new InetSocketAddress(InetAddress
1275                .getLocalHost(), Support_PortManager.getNextPortForUDP()));
1276        assertTrue("should be bound", ms.isBound() && !ms.isClosed()
1277                && !ms.isConnected());
1278        ms.close();
1279        assertTrue("should be closed", ms.isClosed());
1280        ms = new MulticastSocket(new InetSocketAddress("localhost",
1281                Support_PortManager.getNextPortForUDP()));
1282        assertTrue("should be bound", ms.isBound() && !ms.isClosed()
1283                && !ms.isConnected());
1284        ms.close();
1285        assertTrue("should be closed", ms.isClosed());
1286        boolean exception = false;
1287        try {
1288            ms = new MulticastSocket(new InetSocketAddress("unresolvedname",
1289                    Support_PortManager.getNextPortForUDP()));
1290        } catch (IOException e) {
1291            exception = true;
1292        }
1293        assertTrue("Expected IOException", exception);
1294
1295        // regression test for Harmony-1162
1296        InetSocketAddress addr = new InetSocketAddress("0.0.0.0", 0);
1297        MulticastSocket s = new MulticastSocket(addr);
1298        assertTrue(s.getReuseAddress());
1299
1300        InetSocketAddress isa = new InetSocketAddress(InetAddress
1301                .getLocalHost(), Support_PortManager.getNextPortForUDP());
1302
1303        SecurityManager sm = new SecurityManager() {
1304
1305            public void checkPermission(Permission perm) {
1306            }
1307
1308            public void checkListen(int port) {
1309                throw new SecurityException();
1310            }
1311        };
1312
1313        SecurityManager oldSm = System.getSecurityManager();
1314        System.setSecurityManager(sm);
1315        try {
1316            new MulticastSocket(isa);
1317            fail("SecurityException should be thrown.");
1318        } catch (SecurityException e) {
1319            // expected
1320        } catch (SocketException e) {
1321            fail("SocketException was thrown.");
1322        } catch (IOException e) {
1323            fail("IOException was thrown.");
1324            e.printStackTrace();
1325        } finally {
1326            System.setSecurityManager(oldSm);
1327        }
1328    }
1329
1330    /**
1331     * @tests java.net.MulticastSocket#getLoopbackMode()
1332     */
1333    @TestTargetNew(
1334        level = TestLevel.COMPLETE,
1335        notes = "",
1336        method = "getLoopbackMode",
1337        args = {}
1338    )
1339    public void test_getLoopbackMode() {
1340        try {
1341            MulticastSocket ms = new MulticastSocket((SocketAddress) null);
1342            assertTrue("should not be bound", !ms.isBound() && !ms.isClosed()
1343                    && !ms.isConnected());
1344            ms.getLoopbackMode();
1345            assertTrue("should not be bound", !ms.isBound() && !ms.isClosed()
1346                    && !ms.isConnected());
1347            ms.close();
1348            assertTrue("should be closed", ms.isClosed());
1349            try {
1350                ms.getLoopbackMode();
1351                fail("SocketException was not thrown.");
1352            } catch(SocketException ioe) {
1353                //expected
1354            }
1355            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_USELOOPBACK);
1356        } catch (IOException e) {
1357            handleException(e, SO_USELOOPBACK);
1358        }
1359    }
1360
1361    /**
1362     * @tests java.net.MulticastSocket#setLoopbackMode(boolean)
1363     */
1364    @TestTargetNew(
1365        level = TestLevel.COMPLETE,
1366        notes = "",
1367        method = "setLoopbackMode",
1368        args = {boolean.class}
1369    )
1370    public void test_setLoopbackModeZ() {
1371        try {
1372            MulticastSocket ms = new MulticastSocket();
1373            ms.setLoopbackMode(true);
1374            assertTrue("loopback should be true", ms.getLoopbackMode());
1375            ms.setLoopbackMode(false);
1376            assertTrue("loopback should be false", !ms.getLoopbackMode());
1377            ms.close();
1378            assertTrue("should be closed", ms.isClosed());
1379
1380            try {
1381                ms.setLoopbackMode(true);
1382                fail("SocketException was not thrown.");
1383            } catch(SocketException se) {
1384                //expected
1385            }
1386
1387            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_USELOOPBACK);
1388        } catch (IOException e) {
1389            handleException(e, SO_USELOOPBACK);
1390        }
1391    }
1392
1393    /**
1394     * @tests java.net.MulticastSocket#setLoopbackMode(boolean)
1395     */
1396    @TestTargetNew(
1397        level = TestLevel.ADDITIONAL,
1398        notes = "SocketException checking missed",
1399        method = "setLoopbackMode",
1400        args = {boolean.class}
1401    )
1402    public void test_setLoopbackModeSendReceive() throws IOException{
1403        final String ADDRESS = "224.1.2.3";
1404        final int PORT = Support_PortManager.getNextPortForUDP();
1405        final String message = "Hello, world!";
1406
1407        // test send receive
1408        MulticastSocket socket = null;
1409        try {
1410            // open a multicast socket
1411            socket = new MulticastSocket(PORT);
1412            socket.setLoopbackMode(false); // false indecates doing loop back
1413            socket.joinGroup(InetAddress.getByName(ADDRESS));
1414
1415            // send the datagram
1416            byte[] sendData = message.getBytes();
1417            DatagramPacket sendDatagram = new DatagramPacket(sendData, 0,
1418                    sendData.length, new InetSocketAddress(InetAddress
1419                            .getByName(ADDRESS), PORT));
1420            socket.send(sendDatagram);
1421
1422            // receive the datagram
1423            byte[] recvData = new byte[100];
1424            DatagramPacket recvDatagram = new DatagramPacket(recvData,
1425                    recvData.length);
1426            socket.setSoTimeout(5000); // prevent eternal block in
1427            // socket.receive()
1428            socket.receive(recvDatagram);
1429            String recvMessage = new String(recvData, 0, recvDatagram
1430                    .getLength());
1431            assertEquals(message, recvMessage);
1432        } finally {
1433            if (socket != null)
1434                socket.close();
1435        }
1436    }
1437
1438
1439    /**
1440     * @tests java.net.MulticastSocket#setReuseAddress(boolean)
1441     */
1442    @TestTargetNew(
1443        level = TestLevel.PARTIAL,
1444        notes = "SocketException checking missesd. Method inherited from " +
1445                "class java.net.DatagramSocket",
1446        method = "setReuseAddress",
1447        args = {boolean.class}
1448    )
1449    public void test_setReuseAddressZ() {
1450        try {
1451            // test case were we set it to false
1452            MulticastSocket theSocket1 = null;
1453            MulticastSocket theSocket2 = null;
1454            try {
1455                InetSocketAddress theAddress = new InetSocketAddress(
1456                        InetAddress.getLocalHost(), Support_PortManager
1457                                .getNextPortForUDP());
1458                theSocket1 = new MulticastSocket(null);
1459                theSocket2 = new MulticastSocket(null);
1460                theSocket1.setReuseAddress(false);
1461                theSocket2.setReuseAddress(false);
1462                theSocket1.bind(theAddress);
1463                theSocket2.bind(theAddress);
1464                fail(
1465                        "No exception when trying to connect to do " +
1466                        "duplicate socket bind with re-useaddr set to false");
1467            } catch (BindException e) {
1468
1469            }
1470            if (theSocket1 != null)
1471                theSocket1.close();
1472            if (theSocket2 != null)
1473                theSocket2.close();
1474
1475            // test case were we set it to true
1476            try {
1477                InetSocketAddress theAddress = new InetSocketAddress(
1478                        InetAddress.getLocalHost(), Support_PortManager
1479                                .getNextPortForUDP());
1480                theSocket1 = new MulticastSocket(null);
1481                theSocket2 = new MulticastSocket(null);
1482                theSocket1.setReuseAddress(true);
1483                theSocket2.setReuseAddress(true);
1484                theSocket1.bind(theAddress);
1485                theSocket2.bind(theAddress);
1486            } catch (Exception e) {
1487                fail(
1488                        "unexpected exception when trying to connect " +
1489                        "to do duplicate socket bind with re-useaddr set " +
1490                        "to true");
1491            }
1492            if (theSocket1 != null)
1493                theSocket1.close();
1494            if (theSocket2 != null)
1495                theSocket2.close();
1496
1497            // test the default case which we expect to be the same on all
1498            // platforms
1499            try {
1500                InetSocketAddress theAddress = new InetSocketAddress(
1501                        InetAddress.getLocalHost(), Support_PortManager
1502                                .getNextPortForUDP());
1503                theSocket1 = new MulticastSocket(null);
1504                theSocket2 = new MulticastSocket(null);
1505                theSocket1.bind(theAddress);
1506                theSocket2.bind(theAddress);
1507            } catch (BindException e) {
1508                fail(
1509                        "unexpected exception when trying to connect to do " +
1510                        "duplicate socket bind with re-useaddr left as default");
1511            }
1512            if (theSocket1 != null)
1513                theSocket1.close();
1514            if (theSocket2 != null)
1515                theSocket2.close();
1516            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1517        } catch (Exception e) {
1518            handleException(e, SO_REUSEADDR);
1519        }
1520    }
1521
1522    /**
1523     * Sets up the fixture, for example, open a network connection. This method
1524     * is called before a test is executed.
1525     */
1526    protected void setUp() {
1527
1528        Enumeration theInterfaces = null;
1529        try {
1530            theInterfaces = NetworkInterface.getNetworkInterfaces();
1531        } catch (Exception e) {
1532        }
1533
1534        // only consider interfaces that have addresses associated with them.
1535        // Otherwise tests don't work so well
1536        if (theInterfaces != null) {
1537
1538            atLeastOneInterface = false;
1539            while (theInterfaces.hasMoreElements()
1540                    && (atLeastOneInterface == false)) {
1541                networkInterface1 = (NetworkInterface) theInterfaces
1542                        .nextElement();
1543                if ((networkInterface1.getInetAddresses() != null)
1544                        && networkInterface1.getInetAddresses()
1545                                .hasMoreElements() &&
1546                        // we only want real interfaces
1547                        (Support_NetworkInterface
1548                                .useInterface(networkInterface1) == true)) {
1549                    atLeastOneInterface = true;
1550                }
1551            }
1552
1553            atLeastTwoInterfaces = false;
1554            if (theInterfaces.hasMoreElements()) {
1555                while (theInterfaces.hasMoreElements()
1556                        && (atLeastTwoInterfaces == false)) {
1557                    networkInterface2 = (NetworkInterface) theInterfaces
1558                            .nextElement();
1559                    if ((networkInterface2.getInetAddresses() != null)
1560                            && networkInterface2.getInetAddresses()
1561                                    .hasMoreElements() &&
1562                            // we only want real interfaces
1563                            (Support_NetworkInterface
1564                                    .useInterface(networkInterface2) == true)) {
1565                        atLeastTwoInterfaces = true;
1566                    }
1567                }
1568            }
1569
1570            Enumeration addresses;
1571
1572            // first the first interface that supports IPV6 if one exists
1573            try {
1574                theInterfaces = NetworkInterface.getNetworkInterfaces();
1575            } catch (Exception e) {
1576            }
1577            boolean found = false;
1578            while (theInterfaces.hasMoreElements() && !found) {
1579                NetworkInterface nextInterface = (NetworkInterface) theInterfaces
1580                        .nextElement();
1581                addresses = nextInterface.getInetAddresses();
1582                if (addresses != null) {
1583                    while (addresses.hasMoreElements()) {
1584                        InetAddress nextAddress = (InetAddress) addresses
1585                                .nextElement();
1586                        if (nextAddress instanceof Inet6Address) {
1587                            IPV6networkInterface1 = nextInterface;
1588                            found = true;
1589                            break;
1590                        }
1591                    }
1592                }
1593            }
1594        }
1595    }
1596
1597    /**
1598     * Tears down the fixture, for example, close a network connection. This
1599     * method is called after a test is executed.
1600     */
1601    protected void tearDown() {
1602
1603        if (t != null)
1604            t.interrupt();
1605        if (mss != null)
1606            mss.close();
1607        if (server != null)
1608            server.stopServer();
1609    }
1610}
1611