OldDatagramSocketTest.java revision 7e6cee7a973ebf3cdc32638580d777d9b45088ae
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 libcore.java.net;
19
20import java.io.IOException;
21import java.io.InterruptedIOException;
22import java.net.BindException;
23import java.net.DatagramPacket;
24import java.net.DatagramSocket;
25import java.net.DatagramSocketImpl;
26import java.net.DatagramSocketImplFactory;
27import java.net.Inet4Address;
28import java.net.Inet6Address;
29import java.net.InetAddress;
30import java.net.InetSocketAddress;
31import java.net.NetworkInterface;
32import java.net.PortUnreachableException;
33import java.net.SocketAddress;
34import java.net.SocketException;
35import java.net.SocketTimeoutException;
36import java.net.UnknownHostException;
37import java.nio.channels.DatagramChannel;
38import java.nio.channels.IllegalBlockingModeException;
39import java.util.Date;
40import java.util.Vector;
41import tests.support.Support_Configuration;
42import tests.support.Support_PortManager;
43
44public class OldDatagramSocketTest extends junit.framework./*Socket*/TestCase {
45
46    java.net.DatagramSocket ds;
47
48    java.net.DatagramPacket dp;
49
50    DatagramSocket sds = null;
51
52    String retval;
53
54    String testString = "Test String";
55
56    boolean interrupted;
57
58    class DatagramServer extends Thread {
59
60        public DatagramSocket ms;
61
62        boolean running = true;
63
64        public volatile byte[] rbuf = new byte[512];
65
66        volatile DatagramPacket rdp = null;
67
68        public void run() {
69            try {
70                while (running) {
71                    try {
72                        ms.receive(rdp);
73                        // echo the packet back
74                        ms.send(rdp);
75                    } catch (java.io.InterruptedIOException e) {
76                        Thread.yield();
77                    }
78                    ;
79                }
80                ;
81            } catch (java.io.IOException e) {
82                System.out.println("DatagramServer server failed: " + e);
83            } finally {
84                ms.close();
85            }
86        }
87
88        public void stopServer() {
89            running = false;
90        }
91
92        public DatagramServer(int aPort, InetAddress address)
93                throws java.io.IOException {
94            rbuf = new byte[512];
95            rbuf[0] = -1;
96            rdp = new DatagramPacket(rbuf, rbuf.length);
97            ms = new DatagramSocket(aPort, address);
98            ms.setSoTimeout(2000);
99        }
100    }
101
102    public void test_Constructor() {
103        // Test for method java.net.DatagramSocket()
104        try {
105            ds = new java.net.DatagramSocket();
106        } catch (Exception e) {
107            fail("Could not create DatagramSocket : " + e.getMessage());
108        }
109
110        /*
111        SecurityManager sm = new SecurityManager() {
112
113            public void checkPermission(Permission perm) {
114            }
115
116            public void checkListen(int port) {
117                throw new SecurityException();
118            }
119        };
120
121        SecurityManager oldSm = System.getSecurityManager();
122        System.setSecurityManager(sm);
123        try {
124            new DatagramSocket();
125            fail("SecurityException should be thrown.");
126        } catch (SecurityException e) {
127            // expected
128        } catch (SocketException e) {
129            fail("SocketException was thrown.");
130        } finally {
131            System.setSecurityManager(oldSm);
132        }
133        */
134    }
135
136    public void test_ConstructorI() {
137        // Test for method java.net.DatagramSocket(int)
138        try {
139            int portNumber = Support_PortManager.getNextPortForUDP();
140            ds = new java.net.DatagramSocket(portNumber);
141            assertTrue("Created socket with incorrect port",
142                    ds.getLocalPort() == portNumber);
143        } catch (Exception e) {
144            fail("Could not create DatagramSocket : " + e.getMessage());
145        }
146
147        /*
148        SecurityManager sm = new SecurityManager() {
149
150            public void checkPermission(Permission perm) {
151            }
152
153            public void checkListen(int port) {
154                throw new SecurityException();
155            }
156        };
157
158        SecurityManager oldSm = System.getSecurityManager();
159        System.setSecurityManager(sm);
160        try {
161            new DatagramSocket(8080);
162            fail("SecurityException should be thrown.");
163        } catch (SecurityException e) {
164            // expected
165        } catch (SocketException e) {
166            fail("SocketException was thrown.");
167        } finally {
168            System.setSecurityManager(oldSm);
169        }
170        */
171
172        try {
173            DatagramSocket ds = new java.net.DatagramSocket(1);
174            if (!("root".equals(System.getProperty("user.name")))) {
175                fail("SocketException was not thrown.");
176            }
177        } catch (SocketException e) {
178            //expected
179        }
180
181    }
182
183    public void test_ConstructorILjava_net_InetAddress() {
184        // Test for method java.net.DatagramSocket(int, java.net.InetAddress)
185        try {
186            int portNumber = Support_PortManager.getNextPortForUDP();
187            ds = new java.net.DatagramSocket(portNumber, InetAddress
188                    .getLocalHost());
189            assertTrue("Created socket with incorrect port",
190                    ds.getLocalPort() == portNumber);
191            assertTrue("Created socket with incorrect address", ds
192                    .getLocalAddress().equals(InetAddress.getLocalHost()));
193        } catch (Exception e) {
194            fail("Could not create DatagramSocket : " + e.getMessage());
195        }
196
197        /*
198        SecurityManager sm = new SecurityManager() {
199
200            public void checkPermission(Permission perm) {
201            }
202
203            public void checkListen(int port) {
204                throw new SecurityException();
205            }
206        };
207
208        SecurityManager oldSm = System.getSecurityManager();
209        System.setSecurityManager(sm);
210        try {
211            new java.net.DatagramSocket(8080, InetAddress
212                    .getLocalHost());
213            fail("SecurityException should be thrown.");
214        } catch (SecurityException e) {
215            // expected
216        } catch (SocketException e) {
217            fail("SocketException was thrown.");
218        } catch (UnknownHostException e) {
219            fail("UnknownHostException was thrown.");
220        } finally {
221            System.setSecurityManager(oldSm);
222        }
223        */
224
225        try {
226            new java.net.DatagramSocket(1, InetAddress
227                    .getLocalHost());
228            fail("SocketException was not thrown.");
229        } catch(SocketException se) {
230            //expected
231        } catch (UnknownHostException e) {
232            fail("UnknownHostException was thrown.");
233        }
234    }
235
236    public void test_close() {
237        // Test for method void java.net.DatagramSocket.close()
238        try {
239            int portNumber = Support_PortManager.getNextPortForUDP();
240            ds = new java.net.DatagramSocket(portNumber);
241            dp = new DatagramPacket("Test String".getBytes(), 11, InetAddress
242                    .getLocalHost(), 0);
243            ds.close();
244            try {
245                ds.send(dp);
246                fail("IOException was not thrown.");
247            } catch(IOException ioe) {
248                //expected
249            }
250        } catch (Exception e) {
251            fail("Unexpected exception: " + e.getMessage());
252        }
253    }
254
255    public void test_connectLjava_net_InetAddressI() throws
256            UnknownHostException, SocketException {
257        try {
258            ds = new java.net.DatagramSocket();
259            InetAddress inetAddress = InetAddress.getLocalHost();
260            int portNumber = Support_PortManager.getNextPortForUDP();
261            ds.connect(inetAddress, portNumber);
262            assertTrue("Incorrect InetAddress", ds.getInetAddress().equals(
263                    inetAddress));
264            assertTrue("Incorrect Port", ds.getPort() == portNumber);
265            ds.disconnect();
266        } catch (Exception e) {
267            fail("Exception during test : " + e.getMessage());
268        }
269
270            System.out
271                    .println("Running test_connectLjava_net_InetAddressI" +
272                            "(DatagramSocketTest) with IPv6GlobalAddressJcl4: "
273                            + Support_Configuration.IPv6GlobalAddressJcl4);
274            try {
275                ds = new java.net.DatagramSocket();
276                InetAddress inetAddress = InetAddress
277                        .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
278                int portNumber = Support_PortManager.getNextPortForUDP();
279                ds.connect(inetAddress, portNumber);
280                assertTrue("Incorrect InetAddress", ds.getInetAddress().equals(
281                        inetAddress));
282                assertTrue("Incorrect Port", ds.getPort() == portNumber);
283                ds.disconnect();
284            } catch (Exception e) {
285                fail("Exception during test : " + e.getMessage());
286            }
287
288        try {
289            // Create a connected datagram socket to test
290            // PlainDatagramSocketImpl.peek()
291            InetAddress localHost = InetAddress.getLocalHost();
292            DatagramSocket ds = new DatagramSocket();
293            int port = ds.getLocalPort();
294            ds.connect(localHost, port);
295            DatagramPacket send = new DatagramPacket(new byte[10], 10,
296                    localHost, port);
297            ds.send(send);
298            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
299            ds.setSoTimeout(2000);
300            ds.receive(receive);
301            ds.close();
302            assertTrue("Wrong size: " + receive.getLength(), receive
303                    .getLength() == 10);
304            assertTrue("Wrong receiver", receive.getAddress().equals(localHost));
305        } catch (IOException e) {
306            fail("Unexpected IOException : " + e.getMessage());
307        }
308
309        class DatagramServer extends Thread {
310
311            public DatagramSocket ms;
312
313            boolean running = true;
314
315            public byte[] rbuf = new byte[512];
316
317            DatagramPacket rdp = null;
318
319            public void run() {
320                try {
321                    while (running) {
322                        try {
323                            ms.receive(rdp);
324                            // echo the packet back
325                            ms.send(rdp);
326                        } catch (java.io.InterruptedIOException e) {
327                            Thread.yield();
328                        }
329
330                    }
331
332                } catch (java.io.IOException e) {
333                    System.out.println("Multicast server failed: " + e);
334                } finally {
335                    ms.close();
336                }
337            }
338
339            public void stopServer() {
340                running = false;
341            }
342
343            public DatagramServer(int aPort, InetAddress address)
344                    throws java.io.IOException {
345                rbuf = new byte[512];
346                rbuf[0] = -1;
347                rdp = new DatagramPacket(rbuf, rbuf.length);
348                ms = new DatagramSocket(aPort, address);
349                ms.setSoTimeout(2000);
350            }
351        }
352
353        // validate that we get the PortUnreachable exception if we try to
354        // send a dgram to a server that is not running and then do a recv
355        try {
356            ds = new java.net.DatagramSocket();
357            InetAddress inetAddress = InetAddress.getLocalHost();
358            int portNumber = Support_PortManager.getNextPortForUDP();
359            ds.connect(inetAddress, portNumber);
360            DatagramPacket send = new DatagramPacket(new byte[10], 10);
361            ds.send(send);
362            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
363            ds.setSoTimeout(10000);
364            ds.receive(receive);
365            ds.close();
366            fail(
367                    "No PortUnreachableException when connected at native level on recv ");
368        } catch (Exception e) {
369            assertTrue(
370                    "Wrong exception when trying to connect at native level on recv: "
371                            + e.toString(),
372                    (e instanceof PortUnreachableException));
373        }
374
375        // validate that we can send/receive with datagram sockets connected at
376        // the native level
377        DatagramServer server = null;
378        int[] ports = Support_PortManager.getNextPortsForUDP(3);
379        int serverPortNumber = ports[0];
380        try {
381            InetAddress localHost = InetAddress.getLocalHost();
382            DatagramSocket ds = new DatagramSocket(ports[1]);
383            DatagramSocket ds2 = new DatagramSocket(ports[2]);
384
385            try {
386                server = new DatagramServer(serverPortNumber, localHost);
387                server.start();
388                Thread.sleep(1000);
389            } catch (Exception e) {
390                fail(
391                        "Failed to set up datagram server for native connected Dgram socket test ");
392            }
393
394            int port = ds.getLocalPort();
395            ds.connect(localHost, serverPortNumber);
396
397            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
398            DatagramPacket send = new DatagramPacket(sendBytes,
399                    sendBytes.length);
400            ds.send(send);
401            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
402            ds.setSoTimeout(2000);
403            ds.receive(receive);
404            ds.close();
405            assertTrue("Wrong size data received: " + receive.getLength(),
406                    receive.getLength() == sendBytes.length);
407            assertTrue("Wrong data received"
408                    + new String(receive.getData(), 0, receive.getLength())
409                    + ":" + new String(sendBytes), new String(
410                    receive.getData(), 0, receive.getLength())
411                    .equals(new String(sendBytes)));
412            assertTrue("Wrong receiver:" + receive.getAddress() + ":"
413                    + localHost, receive.getAddress().equals(localHost));
414        } catch (Exception e) {
415            fail(
416                    "Unexpected exception when sending data on dgram connected at native level:"
417                            + e.toString());
418        }
419
420        if (server != null) {
421            server.stopServer();
422        }
423
424        // validate that we can disconnect
425        try {
426            ds = new java.net.DatagramSocket();
427            InetAddress inetAddress = InetAddress.getLocalHost();
428            int portNumber = Support_PortManager.getNextPortForUDP();
429            ds.connect(inetAddress, portNumber);
430            ds.disconnect();
431            ds.close();
432        } catch (Exception e) {
433            assertTrue("Unexpected exception when trying to connect at native"
434                    + e.toString(), (e instanceof PortUnreachableException));
435        }
436
437        // validate that once connected we cannot send to another address
438        try {
439            ds = new java.net.DatagramSocket();
440            InetAddress inetAddress = InetAddress.getLocalHost();
441            int portNumber = Support_PortManager.getNextPortForUDP();
442            ds.connect(inetAddress, portNumber);
443            DatagramPacket send = new DatagramPacket(new byte[10], 10,
444                    inetAddress, portNumber + 1);
445            ds.send(send);
446            ds.close();
447            fail(
448                    "No Exception when trying to send to a different address on a connected socket ");
449        } catch (Exception e) {
450            assertTrue(
451                    "Wrong exception when trying to send to a different address on a connected socket: "
452                            + e.toString(),
453                    (e instanceof IllegalArgumentException));
454        }
455
456        // validate that we can connect, then disconnect, then connect then
457        // send/recv
458        server = null;
459        ports = Support_PortManager.getNextPortsForUDP(3);
460        serverPortNumber = ports[0];
461        try {
462            InetAddress localHost = InetAddress.getLocalHost();
463            DatagramSocket ds = new DatagramSocket(ports[1]);
464            DatagramSocket ds2 = new DatagramSocket(ports[2]);
465
466            try {
467                server = new DatagramServer(serverPortNumber, localHost);
468                server.start();
469                Thread.sleep(1000);
470            } catch (Exception e) {
471                fail(
472                        "Failed to set up datagram server for native connected Dgram socket test ");
473            }
474
475            int port = ds.getLocalPort();
476            ds.connect(localHost, serverPortNumber + 1);
477            ds.disconnect();
478            ds.connect(localHost, serverPortNumber);
479
480            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
481            DatagramPacket send = new DatagramPacket(sendBytes,
482                    sendBytes.length);
483            ds.send(send);
484            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
485            ds.setSoTimeout(2000);
486            ds.receive(receive);
487            ds.close();
488            assertTrue(
489                    "connect/disconnect/connect - Wrong size data received: "
490                            + receive.getLength(),
491                    receive.getLength() == sendBytes.length);
492            assertTrue("connect/disconnect/connect - Wrong data received"
493                    + new String(receive.getData(), 0, receive.getLength())
494                    + ":" + new String(sendBytes), new String(
495                    receive.getData(), 0, receive.getLength())
496                    .equals(new String(sendBytes)));
497            assertTrue("connect/disconnect/connect - Wrong receiver:"
498                    + receive.getAddress() + ":" + localHost, receive
499                    .getAddress().equals(localHost));
500        } catch (Exception e) {
501            fail(
502                    "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:"
503                            + e.toString());
504        }
505
506        if (server != null) {
507            server.stopServer();
508        }
509
510        // validate that we can connect/disconnect then send/recv to any address
511        server = null;
512        ports = Support_PortManager.getNextPortsForUDP(3);
513        serverPortNumber = ports[0];
514        try {
515            InetAddress localHost = InetAddress.getLocalHost();
516            DatagramSocket ds = new DatagramSocket(ports[1]);
517            DatagramSocket ds2 = new DatagramSocket(ports[2]);
518
519            try {
520                server = new DatagramServer(serverPortNumber, localHost);
521                server.start();
522                Thread.sleep(1000);
523            } catch (Exception e) {
524                fail(
525                        "Failed to set up datagram server for native connected Dgram socket test ");
526            }
527
528            int port = ds.getLocalPort();
529            ds.connect(localHost, serverPortNumber + 1);
530            ds.disconnect();
531
532            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
533            DatagramPacket send = new DatagramPacket(sendBytes,
534                    sendBytes.length, localHost, serverPortNumber);
535            ds.send(send);
536            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
537            ds.setSoTimeout(2000);
538            ds.receive(receive);
539            ds.close();
540            assertTrue("connect/disconnect - Wrong size data received: "
541                    + receive.getLength(),
542                    receive.getLength() == sendBytes.length);
543            assertTrue("connect/disconnect - Wrong data received"
544                    + new String(receive.getData(), 0, receive.getLength())
545                    + ":" + new String(sendBytes), new String(
546                    receive.getData(), 0, receive.getLength())
547                    .equals(new String(sendBytes)));
548            assertTrue("connect/disconnect - Wrong receiver:"
549                    + receive.getAddress() + ":" + localHost, receive
550                    .getAddress().equals(localHost));
551        } catch (Exception e) {
552            fail(
553                    "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:"
554                            + e.toString());
555        }
556
557        if (server != null) {
558            server.stopServer();
559        }
560
561        // validate that we can connect on an allready connected socket and then
562        // send/recv
563        server = null;
564        ports = Support_PortManager.getNextPortsForUDP(3);
565        serverPortNumber = ports[0];
566        try {
567            InetAddress localHost = InetAddress.getLocalHost();
568            DatagramSocket ds = new DatagramSocket(ports[1]);
569            DatagramSocket ds2 = new DatagramSocket(ports[2]);
570
571            try {
572                server = new DatagramServer(serverPortNumber, localHost);
573                server.start();
574                Thread.sleep(1000);
575            } catch (Exception e) {
576                fail(
577                        "Failed to set up datagram server for native connected Dgram socket test ");
578            }
579
580            int port = ds.getLocalPort();
581            ds.connect(localHost, serverPortNumber + 1);
582            ds.connect(localHost, serverPortNumber);
583
584            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
585            DatagramPacket send = new DatagramPacket(sendBytes,
586                    sendBytes.length);
587            ds.send(send);
588            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
589            ds.setSoTimeout(2000);
590            ds.receive(receive);
591            ds.close();
592            assertTrue("connect/connect - Wrong size data received: "
593                    + receive.getLength(),
594                    receive.getLength() == sendBytes.length);
595            assertTrue("connect/connect - Wrong data received"
596                    + new String(receive.getData(), 0, receive.getLength())
597                    + ":" + new String(sendBytes), new String(
598                    receive.getData(), 0, receive.getLength())
599                    .equals(new String(sendBytes)));
600            assertTrue("connect/connect - Wrong receiver:"
601                    + receive.getAddress() + ":" + localHost, receive
602                    .getAddress().equals(localHost));
603        } catch (Exception e) {
604            fail(
605                    "Unexpected exception when sending data on dgram connected at native level after connect/connect: "
606                            + e.toString());
607        }
608
609        if (server != null) {
610            server.stopServer();
611        }
612
613        // test for when we fail to connect at the native level. Even though we
614        // fail at the native level there is no way to return an exception so
615        // there should be no exception
616        try {
617            ds = new java.net.DatagramSocket();
618            byte[] addressBytes = { 0, 0, 0, 0 };
619            InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
620            int portNumber = Support_PortManager.getNextPortForUDP();
621            ds.connect(inetAddress, portNumber);
622        } catch (Exception e) {
623            fail(
624                    "Unexcpected exception when trying to connect at native level with bad address for signature with no exception to be returned: "
625                            + e.toString());
626        }
627
628            System.out
629                    .println("Running test_connectLjava_net_InetAddressI(DatagramSocketTest) with IPv6 address");
630            try {
631                ds = new java.net.DatagramSocket();
632                byte[] addressBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
633                        0, 0, 0 };
634                InetAddress inetAddress = InetAddress
635                        .getByAddress(addressBytes);
636                int portNumber = Support_PortManager.getNextPortForUDP();
637                ds.connect(inetAddress, portNumber);
638            } catch (Exception e) {
639                fail(
640                        "Unexcpected exception when trying to connect at native level with bad IPv6 address for signature with no exception to be returned: "
641                                + e.toString());
642            }
643    }
644
645    public void test_disconnect() {
646        try {
647            ds = new java.net.DatagramSocket();
648            InetAddress inetAddress = InetAddress.getLocalHost();
649            int portNumber = Support_PortManager.getNextPortForUDP();
650            ds.connect(inetAddress, portNumber);
651            ds.disconnect();
652            assertNull("Incorrect InetAddress", ds.getInetAddress());
653            assertEquals("Incorrect Port", -1, ds.getPort());
654        } catch (Exception e) {
655            fail("Exception during test : " + e.getMessage());
656        }
657
658            System.out
659                    .println("Running test_disconnect(DatagramSocketTest) with IPv6GlobalAddressJcl4: "
660                            + Support_Configuration.IPv6GlobalAddressJcl4);
661            try {
662                ds = new java.net.DatagramSocket();
663                InetAddress inetAddress = InetAddress
664                        .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
665                int portNumber = Support_PortManager.getNextPortForUDP();
666                ds.connect(inetAddress, portNumber);
667                ds.disconnect();
668                assertNull("Incorrect InetAddress", ds.getInetAddress());
669                assertEquals("Incorrect Port", -1, ds.getPort());
670            } catch (Exception e) {
671                fail("Exception during test : " + e.getMessage());
672            }
673    }
674
675    public void test_getInetAddress() {
676        Vector<InetAddress> ias = new Vector<InetAddress>();
677        try {
678            ias.add(InetAddress.getLocalHost());
679            ias.add(InetAddress
680                       .getByName(Support_Configuration.IPv6GlobalAddressJcl4));
681            ias.add(InetAddress
682                       .getByName(Support_Configuration.InetTestAddress2));
683            ias.add(InetAddress
684                    .getByName(Support_Configuration.InetTestAddress2));
685            ias.add(InetAddress
686                    .getByName(Support_Configuration.InetTestIP));
687        } catch(Exception e) {
688            fail("Unexpected exception was thrown: " + e.toString());
689        }
690
691        for(InetAddress ia:ias) {
692            int portNumber = Support_PortManager.getNextPortForUDP();
693            DatagramSocket ds = null;
694            try {
695                ds = new DatagramSocket();
696                ds.connect(ia, portNumber);
697                assertEquals(ia, ds.getInetAddress());
698                assertEquals("" + ia, ia, ds.getInetAddress());
699            } catch (SocketException e) {
700                fail("SocketException was thrown.");
701            } finally {
702                ds.disconnect();
703                ds.close();
704            }
705        }
706
707        try {
708            assertNull(new DatagramSocket().getInetAddress());
709         } catch (SocketException e) {
710             fail("SocketException was thrown.");
711         }
712
713    }
714
715    public void test_getLocalAddress() {
716        // Test for method java.net.InetAddress
717        // java.net.DatagramSocket.getLocalAddress()
718        InetAddress local = null;
719        try {
720            int portNumber = Support_PortManager.getNextPortForUDP();
721            local = InetAddress.getLocalHost();
722            ds = new java.net.DatagramSocket(portNumber, local);
723            assertTrue("Returned incorrect address. Got:"
724                    + ds.getLocalAddress()
725                    + " wanted: "
726                    + InetAddress.getByName(InetAddress.getLocalHost()
727                            .getHostName()), InetAddress.getByName(
728                    InetAddress.getLocalHost().getHostName()).equals(
729                    ds.getLocalAddress()));
730
731            // now check behavior when the ANY address is returned
732            DatagramSocket s = new DatagramSocket(0);
733            assertTrue("ANY address not IPv6: " + s.getLocalSocketAddress(),
734                    s.getLocalAddress() instanceof Inet6Address);
735            s.close();
736        } catch (Exception e) {
737            fail(
738                    "Exception during getLocalAddress: " + local + " - " + e);
739        }
740    }
741
742    public void test_getLocalPort() {
743        // Test for method int java.net.DatagramSocket.getLocalPort()
744        try {
745            int portNumber = Support_PortManager.getNextPortForUDP();
746            ds = new java.net.DatagramSocket(portNumber);
747            assertTrue("Returned incorrect port",
748                    ds.getLocalPort() == portNumber);
749        } catch (Exception e) {
750            fail("Exception during getLocalAddress : " + e.getMessage());
751        }
752    }
753
754    public void test_getPort() {
755        try {
756            int portNumber = Support_PortManager.getNextPortForUDP();
757            DatagramSocket theSocket = new DatagramSocket(portNumber);
758            assertEquals("Expected -1 for remote port as not connected",
759                    -1, theSocket.getPort());
760
761            // now connect the socket and validate that we get the right port
762            theSocket.connect(InetAddress.getLocalHost(), portNumber);
763            assertTrue("getPort returned wrong value:" + theSocket.getPort()
764                    + ":Expected:" + portNumber,
765                    theSocket.getPort() == portNumber);
766        } catch (Exception e) {
767            fail("unexpected exception during getPort test : " + e.getMessage());
768        }
769    }
770
771    public void test_getReceiveBufferSize() throws Exception {
772        int portNumber = Support_PortManager.getNextPortForUDP();
773        ds = new java.net.DatagramSocket(portNumber);
774        ds.setReceiveBufferSize(130);
775        assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
776        ds.close();
777        try {
778            ds.getReceiveBufferSize();
779            fail("SocketException was not thrown.");
780        } catch(SocketException se) {
781            //expected
782        }
783    }
784
785    public void test_getSendBufferSize() throws Exception {
786        int portNumber = Support_PortManager.getNextPortForUDP();
787        ds = new java.net.DatagramSocket(portNumber);
788        ds.setSendBufferSize(134);
789        assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
790        ds.close();
791        try {
792            ds.getSendBufferSize();
793            fail("SocketException was not thrown.");
794        } catch(SocketException se) {
795            //expected
796        }
797    }
798
799    public void test_getSoTimeout() throws Exception {
800        // Test for method int java.net.DatagramSocket.getSoTimeout()
801        int portNumber = Support_PortManager.getNextPortForUDP();
802        ds = new java.net.DatagramSocket(portNumber);
803        ds.setSoTimeout(100);
804        assertEquals("Returned incorrect timeout", 100, ds.getSoTimeout());
805        ds.close();
806        try {
807            ds.getSoTimeout();
808            fail("SocketException was not thrown.");
809        } catch(SocketException se) {
810            //expected
811        }
812    }
813
814    public void test_receiveLjava_net_DatagramPacket() throws Exception {
815        // Test for method void
816        // java.net.DatagramSocket.receive(java.net.DatagramPacket)
817
818        receive_oversize_java_net_DatagramPacket();
819        final int[] ports = Support_PortManager.getNextPortsForUDP(2);
820        final int portNumber = ports[0];
821
822        class TestDGRcv implements Runnable {
823            public void run() {
824                InetAddress localHost = null;
825                try {
826                    localHost = InetAddress.getLocalHost();
827                    Thread.sleep(1000);
828                    DatagramSocket sds = new DatagramSocket(ports[1]);
829                    DatagramPacket rdp = new DatagramPacket("Test String"
830                            .getBytes(), 11, localHost, portNumber);
831                    sds.send(rdp);
832                    sds.close();
833                } catch (Exception e) {
834                    throw new RuntimeException(e);
835                }
836            }
837        }
838
839        try {
840            new Thread(new TestDGRcv(), "DGSender").start();
841            ds = new java.net.DatagramSocket(portNumber);
842            ds.setSoTimeout(6000);
843            byte rbuf[] = new byte[1000];
844            DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
845            ds.receive(rdp);
846            ds.close();
847            assertTrue("Send/Receive failed to return correct data: "
848                    + new String(rbuf, 0, 11), new String(rbuf, 0, 11)
849                    .equals("Test String"));
850        } finally {
851            ds.close();
852        }
853        DatagramSocket socket = null;
854        try {
855            byte rbuf[] = new byte[1000];
856            DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
857            SocketAddress address = new InetSocketAddress(portNumber);
858            DatagramChannel channel = DatagramChannel.open();
859            channel.configureBlocking(false);
860            socket = channel.socket();
861            socket.receive(rdp);
862            fail("IllegalBlockingModeException was not thrown.");
863        } catch(IllegalBlockingModeException ibme) {
864            //expected
865        } finally {
866            socket.close();
867        }
868
869        try {
870            ds = new java.net.DatagramSocket(portNumber);
871            ds.setSoTimeout(1000);
872            byte rbuf[] = new byte[1000];
873            DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
874            ds.receive(rdp);
875            fail("SocketTimeoutException was not thrown.");
876        } catch(SocketTimeoutException te) {
877            //expected
878        } finally {
879            ds.close();
880        }
881
882
883
884        try {
885            interrupted = false;
886            final DatagramSocket ds = new DatagramSocket();
887            ds.setSoTimeout(12000);
888            Runnable runnable = new Runnable() {
889                public void run() {
890                    try {
891                        ds.receive(new DatagramPacket(new byte[1], 1));
892                    } catch (InterruptedIOException e) {
893                        interrupted = true;
894                    } catch (IOException e) {
895                        throw new RuntimeException(e);
896                    }
897                }
898            };
899            Thread thread = new Thread(runnable, "DatagramSocket.receive1");
900            thread.start();
901            try {
902                do {
903                    Thread.sleep(500);
904                } while (!thread.isAlive());
905            } catch (InterruptedException e) {
906            }
907            ds.close();
908            int c = 0;
909            do {
910                try {
911                    Thread.sleep(500);
912                } catch (InterruptedException e) {
913                }
914                if (interrupted) {
915                    fail("received interrupt");
916                }
917                if (++c > 4) {
918                    fail("read call did not exit");
919                }
920            } while (thread.isAlive());
921
922            interrupted = false;
923            int[] ports1 = Support_PortManager.getNextPortsForUDP(2);
924            final int portNum = ports[0];
925            final DatagramSocket ds2 = new DatagramSocket(ports[1]);
926            ds2.setSoTimeout(12000);
927            Runnable runnable2 = new Runnable() {
928                public void run() {
929                    try {
930                        ds2.receive(new DatagramPacket(new byte[1], 1,
931                                InetAddress.getLocalHost(), portNum));
932                    } catch (InterruptedIOException e) {
933                        interrupted = true;
934                    } catch (IOException e) {
935                    }
936                }
937            };
938            Thread thread2 = new Thread(runnable2, "DatagramSocket.receive2");
939            thread2.start();
940            try {
941                do {
942                    Thread.sleep(500);
943                } while (!thread2.isAlive());
944            } catch (InterruptedException e) {
945            }
946            ds2.close();
947            int c2 = 0;
948            do {
949                try {
950                    Thread.sleep(500);
951                } catch (InterruptedException e) {
952                }
953                if (interrupted) {
954                    fail("receive2 was interrupted");
955                }
956                if (++c2 > 4) {
957                    fail("read2 call did not exit");
958                }
959            } while (thread2.isAlive());
960
961            interrupted = false;
962            DatagramSocket ds3 = new DatagramSocket();
963            ds3.setSoTimeout(500);
964            Date start = new Date();
965            try {
966                ds3.receive(new DatagramPacket(new byte[1], 1));
967            } catch (InterruptedIOException e) {
968                interrupted = true;
969            }
970            ds3.close();
971            assertTrue("receive not interrupted", interrupted);
972            int delay = (int) (new Date().getTime() - start.getTime());
973            assertTrue("timeout too soon: " + delay, delay >= 490);
974        } catch (IOException e) {
975            fail("Unexpected IOException : " + e.getMessage());
976        }
977
978
979    }
980
981    public void test_sendLjava_net_DatagramPacket() throws Exception {
982        // Test for method void
983        // java.net.DatagramSocket.send(java.net.DatagramPacket)
984        int[] ports = Support_PortManager.getNextPortsForUDP(2);
985        final int portNumber = ports[0];
986
987        class TestDGSend implements Runnable {
988            Thread pThread;
989
990            public TestDGSend(Thread t) {
991                pThread = t;
992            }
993
994            public void run() {
995                try {
996                    byte[] rbuf = new byte[1000];
997
998                    sds = new DatagramSocket(portNumber);
999                    DatagramPacket sdp = new DatagramPacket(rbuf, rbuf.length);
1000                    sds.setSoTimeout(6000);
1001                    sds.receive(sdp);
1002                    retval = new String(rbuf, 0, testString.length());
1003                    pThread.interrupt();
1004                } catch (java.io.InterruptedIOException e) {
1005                    System.out.println("Recv operation timed out");
1006                    pThread.interrupt();
1007                    ds.close();
1008                    return;
1009                } catch (Exception e) {
1010                    System.out
1011                            .println("Failed to establish Dgram server: " + e);
1012                }
1013            }
1014        }
1015        try {
1016            new Thread(new TestDGSend(Thread.currentThread()), "DGServer")
1017                    .start();
1018            ds = new java.net.DatagramSocket(ports[1]);
1019            dp = new DatagramPacket(testString.getBytes(), testString.length(),
1020                    InetAddress.getLocalHost(), portNumber);
1021            // Wait to allow send to occur
1022            try {
1023                Thread.sleep(500);
1024                ds.send(dp);
1025                Thread.sleep(5000);
1026            } catch (InterruptedException e) {
1027                ds.close();
1028                assertTrue("Incorrect data sent: " + retval, retval
1029                        .equals(testString));
1030            }
1031        } catch (Exception e) {
1032            fail("Exception during send test : " + e.getMessage());
1033        } finally {
1034            ds.close();
1035        }
1036
1037        /*
1038        SecurityManager sm = new SecurityManager() {
1039
1040            public void checkPermission(Permission perm) {
1041            }
1042
1043            public void checkMulticast(InetAddress maddr) {
1044                throw new SecurityException();
1045            }
1046
1047            public void checkConnect(String host,
1048                    int port) {
1049                throw new SecurityException();
1050            }
1051        };
1052        try {
1053
1054            ds = new java.net.DatagramSocket(ports[1]);
1055            dp = new DatagramPacket(testString.getBytes(), testString.length(),
1056                    InetAddress.getLocalHost(), portNumber);
1057
1058            SecurityManager oldSm = System.getSecurityManager();
1059            System.setSecurityManager(sm);
1060            try {
1061                ds.send(dp);
1062                fail("SecurityException should be thrown.");
1063            } catch (SecurityException e) {
1064                // expected
1065            } catch (SocketException e) {
1066                fail("SocketException was thrown.");
1067            } finally {
1068                System.setSecurityManager(oldSm);
1069            }
1070        } catch(Exception e) {
1071            fail("Unexpected exception was thrown: " + e.getMessage());
1072        }
1073        */
1074
1075        DatagramSocket socket = null;
1076        try {
1077            byte rbuf[] = new byte[1000];
1078            DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
1079            SocketAddress address = new InetSocketAddress(portNumber);
1080            DatagramChannel channel = DatagramChannel.open();
1081            channel.configureBlocking(false);
1082            socket = channel.socket();
1083            socket.send(rdp);
1084            fail("IllegalBlockingModeException was not thrown.");
1085        } catch(IllegalBlockingModeException ibme) {
1086            //expected
1087        } catch(IOException ioe) {
1088            fail("IOException was thrown: " + ioe.getMessage());
1089        } finally {
1090            socket.close();
1091        }
1092
1093        //Regression for HARMONY-1118
1094        class testDatagramSocket extends DatagramSocket {
1095            public testDatagramSocket(DatagramSocketImpl impl){
1096               super(impl);
1097            }
1098        }
1099        class testDatagramSocketImpl extends DatagramSocketImpl {
1100            protected void create() throws SocketException {}
1101            protected void bind(int arg0, InetAddress arg1) throws SocketException {}
1102            protected void send(DatagramPacket arg0) throws IOException {}
1103            protected int peek(InetAddress arg0) throws IOException {
1104                return 0;
1105            }
1106            protected int peekData(DatagramPacket arg0) throws IOException {
1107                return 0;
1108            }
1109            protected void receive(DatagramPacket arg0) throws IOException {}
1110            protected void setTTL(byte arg0) throws IOException {}
1111            protected byte getTTL() throws IOException {
1112                return 0;
1113            }
1114            protected void setTimeToLive(int arg0) throws IOException {}
1115            protected int getTimeToLive() throws IOException {
1116                return 0;
1117            }
1118            protected void join(InetAddress arg0) throws IOException {}
1119            protected void leave(InetAddress arg0) throws IOException {}
1120            protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {}
1121            protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {}
1122            protected void close() {}
1123            public void setOption(int arg0, Object arg1) throws SocketException {}
1124            public Object getOption(int arg0) throws SocketException {
1125                return null;
1126            }
1127        }
1128        InetSocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), 0);
1129        //no exception expected for next line
1130        new testDatagramSocket(new testDatagramSocketImpl()).send(new DatagramPacket(new byte[272], 3, sa));
1131
1132        // Regression test for Harmony-2938
1133        InetAddress i = InetAddress.getByName("127.0.0.1");
1134        DatagramSocket d = new DatagramSocket(0, i);
1135        try {
1136            d.send(new DatagramPacket(new byte[] { 1 }, 1));
1137            fail("should throw NPE.");
1138        } catch (NullPointerException e) {
1139            // expected;
1140        } finally {
1141            d.close();
1142        }
1143    }
1144
1145    public void test_setSendBufferSizeI() throws Exception {
1146        int portNumber = Support_PortManager.getNextPortForUDP();
1147        ds = new java.net.DatagramSocket(portNumber);
1148        ds.setSendBufferSize(134);
1149        assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
1150        ds.close();
1151        try {
1152            ds.setSendBufferSize(1);
1153            fail("SocketException was not thrown.");
1154        } catch(SocketException se) {
1155            //expected
1156        }
1157    }
1158
1159    public void test_setReceiveBufferSizeI() throws Exception {
1160        int portNumber = Support_PortManager.getNextPortForUDP();
1161        ds = new java.net.DatagramSocket(portNumber);
1162        ds.setReceiveBufferSize(130);
1163        assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
1164
1165        try {
1166            ds.setReceiveBufferSize(0);
1167            fail("IllegalArgumentException was not thrown.");
1168        } catch(IllegalArgumentException iae) {
1169            //expected
1170        }
1171
1172        try {
1173            ds.setReceiveBufferSize(-1);
1174            fail("IllegalArgumentException was not thrown.");
1175        } catch(IllegalArgumentException iae) {
1176            //expected
1177        }
1178
1179        ds.close();
1180
1181        try {
1182            ds.setReceiveBufferSize(1);
1183            fail("SocketException was not thrown.");
1184        } catch (SocketException e) {
1185            //expected
1186        }
1187    }
1188
1189    public void test_setSoTimeoutI() throws Exception {
1190        // Test for method void java.net.DatagramSocket.setSoTimeout(int)
1191        int portNumber = Support_PortManager.getNextPortForUDP();
1192        ds = new java.net.DatagramSocket(portNumber);
1193        ds.setSoTimeout(5000);
1194        assertTrue("Set incorrect timeout", ds.getSoTimeout() >= 5000);
1195        ds.close();
1196        try {
1197            ds.setSoTimeout(100);
1198            fail("SocketException was not thrown.");
1199        } catch(SocketException se) {
1200            //expected
1201        }
1202    }
1203
1204    public void test_ConstructorLjava_net_DatagramSocketImpl() {
1205        class testDatagramSocket extends DatagramSocket {
1206            public testDatagramSocket(DatagramSocketImpl impl){
1207               super(impl);
1208            }
1209        }
1210
1211        try {
1212            new testDatagramSocket((DatagramSocketImpl) null);
1213            fail("exception expected");
1214        } catch (NullPointerException ex) {
1215            //expected
1216        }
1217    }
1218
1219    public void test_ConstructorLjava_net_SocketAddress() {
1220        class mySocketAddress extends SocketAddress {
1221
1222            public mySocketAddress() {
1223            }
1224        }
1225
1226        try {
1227            try {
1228                int portNumber = Support_PortManager.getNextPortForUDP();
1229                ds = new java.net.DatagramSocket(new InetSocketAddress(
1230                        InetAddress.getLocalHost(), portNumber));
1231                assertTrue(ds.getBroadcast());
1232                assertTrue("Created socket with incorrect port", ds
1233                        .getLocalPort() == portNumber);
1234                assertTrue("Created socket with incorrect address", ds
1235                        .getLocalAddress().equals(InetAddress.getLocalHost()));
1236            } catch (Exception e) {
1237                fail("Could not create DatagramSocket : " + e.getMessage());
1238            }
1239
1240            try {
1241                int portNumber = Support_PortManager.getNextPortForUDP();
1242                ds = new java.net.DatagramSocket(new mySocketAddress());
1243                fail(
1244                        "No exception when constucting datagramSocket with unsupported SocketAddress type");
1245            } catch (IllegalArgumentException e) {
1246
1247            }
1248            //regression for Harmony-894
1249            ds = new DatagramSocket((SocketAddress)null);
1250            assertTrue(ds.getBroadcast());
1251        } catch (Exception ex) {
1252            fail(
1253                    "unexpected exception when datagramSocket SocketAddress constructor test");
1254        }
1255
1256        /*
1257        SecurityManager sm = new SecurityManager() {
1258
1259            public void checkPermission(Permission perm) {
1260            }
1261
1262            public void checkListen(int port) {
1263                throw new SecurityException();
1264            }
1265        };
1266
1267        SecurityManager oldSm = System.getSecurityManager();
1268        System.setSecurityManager(sm);
1269        try {
1270            new DatagramSocket(new InetSocketAddress(
1271                    InetAddress.getLocalHost(), 1));
1272            fail("SecurityException should be thrown.");
1273        } catch (SecurityException e) {
1274            // expected
1275        } catch (SocketException e) {
1276            fail("SocketException was thrown.");
1277        } catch (UnknownHostException e) {
1278            fail("UnknownHostException was thrown.");
1279        } finally {
1280            System.setSecurityManager(oldSm);
1281        }
1282        */
1283
1284        InetSocketAddress isa = null;
1285        try {
1286            isa = new InetSocketAddress(
1287                    InetAddress.getLocalHost(), 1);
1288        } catch (UnknownHostException e) {
1289            fail("UnknownHostException was thrown.");
1290        }
1291    }
1292
1293    public void test_bindLjava_net_SocketAddress() throws Exception {
1294        class mySocketAddress extends SocketAddress {
1295
1296            public mySocketAddress() {
1297            }
1298        }
1299
1300        DatagramServer server = null;
1301        try {
1302            // now create a socket that is not bound and then bind it
1303            int[] ports = Support_PortManager.getNextPortsForUDP(3);
1304            int portNumber = ports[0];
1305            int serverPortNumber = ports[1];
1306            DatagramSocket theSocket = new DatagramSocket(
1307                    new InetSocketAddress(InetAddress.getLocalHost(),
1308                            portNumber));
1309
1310            // validate that the localSocketAddress reflects the address we
1311            // bound to
1312            assertTrue("Local address not correct after bind:"
1313                    + theSocket.getLocalSocketAddress().toString()
1314                    + "Expected: "
1315                    + (new InetSocketAddress(InetAddress.getLocalHost(),
1316                            portNumber)).toString(), theSocket
1317                    .getLocalSocketAddress().equals(
1318                            new InetSocketAddress(InetAddress.getLocalHost(),
1319                                    portNumber)));
1320
1321            // now make sure that datagrams sent from this socket appear to come
1322            // from the address we bound to
1323            InetAddress localHost = InetAddress.getLocalHost();
1324            portNumber = ports[2];
1325            DatagramSocket ds = new DatagramSocket((SocketAddress) null);
1326            ds.bind(new InetSocketAddress(localHost, portNumber));
1327
1328            try {
1329                server = new DatagramServer(serverPortNumber, localHost);
1330                server.start();
1331                Thread.sleep(1000);
1332            } catch (Exception e) {
1333                fail(
1334                        "Failed to set up datagram server for bin datagram socket test ");
1335            }
1336
1337            ds.connect(new InetSocketAddress(localHost, serverPortNumber));
1338
1339            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
1340            DatagramPacket send = new DatagramPacket(sendBytes,
1341                    sendBytes.length);
1342            ds.send(send);
1343            Thread.sleep(1000);
1344            ds.close();
1345            assertTrue(
1346                    "Address in packet sent does not match address bound to:"
1347                            + server.rdp.getAddress() + ":"
1348                            + server.rdp.getPort() + ":" + localHost + ":"
1349                            + portNumber, (server.rdp.getAddress()
1350                            .equals(localHost))
1351                            && (server.rdp.getPort() == portNumber));
1352
1353            // validate if we pass in null that it picks an address for us and
1354            // all is ok
1355            theSocket = new DatagramSocket((SocketAddress) null);
1356            theSocket.bind(null);
1357            assertNotNull("Bind with null did not work", theSocket
1358                    .getLocalSocketAddress());
1359            theSocket.close();
1360
1361            // now check the error conditions
1362
1363            // Address we cannot bind to
1364            theSocket = new DatagramSocket((SocketAddress) null);
1365            try {
1366                theSocket
1367                        .bind(new InetSocketAddress(
1368                                InetAddress
1369                                        .getByAddress(Support_Configuration.nonLocalAddressBytes),
1370                                Support_PortManager.getNextPortForUDP()));
1371                fail("No exception when binding to bad address");
1372            } catch (SocketException ex) {
1373            }
1374            theSocket.close();
1375
1376            // Address that we have allready bound to
1377            ports = Support_PortManager.getNextPortsForUDP(2);
1378            theSocket = new DatagramSocket((SocketAddress) null);
1379            DatagramSocket theSocket2 = new DatagramSocket(ports[0]);
1380            try {
1381                InetSocketAddress theAddress = new InetSocketAddress(
1382                        InetAddress.getLocalHost(), ports[1]);
1383                theSocket.bind(theAddress);
1384                theSocket2.bind(theAddress);
1385                fail("No exception binding to address that is not available");
1386            } catch (SocketException ex) {
1387                //expected
1388            }
1389            theSocket.close();
1390            theSocket2.close();
1391
1392            /*
1393            SecurityManager sm = new SecurityManager() {
1394
1395                public void checkPermission(Permission perm) {
1396                }
1397
1398                public void checkListen(int port) {
1399                    throw new SecurityException();
1400                }
1401            };
1402
1403            ports = Support_PortManager.getNextPortsForUDP(2);
1404            ds = new DatagramSocket(null);
1405            SecurityManager oldSm = System.getSecurityManager();
1406            System.setSecurityManager(sm);
1407            try {
1408
1409                ds.bind(new InetSocketAddress(localHost, ports[0]));
1410                fail("SecurityException should be thrown.");
1411            } catch (SecurityException e) {
1412                // expected
1413            } catch (SocketException e) {
1414                fail("SocketException was thrown.");
1415            } finally {
1416                System.setSecurityManager(oldSm);
1417            }
1418            */
1419
1420            // unsupported SocketAddress subclass
1421            theSocket = new DatagramSocket((SocketAddress) null);
1422            try {
1423                theSocket.bind(new mySocketAddress());
1424                fail("No exception when binding using unsupported SocketAddress subclass");
1425            } catch (IllegalArgumentException ex) {
1426            }
1427            theSocket.close();
1428
1429        } catch (Exception e) {
1430            fail("Unexpected exception during bind test : " + e.getMessage());
1431        }
1432
1433        if (server != null) {
1434            server.stopServer();
1435        }
1436    }
1437
1438    public void test_connectLjava_net_SocketAddress() {
1439
1440        // validate that we get the PortUnreachable exception if we try to
1441        // send a dgram to a server that is not running and then do a recv
1442        try {
1443            ds = new java.net.DatagramSocket();
1444            InetAddress inetAddress = InetAddress.getLocalHost();
1445            int portNumber = Support_PortManager.getNextPortForUDP();
1446            ds.connect(new InetSocketAddress(inetAddress, portNumber));
1447            DatagramPacket send = new DatagramPacket(new byte[10], 10);
1448            ds.send(send);
1449            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
1450            ds.setSoTimeout(10000);
1451            ds.receive(receive);
1452            ds.close();
1453            fail(
1454                    "No PortUnreachableException when connected at native level on recv ");
1455        } catch (Exception e) {
1456            assertTrue(
1457                    "Wrong exception when trying to connect at native level on recv: "
1458                            + e.toString(),
1459                    (e instanceof PortUnreachableException));
1460        }
1461
1462        try {
1463            ds = new java.net.DatagramSocket();
1464            InetAddress inetAddress = InetAddress.getLocalHost();
1465            int portNumber = Support_PortManager.getNextPortForUDP();
1466
1467            ds.connect(new InetSocketAddress("asdfasdf", 1));
1468            ds.close();
1469            fail("SocketException was not thrown.");
1470        } catch (Exception e) {
1471            assertTrue(
1472                    "Wrong exception when trying to connect to unknown host: "
1473                            + e.toString(),
1474                    (e instanceof SocketException));
1475        }
1476
1477        // validate that we can send/receive with datagram sockets connected at
1478        // the native level
1479        DatagramServer server = null;
1480        int[] ports = Support_PortManager.getNextPortsForUDP(3);
1481        int serverPortNumber = ports[0];
1482        try {
1483            InetAddress localHost = InetAddress.getLocalHost();
1484            DatagramSocket ds = new DatagramSocket(ports[1]);
1485            DatagramSocket ds2 = new DatagramSocket(ports[2]);
1486
1487            try {
1488                server = new DatagramServer(serverPortNumber, localHost);
1489                server.start();
1490                Thread.sleep(1000);
1491            } catch (Exception e) {
1492                fail(
1493                        "Failed to set up datagram server for native connected Dgram socket test ");
1494            }
1495
1496            int port = ds.getLocalPort();
1497            ds.connect(new InetSocketAddress(localHost, serverPortNumber));
1498
1499            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
1500            DatagramPacket send = new DatagramPacket(sendBytes,
1501                    sendBytes.length);
1502            ds.send(send);
1503            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
1504            ds.setSoTimeout(2000);
1505            ds.receive(receive);
1506            ds.close();
1507            assertTrue("Wrong size data received: " + receive.getLength(),
1508                    receive.getLength() == sendBytes.length);
1509            assertTrue("Wrong data received"
1510                    + new String(receive.getData(), 0, receive.getLength())
1511                    + ":" + new String(sendBytes), new String(
1512                    receive.getData(), 0, receive.getLength())
1513                    .equals(new String(sendBytes)));
1514            assertTrue("Wrong receiver:" + receive.getAddress() + ":"
1515                    + localHost, receive.getAddress().equals(localHost));
1516        } catch (Exception e) {
1517            fail(
1518                    "Unexpected exception when sending data on dgram connected at native level:"
1519                            + e.toString());
1520        }
1521
1522        if (server != null) {
1523            server.stopServer();
1524        }
1525
1526        // validate that we can disconnect
1527        try {
1528            ds = new java.net.DatagramSocket();
1529            InetAddress inetAddress = InetAddress.getLocalHost();
1530            int portNumber = Support_PortManager.getNextPortForUDP();
1531            ds.connect(new InetSocketAddress(inetAddress, portNumber));
1532            ds.disconnect();
1533            ds.close();
1534        } catch (Exception e) {
1535            assertTrue("Unexpected exception when trying to connect at native"
1536                    + e.toString(), (e instanceof PortUnreachableException));
1537        }
1538
1539        // validate that once connected we cannot send to another address
1540        try {
1541            ds = new java.net.DatagramSocket();
1542            InetAddress inetAddress = InetAddress.getLocalHost();
1543            int portNumber = Support_PortManager.getNextPortForUDP();
1544            ds.connect(new InetSocketAddress(inetAddress, portNumber));
1545            DatagramPacket send = new DatagramPacket(new byte[10], 10,
1546                    inetAddress, portNumber + 1);
1547            ds.send(send);
1548            ds.close();
1549            fail(
1550                    "No Exception when trying to send to a different address on a connected socket ");
1551        } catch (Exception e) {
1552            assertTrue(
1553                    "Wrong exception when trying to send to a different address on a connected socket: "
1554                            + e.toString(),
1555                    (e instanceof IllegalArgumentException));
1556        }
1557
1558        // validate that we can connect, then disconnect, then connect then
1559        // send/recv
1560        server = null;
1561        ports = Support_PortManager.getNextPortsForUDP(3);
1562        serverPortNumber = ports[0];
1563        try {
1564            InetAddress localHost = InetAddress.getLocalHost();
1565            DatagramSocket ds = new DatagramSocket(ports[1]);
1566            DatagramSocket ds2 = new DatagramSocket(ports[2]);
1567
1568            try {
1569                server = new DatagramServer(serverPortNumber, localHost);
1570                server.start();
1571                Thread.sleep(1000);
1572            } catch (Exception e) {
1573                fail(
1574                        "Failed to set up datagram server for native connected Dgram socket test ");
1575            }
1576
1577            int port = ds.getLocalPort();
1578            ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
1579            ds.disconnect();
1580            ds.connect(new InetSocketAddress(localHost, serverPortNumber));
1581
1582            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
1583            DatagramPacket send = new DatagramPacket(sendBytes,
1584                    sendBytes.length);
1585            ds.send(send);
1586            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
1587            ds.setSoTimeout(2000);
1588            ds.receive(receive);
1589            ds.close();
1590            assertTrue(
1591                    "connect/disconnect/connect - Wrong size data received: "
1592                            + receive.getLength(),
1593                    receive.getLength() == sendBytes.length);
1594            assertTrue("connect/disconnect/connect - Wrong data received"
1595                    + new String(receive.getData(), 0, receive.getLength())
1596                    + ":" + new String(sendBytes), new String(
1597                    receive.getData(), 0, receive.getLength())
1598                    .equals(new String(sendBytes)));
1599            assertTrue("connect/disconnect/connect - Wrong receiver:"
1600                    + receive.getAddress() + ":" + localHost, receive
1601                    .getAddress().equals(localHost));
1602        } catch (Exception e) {
1603            fail(
1604                    "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:"
1605                            + e.toString());
1606        }
1607
1608        if (server != null) {
1609            server.stopServer();
1610        }
1611
1612        // validate that we can connect/disconnect then send/recv to any address
1613        server = null;
1614        ports = Support_PortManager.getNextPortsForUDP(3);
1615        serverPortNumber = ports[0];
1616        try {
1617            InetAddress localHost = InetAddress.getLocalHost();
1618            DatagramSocket ds = new DatagramSocket(ports[1]);
1619            DatagramSocket ds2 = new DatagramSocket(ports[2]);
1620
1621            try {
1622                server = new DatagramServer(serverPortNumber, localHost);
1623                server.start();
1624                Thread.sleep(1000);
1625            } catch (Exception e) {
1626                fail(
1627                        "Failed to set up datagram server for native connected Dgram socket test ");
1628            }
1629
1630            int port = ds.getLocalPort();
1631            ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
1632            ds.disconnect();
1633
1634            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
1635            DatagramPacket send = new DatagramPacket(sendBytes,
1636                    sendBytes.length, localHost, serverPortNumber);
1637            ds.send(send);
1638            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
1639            ds.setSoTimeout(2000);
1640            ds.receive(receive);
1641            ds.close();
1642            assertTrue("connect/disconnect - Wrong size data received: "
1643                    + receive.getLength(),
1644                    receive.getLength() == sendBytes.length);
1645            assertTrue("connect/disconnect - Wrong data received"
1646                    + new String(receive.getData(), 0, receive.getLength())
1647                    + ":" + new String(sendBytes), new String(
1648                    receive.getData(), 0, receive.getLength())
1649                    .equals(new String(sendBytes)));
1650            assertTrue("connect/disconnect - Wrong receiver:"
1651                    + receive.getAddress() + ":" + localHost, receive
1652                    .getAddress().equals(localHost));
1653        } catch (Exception e) {
1654            fail(
1655                    "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:"
1656                            + e.toString());
1657        }
1658
1659        if (server != null) {
1660            server.stopServer();
1661        }
1662
1663        // validate that we can connect on an allready connected socket and then
1664        // send/recv
1665        server = null;
1666        ports = Support_PortManager.getNextPortsForUDP(3);
1667        serverPortNumber = ports[0];
1668        try {
1669            InetAddress localHost = InetAddress.getLocalHost();
1670            DatagramSocket ds = new DatagramSocket(ports[1]);
1671            DatagramSocket ds2 = new DatagramSocket(ports[2]);
1672
1673            try {
1674                server = new DatagramServer(serverPortNumber, localHost);
1675                server.start();
1676                Thread.sleep(1000);
1677            } catch (Exception e) {
1678                fail(
1679                        "Failed to set up datagram server for native connected Dgram socket test ");
1680            }
1681
1682            int port = ds.getLocalPort();
1683            ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
1684            ds.connect(new InetSocketAddress(localHost, serverPortNumber));
1685
1686            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
1687            DatagramPacket send = new DatagramPacket(sendBytes,
1688                    sendBytes.length);
1689            ds.send(send);
1690            DatagramPacket receive = new DatagramPacket(new byte[20], 20);
1691            ds.setSoTimeout(2000);
1692            ds.receive(receive);
1693            ds.close();
1694            assertTrue("connect/connect - Wrong size data received: "
1695                    + receive.getLength(),
1696                    receive.getLength() == sendBytes.length);
1697            assertTrue("connect/connect - Wrong data received"
1698                    + new String(receive.getData(), 0, receive.getLength())
1699                    + ":" + new String(sendBytes), new String(
1700                    receive.getData(), 0, receive.getLength())
1701                    .equals(new String(sendBytes)));
1702            assertTrue("connect/connect - Wrong receiver:"
1703                    + receive.getAddress() + ":" + localHost, receive
1704                    .getAddress().equals(localHost));
1705        } catch (Exception e) {
1706            fail(
1707                    "Unexpected exception when sending data on dgram connected at native level after connect/connect: "
1708                            + e.toString());
1709        }
1710
1711        if (server != null) {
1712            server.stopServer();
1713        }
1714
1715        // test for when we fail to connect at the native level. It seems to
1716        // fail for the any address so we use this. Now to be compatible we
1717        // don't throw the exception but eat it and then act as if we were
1718        // connected at the Java level.
1719        try {
1720            ds = new java.net.DatagramSocket();
1721            byte[] addressBytes = { 0, 0, 0, 0 };
1722            InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
1723            int portNumber = Support_PortManager.getNextPortForUDP();
1724            InetAddress localHost = InetAddress.getLocalHost();
1725            ds.connect(new InetSocketAddress(inetAddress, portNumber));
1726            assertTrue("Is not connected after connect to inaddr any", ds
1727                    .isConnected());
1728            byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
1729            DatagramPacket send = new DatagramPacket(sendBytes,
1730                    sendBytes.length, localHost, portNumber);
1731            ds.send(send);
1732            fail(
1733                    "No exception when trying to connect at native level with bad address (exception from send)  ");
1734        } catch (Exception e) {
1735            assertTrue(
1736                    "Wrong exception when trying to connect at native level with bad address (exception from send): "
1737                            + e.toString(),
1738                    (e instanceof IllegalArgumentException));
1739        }
1740    }
1741
1742    public void test_isBound() {
1743        try {
1744            InetAddress addr = InetAddress.getLocalHost();
1745            int[] ports = Support_PortManager.getNextPortsForUDP(3);
1746            int port = ports[0];
1747
1748            DatagramSocket theSocket = new DatagramSocket(ports[1]);
1749            assertTrue("Socket indicated  not bound when it should be (1)",
1750                    theSocket.isBound());
1751            theSocket.close();
1752
1753            theSocket = new DatagramSocket(new InetSocketAddress(addr, port));
1754            assertTrue("Socket indicated  not bound when it should be (2)",
1755                    theSocket.isBound());
1756            theSocket.close();
1757
1758            theSocket = new DatagramSocket((SocketAddress) null);
1759            assertFalse("Socket indicated  bound when it should not be (1)",
1760                    theSocket.isBound());
1761            theSocket.close();
1762
1763            // connect causes implicit bind
1764            theSocket = new DatagramSocket((SocketAddress) null);
1765            theSocket.connect(new InetSocketAddress(addr, port));
1766            assertTrue("Socket indicated not bound when it should be (3)",
1767                    theSocket.isBound());
1768            theSocket.close();
1769
1770            // now test when we bind explicitely
1771            InetSocketAddress theLocalAddress = new InetSocketAddress(
1772                    InetAddress.getLocalHost(), ports[2]);
1773            theSocket = new DatagramSocket((SocketAddress) null);
1774            assertFalse("Socket indicated bound when it should not be (2)",
1775                    theSocket.isBound());
1776            theSocket.bind(theLocalAddress);
1777            assertTrue("Socket indicated not bound when it should be (4)",
1778                    theSocket.isBound());
1779            theSocket.close();
1780            assertTrue("Socket indicated not bound when it should be (5)",
1781                    theSocket.isBound());
1782        } catch (Exception e) {
1783            fail("Got exception during isBound tests" + e.toString());
1784        }
1785    }
1786
1787    public void test_isConnected() {
1788        try {
1789            InetAddress addr = InetAddress.getLocalHost();
1790            int[] ports = Support_PortManager.getNextPortsForUDP(4);
1791            int port = ports[0];
1792
1793            // base test
1794            DatagramSocket theSocket = new DatagramSocket(ports[1]);
1795            assertFalse("Socket indicated connected when it should not be",
1796                    theSocket.isConnected());
1797            theSocket.connect(new InetSocketAddress(addr, port));
1798            assertTrue("Socket indicated  not connected when it should be",
1799                    theSocket.isConnected());
1800
1801            // reconnect the socket and make sure we get the right answer
1802            theSocket.connect(new InetSocketAddress(addr, ports[2]));
1803            assertTrue("Socket indicated  not connected when it should be",
1804                    theSocket.isConnected());
1805
1806            // now disconnect the socket and make sure we get the right answer
1807            theSocket.disconnect();
1808            assertFalse("Socket indicated connected when it should not be",
1809                    theSocket.isConnected());
1810            theSocket.close();
1811
1812            // now check behavior when socket is closed when connected
1813            theSocket = new DatagramSocket(ports[3]);
1814            theSocket.connect(new InetSocketAddress(addr, port));
1815            theSocket.close();
1816            assertTrue("Socket indicated  not connected when it should be",
1817                    theSocket.isConnected());
1818        } catch (Exception e) {
1819            fail("Got exception during isConnected tests" + e.toString());
1820        }
1821    }
1822
1823    public void test_getRemoteSocketAddress() {
1824        try {
1825            int[] ports = Support_PortManager.getNextPortsForUDP(3);
1826            int sport = ports[0];
1827            int portNumber = ports[1];
1828            DatagramSocket s = new DatagramSocket(new InetSocketAddress(
1829                    InetAddress.getLocalHost(), portNumber));
1830            s.connect(new InetSocketAddress(InetAddress.getLocalHost(), sport));
1831            assertTrue("Returned incorrect InetSocketAddress(1):"
1832                    + s.getLocalSocketAddress().toString(), s
1833                    .getRemoteSocketAddress().equals(
1834                            new InetSocketAddress(InetAddress.getLocalHost(),
1835                                    sport)));
1836            s.close();
1837
1838            // now create one that is not connected and validate that we get the
1839            // right answer
1840            DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
1841            portNumber = ports[2];
1842            theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
1843                    portNumber));
1844            assertNull(
1845                    "Returned incorrect InetSocketAddress -unconnected socket:"
1846                            + "Expected: NULL", theSocket
1847                            .getRemoteSocketAddress());
1848
1849            // now connect and validate we get the right answer
1850            theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
1851                    sport));
1852            assertTrue("Returned incorrect InetSocketAddress(2):"
1853                    + theSocket.getRemoteSocketAddress().toString(), theSocket
1854                    .getRemoteSocketAddress().equals(
1855                            new InetSocketAddress(InetAddress.getLocalHost(),
1856                                    sport)));
1857            theSocket.close();
1858
1859        } catch (Exception e) {
1860            fail("Exception during getRemoteSocketAddress test: " + e);
1861        }
1862    }
1863
1864    public void test_getLocalSocketAddress() throws Exception {
1865        int portNumber = Support_PortManager.getNextPortForUDP();
1866        DatagramSocket s = new DatagramSocket(new InetSocketAddress(
1867                InetAddress.getLocalHost(), portNumber));
1868        assertTrue("Returned incorrect InetSocketAddress(1):"
1869                + s.getLocalSocketAddress().toString()
1870                + "Expected: "
1871                + (new InetSocketAddress(InetAddress.getLocalHost(),
1872                        portNumber)).toString(), s.getLocalSocketAddress()
1873                .equals(
1874                        new InetSocketAddress(InetAddress.getLocalHost(),
1875                                portNumber)));
1876        s.close();
1877
1878        InetSocketAddress remoteAddress = (InetSocketAddress) s
1879                .getRemoteSocketAddress();
1880
1881        // now create a socket that is not bound and validate we get the
1882        // right answer
1883        DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
1884        assertNull(
1885                "Returned incorrect InetSocketAddress -unbound socket- Expected null",
1886                theSocket.getLocalSocketAddress());
1887
1888        // now bind the socket and make sure we get the right answer
1889        portNumber = Support_PortManager.getNextPortForUDP();
1890        theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
1891                portNumber));
1892        assertTrue("Returned incorrect InetSocketAddress(2):"
1893                + theSocket.getLocalSocketAddress().toString()
1894                + "Expected: "
1895                + (new InetSocketAddress(InetAddress.getLocalHost(),
1896                        portNumber)).toString(), theSocket
1897                .getLocalSocketAddress().equals(
1898                        new InetSocketAddress(InetAddress.getLocalHost(),
1899                                portNumber)));
1900        theSocket.close();
1901
1902        // now check behavior when the ANY address is returned
1903        s = new DatagramSocket(0);
1904        assertTrue("ANY address not IPv6: " + s.getLocalSocketAddress(),
1905                ((InetSocketAddress) s.getLocalSocketAddress()).getAddress() instanceof Inet6Address);
1906        s.close();
1907    }
1908
1909    public void test_setReuseAddressZ() throws Exception {
1910        // test case were we set it to false
1911        DatagramSocket theSocket1 = null;
1912        DatagramSocket theSocket2 = null;
1913        try {
1914            InetSocketAddress theAddress = new InetSocketAddress(
1915                    InetAddress.getLocalHost(), Support_PortManager
1916                            .getNextPortForUDP());
1917            theSocket1 = new DatagramSocket((SocketAddress) null);
1918            theSocket2 = new DatagramSocket((SocketAddress) null);
1919            theSocket1.setReuseAddress(false);
1920            theSocket2.setReuseAddress(false);
1921            theSocket1.bind(theAddress);
1922            theSocket2.bind(theAddress);
1923            fail(
1924                    "No exception when trying to connect to do duplicate socket bind with re-useaddr set to false");
1925        } catch (BindException e) {
1926
1927        }
1928        if (theSocket1 != null)
1929            theSocket1.close();
1930        if (theSocket2 != null)
1931            theSocket2.close();
1932
1933        // test case were we set it to true
1934        try {
1935            InetSocketAddress theAddress = new InetSocketAddress(
1936                    InetAddress.getLocalHost(), Support_PortManager
1937                            .getNextPortForUDP());
1938            theSocket1 = new DatagramSocket((SocketAddress) null);
1939            theSocket2 = new DatagramSocket((SocketAddress) null);
1940            theSocket1.setReuseAddress(true);
1941            theSocket2.setReuseAddress(true);
1942            theSocket1.bind(theAddress);
1943            theSocket2.bind(theAddress);
1944        } catch (Exception e) {
1945            fail(
1946                    "unexpected exception when trying to connect to do duplicate socket bind with re-useaddr set to true");
1947        }
1948        if (theSocket1 != null)
1949            theSocket1.close();
1950        if (theSocket2 != null)
1951            theSocket2.close();
1952
1953        // test the default case which we expect to be the same on all
1954        // platforms
1955        try {
1956            InetSocketAddress theAddress = new InetSocketAddress(
1957                    InetAddress.getLocalHost(), Support_PortManager
1958                            .getNextPortForUDP());
1959            theSocket1 = new DatagramSocket((SocketAddress) null);
1960            theSocket2 = new DatagramSocket((SocketAddress) null);
1961            theSocket1.bind(theAddress);
1962            theSocket2.bind(theAddress);
1963            fail(
1964                    "No exception when trying to connect to do duplicate socket bind with re-useaddr left as default");
1965        } catch (BindException e) {
1966
1967        }
1968        if (theSocket1 != null)
1969            theSocket1.close();
1970        if (theSocket2 != null)
1971            theSocket2.close();
1972
1973        try {
1974            theSocket1.setReuseAddress(true);
1975            fail("SocketException was not thrown.");
1976        } catch(SocketException se) {
1977            //expected
1978        }
1979    }
1980
1981    public void test_getReuseAddress() throws Exception {
1982        DatagramSocket theSocket = new DatagramSocket();
1983        theSocket.setReuseAddress(true);
1984        assertTrue("getReuseAddress false when it should be true",
1985                theSocket.getReuseAddress());
1986        theSocket.setReuseAddress(false);
1987        assertFalse("getReuseAddress true when it should be false",
1988                theSocket.getReuseAddress());
1989        theSocket.close();
1990        try {
1991            theSocket.getReuseAddress();
1992            fail("SocketException was not thrown.");
1993        } catch(SocketException se) {
1994            //expected
1995        }
1996    }
1997
1998    public void test_setBroadcastZ() throws Exception {
1999        int[] ports = Support_PortManager.getNextPortsForUDP(3);
2000        DatagramSocket theSocket = new DatagramSocket(ports[0]);
2001        theSocket.setBroadcast(false);
2002        byte theBytes[] = { -1, -1, -1, -1 };
2003
2004        // validate we cannot connect to the broadcast address when
2005        // setBroadcast is false
2006        try {
2007            theSocket.connect(new InetSocketAddress(InetAddress
2008                    .getByAddress(theBytes), ports[1]));
2009            assertFalse(
2010                    "No exception when connecting to broadcast address with setBroadcast(false)",
2011                    theSocket.getBroadcast());
2012        } catch (SocketException ex) {
2013            //expected
2014        }
2015
2016        // now validate that we can connect to the broadcast address when
2017        // setBroadcast is true
2018        theSocket.setBroadcast(true);
2019        theSocket.connect(new InetSocketAddress(InetAddress
2020                        .getByAddress(theBytes), ports[2]));
2021
2022        theSocket.close();
2023        try {
2024            theSocket.setBroadcast(false);
2025            fail("SocketException was not thrown.");
2026        } catch(SocketException se) {
2027            //expected
2028        }
2029    }
2030
2031    public void test_getBroadcast() throws Exception {
2032        DatagramSocket theSocket = new DatagramSocket();
2033        theSocket.setBroadcast(true);
2034        assertTrue("getBroadcast false when it should be true", theSocket
2035                .getBroadcast());
2036        theSocket.setBroadcast(false);
2037        assertFalse("getBroadcast true when it should be False", theSocket
2038                .getBroadcast());
2039        theSocket.close();
2040        try {
2041            theSocket.getBroadcast();
2042            fail("SocketException was not thrown.");
2043        } catch(SocketException se) {
2044            //expected
2045        }
2046    }
2047
2048    public void test_setTrafficClassI() throws Exception {
2049        int IPTOS_LOWCOST = 0x2;
2050        int IPTOS_RELIABILTY = 0x4;
2051        int IPTOS_THROUGHPUT = 0x8;
2052        int IPTOS_LOWDELAY = 0x10;
2053        int[] ports = Support_PortManager.getNextPortsForUDP(2);
2054
2055        new InetSocketAddress(InetAddress.getLocalHost(),
2056                ports[0]);
2057        DatagramSocket theSocket = new DatagramSocket(ports[1]);
2058
2059        // validate that value set must be between 0 and 255
2060        try {
2061            theSocket.setTrafficClass(256);
2062            fail("No exception when traffic class set to 256");
2063        } catch (IllegalArgumentException e) {
2064        }
2065
2066        try {
2067            theSocket.setTrafficClass(-1);
2068            fail("No exception when traffic class set to -1");
2069        } catch (IllegalArgumentException e) {
2070        }
2071
2072        // now validate that we can set it to some good values
2073        theSocket.setTrafficClass(IPTOS_LOWCOST);
2074        theSocket.setTrafficClass(IPTOS_THROUGHPUT);
2075
2076        theSocket.close();
2077        try {
2078            theSocket.setTrafficClass(1);
2079            fail("SocketException was not thrown.");
2080        } catch(SocketException se) {
2081            //expected
2082        }
2083    }
2084
2085    public void test_getTrafficClass() throws Exception {
2086        int IPTOS_LOWCOST = 0x2;
2087        int IPTOS_RELIABILTY = 0x4;
2088        int IPTOS_THROUGHPUT = 0x8;
2089        int IPTOS_LOWDELAY = 0x10;
2090        int[] ports = Support_PortManager.getNextPortsForUDP(2);
2091
2092        new InetSocketAddress(InetAddress.getLocalHost(),
2093                ports[0]);
2094        DatagramSocket theSocket = new DatagramSocket(ports[1]);
2095
2096        /*
2097         * we cannot actually check that the values are set as if a platform
2098         * does not support the option then it may come back unset even
2099         * though we set it so just get the value to make sure we can get it
2100         */
2101        int trafficClass = theSocket.getTrafficClass();
2102
2103        theSocket.close();
2104        try {
2105            theSocket.getTrafficClass();
2106            fail("SocketException was not thrown.");
2107        } catch(SocketException se) {
2108            //expected
2109        }
2110    }
2111
2112    public void test_isClosed() {
2113        try {
2114            DatagramSocket theSocket = new DatagramSocket();
2115
2116            // validate isClosed returns expected values
2117            assertFalse("Socket should indicate it is not closed(1):",
2118                    theSocket.isClosed());
2119            theSocket.close();
2120            assertTrue("Socket should indicate it is not closed(1):", theSocket
2121                    .isClosed());
2122
2123            InetSocketAddress theAddress = new InetSocketAddress(InetAddress
2124                    .getLocalHost(), Support_PortManager.getNextPortForUDP());
2125            theSocket = new DatagramSocket(theAddress);
2126            assertFalse("Socket should indicate it is not closed(2):",
2127                    theSocket.isClosed());
2128            theSocket.close();
2129            assertTrue("Socket should indicate it is not closed(2):", theSocket
2130                    .isClosed());
2131        } catch (Exception e) {
2132            fail("Got exception during isClosed tests" + e.toString());
2133        }
2134    }
2135
2136    public void test_getChannel() throws Exception {
2137        assertNull(new DatagramSocket().getChannel());
2138
2139        int portNumber = Support_PortManager.getNextPortForUDP();
2140        DatagramSocket ds = null;
2141        try {
2142            InetAddress ia = InetAddress
2143                        .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
2144            ds = new DatagramSocket();
2145            assertNull(ds.getChannel());
2146            ds.connect(ia, portNumber);
2147            assertNull(ds.getChannel());
2148        } catch (SocketException e) {
2149            fail("SocketException was thrown.");
2150        } finally {
2151            ds.disconnect();
2152            ds.close();
2153        }
2154        portNumber = Support_PortManager.getNextPortForUDP();
2155        SocketAddress address = new InetSocketAddress(portNumber);
2156        DatagramChannel channel = DatagramChannel.open();
2157        DatagramSocket socket = channel.socket();
2158        assertEquals(channel, socket.getChannel());
2159    }
2160
2161    class TestDatagramSocketImplFactory implements DatagramSocketImplFactory {
2162        public DatagramSocketImpl createDatagramSocketImpl() {
2163            return new TestDatagramSocketImpl();
2164        }
2165    }
2166
2167    class TestDatagramSocketImpl extends DatagramSocketImpl {
2168
2169        @Override
2170        protected void bind(int arg0, InetAddress arg1) throws SocketException {
2171            // TODO Auto-generated method stub
2172
2173        }
2174
2175        @Override
2176        protected void close() {
2177            // TODO Auto-generated method stub
2178
2179        }
2180
2181        @Override
2182        protected void create() throws SocketException {
2183            // TODO Auto-generated method stub
2184
2185        }
2186
2187        @Override
2188        protected byte getTTL() throws IOException {
2189            // TODO Auto-generated method stub
2190            return 0;
2191        }
2192
2193        @Override
2194        protected int getTimeToLive() throws IOException {
2195            // TODO Auto-generated method stub
2196            return 0;
2197        }
2198
2199        @Override
2200        protected void join(InetAddress arg0) throws IOException {
2201            // TODO Auto-generated method stub
2202
2203        }
2204
2205        @Override
2206        protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
2207            // TODO Auto-generated method stub
2208
2209        }
2210
2211        @Override
2212        protected void leave(InetAddress arg0) throws IOException {
2213            // TODO Auto-generated method stub
2214
2215        }
2216
2217        @Override
2218        protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
2219            // TODO Auto-generated method stub
2220
2221        }
2222
2223        @Override
2224        protected int peek(InetAddress arg0) throws IOException {
2225            // TODO Auto-generated method stub
2226            return 0;
2227        }
2228
2229        @Override
2230        protected int peekData(DatagramPacket arg0) throws IOException {
2231            // TODO Auto-generated method stub
2232            return 0;
2233        }
2234
2235        @Override
2236        protected void receive(DatagramPacket arg0) throws IOException {
2237            // TODO Auto-generated method stub
2238
2239        }
2240
2241        @Override
2242        protected void send(DatagramPacket arg0) throws IOException {
2243            // TODO Auto-generated method stub
2244
2245        }
2246
2247        @Override
2248        protected void setTTL(byte arg0) throws IOException {
2249            // TODO Auto-generated method stub
2250
2251        }
2252
2253        @Override
2254        protected void setTimeToLive(int arg0) throws IOException {
2255            // TODO Auto-generated method stub
2256
2257        }
2258
2259        public Object getOption(int arg0) throws SocketException {
2260            // TODO Auto-generated method stub
2261            return null;
2262        }
2263
2264        public void setOption(int arg0, Object arg1) throws SocketException {
2265            // TODO Auto-generated method stub
2266
2267        }
2268
2269    }
2270
2271    /**
2272     * Sets up the fixture, for example, open a network connection. This method
2273     * is called before a test is executed.
2274     */
2275    protected void setUp() {
2276        retval = "Bogus retval";
2277    }
2278
2279    /**
2280     * Tears down the fixture, for example, close a network connection. This
2281     * method is called after a test is executed.
2282     */
2283    protected void tearDown() {
2284        try {
2285            ds.close();
2286            sds.close();
2287        } catch (Exception e) {
2288        }
2289    }
2290
2291    protected void receive_oversize_java_net_DatagramPacket() throws Exception {
2292        final int[] ports = Support_PortManager.getNextPortsForUDP(2);
2293        final int portNumber = ports[0];
2294
2295        class TestDGRcvOver implements Runnable {
2296            public void run() {
2297                InetAddress localHost = null;
2298                try {
2299                    localHost = InetAddress.getLocalHost();
2300                    Thread.sleep(1000);
2301                    DatagramSocket sds = new DatagramSocket(ports[1]);
2302                    DatagramPacket rdp = new DatagramPacket("0123456789"
2303                            .getBytes(), 10, localHost, portNumber);
2304                    sds.send(rdp);
2305                    sds.close();
2306                } catch (Exception e) {
2307                    throw new RuntimeException(e);
2308                }
2309            }
2310        }
2311
2312        try {
2313            new Thread(new TestDGRcvOver(), "DGSenderOver").start();
2314            ds = new java.net.DatagramSocket(portNumber);
2315            ds.setSoTimeout(6000);
2316            byte rbuf[] = new byte[5];
2317            DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
2318            ;
2319            ds.receive(rdp);
2320            ds.close();
2321            assertTrue("Send/Receive oversize failed to return correct data: "
2322                    + new String(rbuf, 0, 5), new String(rbuf, 0, 5)
2323                    .equals("01234"));
2324        } finally {
2325            ds.close();
2326        }
2327    }
2328}
2329