SocketTest.java revision 561ee011997c6c2f1befbfaa9d5f0a99771c1d63
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 org.apache.harmony.luni.tests.java.net;
19
20import java.io.IOException;
21import java.io.InputStream;
22import java.io.OutputStream;
23import java.net.ConnectException;
24import java.net.Inet4Address;
25import java.net.Inet6Address;
26import java.net.InetAddress;
27import java.net.InetSocketAddress;
28import java.net.Proxy;
29import java.net.ServerSocket;
30import java.net.Socket;
31import java.net.SocketAddress;
32import java.net.SocketException;
33import java.net.SocketImpl;
34import java.net.SocketImplFactory;
35import java.net.SocketTimeoutException;
36import java.net.UnknownHostException;
37import java.security.Permission;
38import java.util.Arrays;
39import java.util.Locale;
40
41import org.apache.harmony.luni.net.PlainSocketImpl;
42
43import tests.support.Support_Configuration;
44
45public class SocketTest extends SocketTestCase {
46    private class ClientThread implements Runnable {
47
48        public void run() {
49            try {
50                Socket socket = new Socket();
51                InetSocketAddress addr = new InetSocketAddress(host, port);
52                socket.connect(addr);
53
54                socket.close();
55            } catch (IOException e) {
56                throw new RuntimeException(e);
57            }
58        }
59    }
60
61    private class ServerThread implements Runnable {
62        private static final int FIRST_TIME = 1;
63
64        private static final int SECOND_TIME = 2;
65
66        private int backlog = 10;
67
68        public boolean ready = false;
69
70        private int serverSocketConstructor = 0;
71
72        public void run() {
73            try {
74
75                ServerSocket socket = null;
76                switch (serverSocketConstructor) {
77                case FIRST_TIME:
78                    socket = new ServerSocket(port, backlog,
79                            new InetSocketAddress(host, port).getAddress());
80                    port = socket.getLocalPort();
81                    break;
82                case SECOND_TIME:
83                    socket = new ServerSocket(port, backlog);
84                    host = socket.getInetAddress().getHostName();
85                    port = socket.getLocalPort();
86                    break;
87                default:
88                    socket = new ServerSocket();
89                    break;
90                }
91
92                synchronized (this) {
93                    ready = true;
94                    this.notifyAll();
95                }
96
97                socket.setSoTimeout(5000);
98                Socket client = socket.accept();
99                client.close();
100                socket.close();
101            } catch (IOException e) {
102                e.printStackTrace();
103            } catch (Throwable e) {
104                e.printStackTrace();
105            }
106        }
107
108        public synchronized void waitCreated() throws Exception {
109            while (!ready) {
110                this.wait();
111            }
112        }
113    }
114
115    boolean interrupted;
116
117    String host = "localhost";
118    int port;
119
120    Thread t;
121
122    private void connectTestImpl(int ssConsType) throws Exception {
123        ServerThread server = new ServerThread();
124        server.serverSocketConstructor = ssConsType;
125        Thread serverThread = new Thread(server);
126        serverThread.start();
127        server.waitCreated();
128
129        ClientThread client = new ClientThread();
130        Thread clientThread = new Thread(client);
131        clientThread.start();
132        try {
133            serverThread.join();
134            clientThread.join();
135        } catch (InterruptedException e) {
136            e.printStackTrace();
137        }
138    }
139
140    protected void tearDown() {
141        try {
142            if (t != null) {
143                t.interrupt();
144            }
145        } catch (Exception e) {
146        }
147        this.t = null;
148        this.interrupted = false;
149    }
150
151    /**
152     * @tests java.net.Socket#bind(java.net.SocketAddress)
153     */
154    public void test_bindLjava_net_SocketAddress() throws IOException {
155
156        @SuppressWarnings("serial")
157        class UnsupportedSocketAddress extends SocketAddress {
158            public UnsupportedSocketAddress() {
159            }
160        }
161
162        // Address we cannot bind to
163        Socket theSocket = new Socket();
164        InetSocketAddress bogusAddress = new InetSocketAddress(InetAddress
165                .getByAddress(Support_Configuration.nonLocalAddressBytes), 42);
166        try {
167            theSocket.bind(bogusAddress);
168            fail("No exception when binding to bad address");
169        } catch (IOException ex) {
170            // Expected
171        }
172        theSocket.close();
173
174        // Now create a socket that is not bound and then bind it
175        theSocket = new Socket();
176        theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
177        int portNumber = theSocket.getLocalPort();
178
179        // Validate that the localSocketAddress reflects the address we
180        // bound to
181        assertEquals("Local address not correct after bind",
182                new InetSocketAddress(InetAddress.getLocalHost(), portNumber),
183                theSocket.getLocalSocketAddress());
184
185        // Make sure we can now connect and that connections appear to come
186        // from the address we bound to.
187        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
188                .getLocalHost(), 0);
189        ServerSocket server = new ServerSocket();
190        server.bind(theAddress);
191        int sport = server.getLocalPort();
192        InetSocketAddress boundAddress = new InetSocketAddress(InetAddress
193                .getLocalHost(), sport);
194
195        theSocket.connect(boundAddress);
196        Socket worker = server.accept();
197        assertEquals(
198                "Returned Remote address from server connected to does not match expected local address",
199                new InetSocketAddress(InetAddress.getLocalHost(), portNumber),
200                worker.getRemoteSocketAddress());
201        theSocket.close();
202        worker.close();
203        server.close();
204
205        // Validate if we pass in null that it picks an address for us and
206        // all is ok
207        theSocket = new Socket();
208        theSocket.bind(null);
209        assertNotNull("Bind with null did not work", theSocket
210                .getLocalSocketAddress());
211        theSocket.close();
212
213        // now check the error conditions
214
215        // Address that we have already bound to
216        theSocket = new Socket();
217        theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
218        theSocket.bind(theAddress);
219
220        Socket theSocket2 = new Socket();
221        try {
222            theSocket2.bind(theSocket.getLocalSocketAddress());
223            fail("No exception binding to address that is not available");
224        } catch (IOException ex) {
225            // Expected
226        }
227        theSocket.close();
228        theSocket2.close();
229
230        // Unsupported SocketAddress subclass
231        theSocket = new Socket();
232        try {
233            theSocket.bind(new UnsupportedSocketAddress());
234            fail("No exception when binding using unsupported SocketAddress subclass");
235        } catch (IllegalArgumentException ex) {
236            // Expected
237        }
238        theSocket.close();
239    }
240
241    /**
242     * @tests java.net.Socket#bind(java.net.SocketAddress)
243     */
244    public void test_bindLjava_net_SocketAddress_Proxy() throws IOException {
245        // The Proxy will not impact on the bind operation. It can be assigned
246        // with any address.
247        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(
248                "127.0.0.1", 0));
249        Socket socket = new Socket(proxy);
250
251        InetAddress address = InetAddress.getByName("localhost");
252        socket.bind(new InetSocketAddress(address, 0));
253
254        assertEquals(address, socket.getLocalAddress());
255        assertTrue(0 != socket.getLocalPort());
256
257        socket.close();
258    }
259
260    /**
261     * @tests java.net.Socket#close()
262     */
263    public void test_close() throws IOException {
264        ServerSocket server = new ServerSocket(0);
265        Socket client = new Socket(InetAddress.getLocalHost(), server
266                .getLocalPort());
267
268        try {
269            client.setSoLinger(false, 100);
270        } catch (IOException e) {
271            handleException(e, SO_LINGER);
272        }
273
274        client.close();
275        try {
276            client.getOutputStream();
277            fail("Failed to close socket");
278        } catch (IOException e) { // Caught Exception after close.
279            // Expected
280        }
281
282        server.close();
283    }
284
285    /**
286     * @tests Socket#connect(SocketAddress) try an unknownhost
287     */
288    public void test_connect_unknownhost() throws Exception {
289        Socket socket = new Socket();
290        try {
291            socket.connect(new InetSocketAddress("unknownhost.invalid", 12345));
292            fail("Should throw UnknownHostException");
293        } catch (UnknownHostException e) {
294            // expected
295        }
296    }
297
298    /**
299     * @tests Socket#connect(SocketAddress)
300     */
301    public void test_connect_unresolved() throws IOException {
302        Socket socket = new Socket();
303
304        // Try a known host created by createUnresolved()
305        try {
306            socket.connect(InetSocketAddress.createUnresolved("www.apache.org",
307                    80));
308            fail("Should throw UnknownHostException");
309        } catch (UnknownHostException e) {
310            // expected
311        }
312
313        // Try an unknown host created by createUnresolved()
314        try {
315            socket.connect(InetSocketAddress.createUnresolved(
316                    "unknownhost.invalid", 12345));
317            fail("Should throw UnknownHostException");
318        } catch (UnknownHostException e) {
319            // expected
320        }
321    }
322
323    /**
324     * @tests java.net.Socket#connect(java.net.SocketAddress)
325     */
326    public void test_connectLjava_net_SocketAddress() throws Exception {
327
328        @SuppressWarnings("serial")
329        class UnsupportedSocketAddress extends SocketAddress {
330            public UnsupportedSocketAddress() {
331            }
332        }
333
334        Socket theSocket = new Socket();
335        try {
336            theSocket.connect(null);
337            fail("No exception for null arg");
338        } catch (IllegalArgumentException e) {
339            // Expected
340        }
341
342        try {
343            theSocket.connect(new UnsupportedSocketAddress());
344            fail("No exception for invalid socket address");
345        } catch (IllegalArgumentException e) {
346            // Expected
347        }
348
349        try {
350            theSocket.connect(new InetSocketAddress(InetAddress
351                    .getByAddress(new byte[] { 0, 0, 0, 0 }), 42));
352            fail("No exception with non-connectable address");
353        } catch (ConnectException e) {
354            // Expected
355        }
356
357        // now validate that we get a connect exception if we try to connect to
358        // an address on which nobody is listening
359        theSocket = new Socket();
360        try {
361            theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
362                    0));
363            fail("No exception when connecting to address nobody listening on");
364        } catch (ConnectException e) {
365            // Expected
366        }
367
368        // Now validate that we can actually connect when somebody is listening
369        ServerSocket server = new ServerSocket(0);
370        InetSocketAddress boundAddress = new InetSocketAddress(InetAddress
371                .getLocalHost(), server.getLocalPort());
372        Socket client = new Socket();
373        client.connect(boundAddress);
374
375        // validate that when a socket is connected that it answers
376        // correctly to related queries
377        assertTrue("Wrong connected status", client.isConnected());
378        assertFalse("Wrong closed status", client.isClosed());
379        assertTrue("Wrong bound status", client.isBound());
380        assertFalse("Wrong input shutdown status", client.isInputShutdown());
381        assertFalse("Wrong output shutdown status", client.isOutputShutdown());
382        assertTrue("Local port was 0", client.getLocalPort() != 0);
383
384        client.close();
385        server.close();
386
387        // Now validate that we get the right exception if we connect when we
388        // are already connected
389        server = new ServerSocket(0);
390        boundAddress = new InetSocketAddress(InetAddress.getLocalHost(), server
391                .getLocalPort());
392        client = new Socket();
393        client.connect(boundAddress);
394
395        try {
396            client.connect(boundAddress);
397            fail("No exception when we try to connect on a connected socket: ");
398        } catch (SocketException e) {
399            // Expected
400        }
401        client.close();
402        server.close();
403    }
404
405    /**
406     * Regression for Harmony-2503
407     */
408    public void test_connectLjava_net_SocketAddress_AnyAddress()
409            throws Exception {
410        connectTestImpl(ServerThread.FIRST_TIME);
411        connectTestImpl(ServerThread.SECOND_TIME);
412    }
413
414    /**
415     * @tests java.net.Socket#connect(java.net.SocketAddress, int)
416     */
417    public void test_connectLjava_net_SocketAddressI() throws Exception {
418
419        @SuppressWarnings("serial")
420        class UnsupportedSocketAddress extends SocketAddress {
421            public UnsupportedSocketAddress() {
422            }
423        }
424
425        // Start by validating the error checks
426        Socket theSocket = new Socket();
427        try {
428            theSocket.connect(new InetSocketAddress(0), -100);
429            fail("No exception for negative timeout");
430        } catch (IllegalArgumentException e) {
431            // Expected
432        }
433
434        try {
435            theSocket.connect(null, 0);
436            fail("No exception for null address");
437        } catch (IllegalArgumentException e) {
438            // Expected
439        }
440
441        try {
442            theSocket.connect(new UnsupportedSocketAddress(), 1000);
443            fail("No exception for invalid socket address type");
444        } catch (IllegalArgumentException e) {
445            // Expected
446        }
447
448        SocketAddress nonConnectableAddress = new InetSocketAddress(InetAddress
449                .getByAddress(new byte[] { 0, 0, 0, 0 }), 0);
450        try {
451            theSocket.connect(nonConnectableAddress, 1000);
452            fail("No exception when non Connectable Address passed in: ");
453        } catch (SocketException e) {
454            // Expected
455        }
456
457        // Now validate that we get a connect exception if we try to connect to
458        // an address on which nobody is listening
459        theSocket = new Socket();
460        try {
461            theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
462                    0), 0);
463            fail("No exception when connecting to address nobody listening on");
464        } catch (ConnectException e) {
465            // Expected
466        }
467        theSocket.close();
468
469        // Now validate that we can actually connect when somebody is listening
470        ServerSocket server = new ServerSocket(0);
471        InetSocketAddress boundAddress = new InetSocketAddress(InetAddress
472                .getLocalHost(), server.getLocalPort());
473        Socket client = new Socket();
474        client.connect(boundAddress, 0);
475
476        // Validate that when a socket is connected that it answers
477        // correctly to related queries
478        assertTrue("Wrong connected status", client.isConnected());
479        assertFalse("Wrong closed status", client.isClosed());
480        assertTrue("Wrong bound status", client.isBound());
481        assertFalse("Wrong input shutdown status", client.isInputShutdown());
482        assertFalse("Wrong output shutdown status", client.isOutputShutdown());
483        assertTrue("Local port was 0", client.getLocalPort() != 0);
484
485        client.close();
486        server.close();
487
488        // Now validate that we get a connect exception if we try to connect to
489        // an address on which nobody is listening
490        theSocket = new Socket();
491        SocketAddress nonListeningAddress = new InetSocketAddress(InetAddress
492                .getLocalHost(), 42);
493        try {
494            theSocket.connect(nonListeningAddress, 1000);
495            fail("No exception when connecting to address nobody listening on");
496        } catch (ConnectException e) {
497            // Expected
498        } catch (SocketTimeoutException e) {
499            // The other possibility is that the system timed us out.
500        }
501        theSocket.close();
502
503        // Now validate that we get the right exception if we connect when we
504        // are already connected
505        server = new ServerSocket(0);
506        boundAddress = new InetSocketAddress(InetAddress.getLocalHost(), server
507                .getLocalPort());
508        client = new Socket();
509        client.connect(boundAddress, 10000);
510
511        try {
512            client.connect(boundAddress, 10000);
513            fail("No exception when we try to connect on a connected socket: ");
514        } catch (SocketException e) {
515            // Expected
516        }
517        client.close();
518        server.close();
519    }
520
521    /**
522     * @tests java.net.Socket#Socket()
523     */
524    public void test_Constructor() {
525        // create the socket and then validate some basic state
526        Socket s = new Socket();
527        assertFalse("new socket should not be connected", s.isConnected());
528        assertFalse("new socket should not be bound", s.isBound());
529        assertFalse("new socket should not be closed", s.isClosed());
530        assertFalse("new socket should not be in InputShutdown", s
531                .isInputShutdown());
532        assertFalse("new socket should not be in OutputShutdown", s
533                .isOutputShutdown());
534    }
535
536    /**
537     * @tests java.net.Socket#Socket(java.lang.String, int)
538     */
539    public void test_ConstructorLjava_lang_StringI() throws IOException {
540        ServerSocket server = new ServerSocket(0);
541        Socket client = new Socket(InetAddress.getLocalHost(), server
542                .getLocalPort());
543
544        assertEquals("Failed to create socket", server.getLocalPort(), client
545                .getPort());
546
547        // Regression for HARMONY-946
548        ServerSocket ss = new ServerSocket(0);
549        Socket s = new Socket("0.0.0.0", ss.getLocalPort());
550        ss.close();
551        s.close();
552    }
553
554    /**
555     * @tests java.net.Socket#Socket(java.lang.String, int,
556     *        java.net.InetAddress, int)
557     */
558    public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI()
559            throws IOException {
560
561        ServerSocket server = new ServerSocket(0);
562        int serverPort = server.getLocalPort();
563        Socket client = new Socket(InetAddress.getLocalHost().getHostName(),
564                serverPort, InetAddress.getLocalHost(), 0);
565        assertTrue("Failed to create socket", client.getPort() == serverPort);
566        client.close();
567
568        Socket theSocket = null;
569        try {
570            theSocket = new Socket("127.0.0.1", serverPort, InetAddress
571                    .getLocalHost(), 0);
572        } catch (IOException e) {
573            // check here if InetAddress.getLocalHost() is returning the
574            // loopback address, if so that is likely the cause of the failure
575            assertFalse(
576                    "Misconfiguration - local host is the loopback address",
577                    InetAddress.getLocalHost().isLoopbackAddress());
578            throw e;
579        }
580
581        assertTrue(theSocket.isConnected());
582
583        try {
584            new Socket("127.0.0.1", serverPort, theSocket.getLocalAddress(),
585                    theSocket.getLocalPort());
586            fail("Was able to create two sockets on same port");
587        } catch (IOException e) {
588            // Expected
589        }
590
591        theSocket.close();
592        server.close();
593    }
594
595    /**
596     * @tests java.net.Socket#Socket(java.lang.String, int,
597     *        java.net.InetAddress, int)
598     */
599    public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI_ipv6()
600            throws IOException {
601
602        boolean preferIPv6 = "true".equals(System
603                .getProperty("java.net.preferIPv6Addresses"));
604        boolean preferIPv4 = "true".equals(System
605                .getProperty("java.net.preferIPv4Stack"));
606        boolean runIPv6 = "true".equals(System.getProperty("run.ipv6tests"));
607
608        if (!runIPv6 || !preferIPv6 || preferIPv4) {
609            // This test is not for me
610            return;
611        }
612
613        ServerSocket server = new ServerSocket(0);
614        int serverPort = server.getLocalPort();
615        Socket client = new Socket(InetAddress.getLocalHost().getHostName(),
616                serverPort, InetAddress.getLocalHost(), 0);
617        assertTrue("Failed to create socket", client.getPort() == serverPort);
618        client.close();
619
620        Socket theSocket = null;
621        try {
622            theSocket = new Socket(Support_Configuration.IPv6GlobalAddressJcl4,
623                    serverPort, InetAddress.getLocalHost(), 0);
624        } catch (IOException e) {
625            // check here if InetAddress.getLocalHost() is returning the
626            // loopback address, if so that is likely the cause of the failure
627            assertFalse(
628                    "Misconfiguration - local host is the loopback address",
629                    InetAddress.getLocalHost().isLoopbackAddress());
630            throw e;
631        }
632
633        assertTrue(theSocket.isConnected());
634
635        try {
636            new Socket(Support_Configuration.IPv6GlobalAddressJcl4, serverPort,
637                    theSocket.getLocalAddress(), theSocket.getLocalPort());
638            fail("Was able to create two sockets on same port");
639        } catch (IOException e) {
640            // Expected
641        }
642
643        theSocket.close();
644        server.close();
645    }
646
647    /**
648     * @tests java.net.Socket#Socket(java.lang.String, int, boolean)
649     */
650    @SuppressWarnings("deprecation")
651    public void test_ConstructorLjava_lang_StringIZ() throws IOException {
652        ServerSocket server = new ServerSocket(0);
653        int serverPort = server.getLocalPort();
654        Socket client = new Socket(InetAddress.getLocalHost().getHostAddress(),
655                serverPort, true);
656
657        assertEquals("Failed to create socket", serverPort, client.getPort());
658        client.close();
659
660        client = new Socket(InetAddress.getLocalHost().getHostName(),
661                serverPort, false);
662        client.close();
663        server.close();
664    }
665
666    /**
667     * @tests java.net.Socket#Socket(java.net.InetAddress, int)
668     */
669    public void test_ConstructorLjava_net_InetAddressI() throws IOException {
670        ServerSocket server = new ServerSocket(0);
671        Socket client = new Socket(InetAddress.getLocalHost(), server
672                .getLocalPort());
673
674        assertEquals("Failed to create socket", server.getLocalPort(), client
675                .getPort());
676
677        client.close();
678        server.close();
679    }
680
681    /**
682     * @tests java.net.Socket#Socket(java.net.InetAddress, int,
683     *        java.net.InetAddress, int)
684     */
685    public void test_ConstructorLjava_net_InetAddressILjava_net_InetAddressI()
686            throws IOException {
687        ServerSocket server = new ServerSocket(0);
688        Socket client = new Socket(InetAddress.getLocalHost(), server
689                .getLocalPort(), InetAddress.getLocalHost(), 0);
690        assertNotSame("Failed to create socket", 0, client.getLocalPort());
691    }
692
693    /**
694     * @tests java.net.Socket#Socket(java.net.InetAddress, int, boolean)
695     */
696    @SuppressWarnings("deprecation")
697    public void test_ConstructorLjava_net_InetAddressIZ() throws IOException {
698        ServerSocket server = new ServerSocket(0);
699        int serverPort = server.getLocalPort();
700
701        Socket client = new Socket(InetAddress.getLocalHost(), serverPort, true);
702        assertEquals("Failed to create socket", serverPort, client.getPort());
703
704        client = new Socket(InetAddress.getLocalHost(), serverPort, false);
705        client.close();
706    }
707
708    /**
709     * @tests java.net.Socket#Socket(Proxy)
710     */
711    public void test_ConstructorLjava_net_Proxy_Exception() {
712
713        class MockSecurityManager extends SecurityManager {
714
715            public void checkConnect(String host, int port) {
716                if ("127.0.0.1".equals(host)) {
717                    throw new SecurityException("permission is not allowed");
718                }
719            }
720
721            public void checkPermission(Permission permission) {
722                return;
723            }
724        }
725
726        SocketAddress addr1 = InetSocketAddress.createUnresolved("127.0.0.1",
727                80);
728        SocketAddress addr2 = new InetSocketAddress("localhost", 80);
729
730        Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1);
731        // IllegalArgumentException test
732        try {
733            new Socket(proxy1);
734            fail("should throw IllegalArgumentException");
735        } catch (IllegalArgumentException e) {
736            // expected
737        }
738
739        Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr1);
740        // should not throw any exception
741        new Socket(proxy2);
742        new Socket(Proxy.NO_PROXY);
743
744        // SecurityException test
745        SecurityManager originalSecurityManager = System.getSecurityManager();
746        try {
747            System.setSecurityManager(new MockSecurityManager());
748        } catch (SecurityException e) {
749            System.err
750                    .println("No permission to setSecurityManager, security related test in test_ConstructorLjava_net_Proxy_Security is ignored");
751            return;
752        }
753
754        Proxy proxy3 = new Proxy(Proxy.Type.SOCKS, addr1);
755        Proxy proxy4 = new Proxy(Proxy.Type.SOCKS, addr2);
756        try {
757            try {
758                new Socket(proxy3);
759                fail("should throw SecurityException");
760            } catch (SecurityException e) {
761                // expected
762            }
763            try {
764                new Socket(proxy4);
765                fail("should throw SecurityException");
766            } catch (SecurityException e) {
767                // expected
768            }
769        } finally {
770            System.setSecurityManager(originalSecurityManager);
771        }
772
773    }
774
775    /**
776     * @tests java.net.Socket#getChannel()
777     */
778    public void test_getChannel() {
779        assertNull(new Socket().getChannel());
780    }
781
782    /**
783     * @tests java.net.Socket#getInetAddress()
784     */
785    public void test_getInetAddress() throws IOException {
786        ServerSocket server = new ServerSocket(0);
787        Socket client = new Socket(InetAddress.getLocalHost(), server
788                .getLocalPort());
789
790        assertTrue("Returned incorrect InetAdrees", client.getInetAddress()
791                .equals(InetAddress.getLocalHost()));
792
793        client.close();
794        server.close();
795    }
796
797    /**
798     * @tests java.net.Socket#getInputStream()
799     */
800    public void test_getInputStream() throws IOException {
801        // Simple fetch test
802        ServerSocket server = new ServerSocket(0);
803        Socket client = new Socket(InetAddress.getLocalHost(), server
804                .getLocalPort());
805        InputStream is = client.getInputStream();
806        assertNotNull("Failed to get stream", is);
807        is.close();
808        client.close();
809        server.close();
810    }
811
812    private boolean isUnix() {
813        String osName = System.getProperty("os.name");
814
815        // only comparing ASCII, so assume english locale
816        osName = (osName == null ? null : osName.toLowerCase(Locale.ENGLISH));
817
818        if (osName != null && osName.startsWith("windows")) { //$NON-NLS-1$
819            return false;
820        }
821        return true;
822    }
823
824    /**
825     * @tests java.net.Socket#getKeepAlive()
826     */
827    public void test_getKeepAlive() {
828        try {
829            ServerSocket server = new ServerSocket(0);
830            Socket client = new Socket(InetAddress.getLocalHost(), server
831                    .getLocalPort(), null, 0);
832
833            client.setKeepAlive(true);
834            assertTrue("getKeepAlive false when it should be true", client
835                    .getKeepAlive());
836
837            client.setKeepAlive(false);
838            assertFalse("getKeepAlive true when it should be False", client
839                    .getKeepAlive());
840            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
841        } catch (Exception e) {
842            handleException(e, SO_KEEPALIVE);
843        }
844    }
845
846    /**
847     * @tests java.net.Socket#getLocalAddress()
848     */
849    public void test_getLocalAddress() throws IOException {
850        ServerSocket server = new ServerSocket(0);
851        Socket client = new Socket(InetAddress.getLocalHost(), server
852                .getLocalPort());
853
854        assertTrue("Returned incorrect InetAddress", client.getLocalAddress()
855                .equals(InetAddress.getLocalHost()));
856
857        // now validate that behaviour when the any address is returned
858        String preferIPv4StackValue = System
859                .getProperty("java.net.preferIPv4Stack");
860        String preferIPv6AddressesValue = System
861                .getProperty("java.net.preferIPv6Addresses");
862
863        client = new Socket();
864        client.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
865
866        if (((preferIPv4StackValue == null) || preferIPv4StackValue
867                .equalsIgnoreCase("false"))
868                && (preferIPv6AddressesValue != null)
869                && (preferIPv6AddressesValue.equals("true"))) {
870            assertTrue(
871                    "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=false "
872                            + client.getLocalSocketAddress(), client
873                            .getLocalAddress() instanceof Inet6Address);
874        } else {
875            assertTrue(
876                    "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=true "
877                            + client.getLocalSocketAddress(), client
878                            .getLocalAddress() instanceof Inet4Address);
879        }
880        client.close();
881        server.close();
882    }
883
884    /**
885     * @tests java.net.Socket#getLocalPort()
886     */
887    public void test_getLocalPort() throws IOException {
888        ServerSocket server = new ServerSocket(0);
889        Socket client = new Socket(InetAddress.getLocalHost(), server
890                .getLocalPort());
891
892        assertNotSame("Returned incorrect port", 0, client.getLocalPort());
893
894        client.close();
895        server.close();
896    }
897
898    /**
899     * @tests java.net.Socket#getLocalSocketAddress()
900     */
901    public void test_getLocalSocketAddress() throws IOException {
902        // set up server connect and then validate that we get the right
903        // response for the local address
904        ServerSocket server = new ServerSocket(0);
905        Socket client = new Socket(InetAddress.getLocalHost(), server
906                .getLocalPort());
907        int clientPort = client.getLocalPort();
908
909        assertEquals("Returned incorrect InetSocketAddress(1):",
910                new InetSocketAddress(InetAddress.getLocalHost(), clientPort),
911                client.getLocalSocketAddress());
912        client.close();
913        server.close();
914
915        // now create a socket that is not bound and validate we get the
916        // right answer
917        client = new Socket();
918        assertNull(
919                "Returned incorrect InetSocketAddress -unbound socket- Expected null",
920                client.getLocalSocketAddress());
921
922        // now bind the socket and make sure we get the right answer
923        client.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
924        clientPort = client.getLocalPort();
925        assertEquals("Returned incorrect InetSocketAddress(2):",
926                new InetSocketAddress(InetAddress.getLocalHost(), clientPort),
927                client.getLocalSocketAddress());
928        client.close();
929
930        // now validate the behaviour when the any address is returned
931        client = new Socket();
932        client.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
933
934        String preferIPv4StackValue = System
935                .getProperty("java.net.preferIPv4Stack");
936        String preferIPv6AddressesValue = System
937                .getProperty("java.net.preferIPv6Addresses");
938        if (((preferIPv4StackValue == null) || preferIPv4StackValue
939                .equalsIgnoreCase("false"))
940                && (preferIPv6AddressesValue != null)
941                && (preferIPv6AddressesValue.equals("true"))) {
942            assertTrue(
943                    "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=false "
944                            + client.getLocalSocketAddress(),
945                    ((InetSocketAddress) client.getLocalSocketAddress())
946                            .getAddress() instanceof Inet6Address);
947        } else {
948            assertTrue(
949                    "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=true "
950                            + client.getLocalSocketAddress(),
951                    ((InetSocketAddress) client.getLocalSocketAddress())
952                            .getAddress() instanceof Inet4Address);
953        }
954        client.close();
955
956        // now validate the same for getLocalAddress
957        client = new Socket();
958        client.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
959        if (((preferIPv4StackValue == null) || preferIPv4StackValue
960                .equalsIgnoreCase("false"))
961                && (preferIPv6AddressesValue != null)
962                && (preferIPv6AddressesValue.equals("true"))) {
963            assertTrue(
964                    "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=false "
965                            + client.getLocalSocketAddress(),
966                    ((InetSocketAddress) client.getLocalSocketAddress())
967                            .getAddress() instanceof Inet6Address);
968        } else {
969            assertTrue(
970                    "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=true "
971                            + client.getLocalSocketAddress(),
972                    ((InetSocketAddress) client.getLocalSocketAddress())
973                            .getAddress() instanceof Inet4Address);
974        }
975        client.close();
976    }
977
978    /**
979     * @tests java.net.Socket#getOOBInline()
980     */
981    public void test_getOOBInline() {
982        try {
983            Socket theSocket = new Socket();
984
985            theSocket.setOOBInline(true);
986            assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
987
988            theSocket.setOOBInline(false);
989            assertFalse("expected OOBIline to be false", theSocket
990                    .getOOBInline());
991
992            theSocket.setOOBInline(false);
993            assertFalse("expected OOBIline to be false", theSocket
994                    .getOOBInline());
995
996            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_OOBINLINE);
997        } catch (Exception e) {
998            handleException(e, SO_OOBINLINE);
999        }
1000    }
1001
1002    /**
1003     * @tests java.net.Socket#getOutputStream()
1004     */
1005    @SuppressWarnings("deprecation")
1006    public void test_getOutputStream() throws IOException {
1007        // Simple fetch test
1008        ServerSocket server = new ServerSocket(0);
1009        Socket client = new Socket(InetAddress.getLocalHost(), server
1010                .getLocalPort());
1011        OutputStream os = client.getOutputStream();
1012        assertNotNull("Failed to get stream", os);
1013        os.close();
1014        client.close();
1015        server.close();
1016
1017        // Simple read/write test over the IO streams
1018        final ServerSocket sinkServer = new ServerSocket(0);
1019        Runnable runnable = new Runnable() {
1020            public void run() {
1021                try {
1022                    Socket worker = sinkServer.accept();
1023                    sinkServer.close();
1024                    InputStream in = worker.getInputStream();
1025                    in.read();
1026                    in.close();
1027                    worker.close();
1028                } catch (IOException e) {
1029                    fail();
1030                }
1031            }
1032        };
1033        Thread thread = new Thread(runnable, "Socket.getOutputStream");
1034        thread.start();
1035
1036        Socket pingClient = new Socket(InetAddress.getLocalHost(), sinkServer
1037                .getLocalPort());
1038
1039        // Busy wait until the client is connected.
1040        int c = 0;
1041        while (!pingClient.isConnected()) {
1042            try {
1043                Thread.sleep(200);
1044            } catch (InterruptedException e) {
1045            }
1046            if (++c > 4) {
1047                fail("thread is not alive");
1048            }
1049        }
1050
1051        // Write some data to the server
1052        OutputStream out = pingClient.getOutputStream();
1053        out.write(new byte[256]);
1054
1055        // Wait for the server to finish
1056        Thread.yield();
1057        c = 0;
1058        while (thread.isAlive()) {
1059            try {
1060                Thread.sleep(200);
1061            } catch (InterruptedException e) {
1062            }
1063            if (++c > 4) {
1064                fail("read call did not exit");
1065            }
1066        }
1067
1068        // Subsequent writes should throw an exception
1069        try {
1070            // The output buffer may remain valid until the close completes
1071            for (int i = 0; i < 400; i++) {
1072                out.write(new byte[256]);
1073            }
1074            fail("write to closed socket did not cause exception");
1075        } catch (IOException e) {
1076            // Expected
1077        }
1078
1079        out.close();
1080        pingClient.close();
1081        sinkServer.close();
1082
1083        // Regression test for HARMONY-873
1084        ServerSocket ss2 = new ServerSocket(0);
1085        Socket s = new Socket("127.0.0.1", ss2.getLocalPort());
1086        ss2.accept();
1087        s.shutdownOutput();
1088        try {
1089            s.getOutputStream();
1090            fail("should throw SocketException");
1091        } catch (SocketException e) {
1092            // expected
1093        }
1094    }
1095
1096    /**
1097     * @tests java.net.Socket#getPort()
1098     */
1099    public void test_getPort() throws IOException {
1100        ServerSocket server = new ServerSocket(0);
1101        int serverPort = server.getLocalPort();
1102        Socket client = new Socket(InetAddress.getLocalHost(), serverPort);
1103
1104        assertEquals("Returned incorrect port", serverPort, client.getPort());
1105
1106        client.close();
1107        server.close();
1108    }
1109
1110    /**
1111     * @tests java.net.Socket#getReceiveBufferSize()
1112     */
1113    public void test_getReceiveBufferSize() throws IOException {
1114        ServerSocket server = new ServerSocket(0);
1115        Socket client = new Socket(InetAddress.getLocalHost(), server
1116                .getLocalPort());
1117
1118        try {
1119            client.setReceiveBufferSize(130);
1120            assertTrue("Incorrect buffer size",
1121                    client.getReceiveBufferSize() >= 130);
1122
1123            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
1124        } catch (Exception e) {
1125            handleException(e, SO_RCVBUF);
1126        } finally {
1127            client.close();
1128            server.close();
1129        }
1130    }
1131
1132    /**
1133     * @tests java.net.Socket#getRemoteSocketAddress()
1134     */
1135    public void test_getRemoteSocketAddress() throws IOException {
1136        // set up server connect and then validate that we get the right
1137        // response for the remote address
1138        ServerSocket server = new ServerSocket(0);
1139        int serverPort = server.getLocalPort();
1140        Socket client = new Socket(InetAddress.getLocalHost(), serverPort);
1141
1142        assertEquals("Returned incorrect InetSocketAddress(1):",
1143                new InetSocketAddress(InetAddress.getLocalHost(), serverPort),
1144                client.getRemoteSocketAddress());
1145        client.close();
1146
1147        // now create one that is not connected and validate that we get the
1148        // right answer
1149        Socket theSocket = new Socket();
1150        theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
1151        assertNull("Returned incorrect InetSocketAddress -unconnected socket:",
1152                theSocket.getRemoteSocketAddress());
1153
1154        // now connect and validate we get the right answer
1155        theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
1156                serverPort));
1157        assertEquals("Returned incorrect InetSocketAddress(2):",
1158                new InetSocketAddress(InetAddress.getLocalHost(), serverPort),
1159                theSocket.getRemoteSocketAddress());
1160        theSocket.close();
1161
1162        server.close();
1163    }
1164
1165    /**
1166     * @tests java.net.Socket#getReuseAddress()
1167     */
1168    public void test_getReuseAddress() {
1169        try {
1170            Socket theSocket = new Socket();
1171            theSocket.setReuseAddress(true);
1172            assertTrue("getReuseAddress false when it should be true",
1173                    theSocket.getReuseAddress());
1174            theSocket.setReuseAddress(false);
1175            assertFalse("getReuseAddress true when it should be False",
1176                    theSocket.getReuseAddress());
1177
1178            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1179        } catch (Exception e) {
1180            handleException(e, SO_REUSEADDR);
1181        }
1182    }
1183
1184    /**
1185     * @tests java.net.Socket#getSendBufferSize()
1186     */
1187    public void test_getSendBufferSize() throws IOException {
1188        ServerSocket server = new ServerSocket(0);
1189        Socket client = new Socket(InetAddress.getLocalHost(), server
1190                .getLocalPort());
1191
1192        try {
1193            client.setSendBufferSize(134);
1194            assertTrue("Incorrect buffer size",
1195                    client.getSendBufferSize() >= 134);
1196
1197            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
1198        } catch (Exception e) {
1199            handleException(e, SO_SNDBUF);
1200        } finally {
1201            client.close();
1202            server.close();
1203        }
1204    }
1205
1206    /**
1207     * @tests java.net.Socket#getSoLinger()
1208     */
1209    public void test_getSoLinger() throws IOException {
1210        ServerSocket server = new ServerSocket(0);
1211        Socket client = new Socket(InetAddress.getLocalHost(), server
1212                .getLocalPort());
1213
1214        try {
1215            client.setSoLinger(true, 200);
1216            assertEquals("Returned incorrect linger", 200, client.getSoLinger());
1217            client.setSoLinger(false, 0);
1218
1219            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
1220        } catch (Exception e) {
1221            handleException(e, SO_LINGER);
1222        } finally {
1223            client.close();
1224            server.close();
1225        }
1226    }
1227
1228    /**
1229     * @tests java.net.Socket#getSoTimeout()
1230     */
1231    public void test_getSoTimeout() throws IOException {
1232        ServerSocket server = new ServerSocket(0);
1233        Socket client = new Socket(InetAddress.getLocalHost(), server
1234                .getLocalPort());
1235
1236        try {
1237            client.setSoTimeout(100);
1238            assertEquals("Returned incorrect sotimeout", 100, client
1239                    .getSoTimeout());
1240
1241            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
1242        } catch (Exception e) {
1243            handleException(e, SO_TIMEOUT);
1244        } finally {
1245            client.close();
1246            server.close();
1247        }
1248    }
1249
1250    /**
1251     * @tests java.net.Socket#getTcpNoDelay()
1252     */
1253    public void test_getTcpNoDelay() throws IOException {
1254        ServerSocket server = new ServerSocket(0);
1255        Socket client = new Socket(InetAddress.getLocalHost(), server
1256                .getLocalPort());
1257
1258        try {
1259            boolean bool = !client.getTcpNoDelay();
1260            client.setTcpNoDelay(bool);
1261            assertTrue("Failed to get no delay setting: "
1262                    + client.getTcpNoDelay(), client.getTcpNoDelay() == bool);
1263
1264            ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
1265        } catch (Exception e) {
1266            handleException(e, TCP_NODELAY);
1267        } finally {
1268            client.close();
1269            server.close();
1270        }
1271    }
1272
1273    /**
1274     * @tests java.net.Socket#getTrafficClass()
1275     */
1276    public void test_getTrafficClass() {
1277        try {
1278            /*
1279             * We cannot actually check that the values are set as if a platform
1280             * does not support the option then it may come back unset even
1281             * though we set it so just get the value to make sure we can get it
1282             */
1283            int trafficClass = new Socket().getTrafficClass();
1284            assertTrue(0 <= trafficClass);
1285            assertTrue(trafficClass <= 255);
1286
1287            ensureExceptionThrownIfOptionIsUnsupportedOnOS(IP_TOS);
1288        } catch (Exception e) {
1289            handleException(e, IP_TOS);
1290        }
1291    }
1292
1293    /**
1294     * @tests java.net.Socket#isBound()
1295     */
1296    public void test_isBound() throws IOException {
1297        ServerSocket server = new ServerSocket(0);
1298        Socket client = new Socket(InetAddress.getLocalHost(), server
1299                .getLocalPort());
1300        Socket worker = server.accept();
1301
1302        assertTrue("Socket indicated  not bound when it should be (1)", client
1303                .isBound());
1304        worker.close();
1305        client.close();
1306        server.close();
1307
1308        client = new Socket();
1309        assertFalse("Socket indicated bound when it was not (2)", client
1310                .isBound());
1311
1312        server = new ServerSocket();
1313        server.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
1314        InetSocketAddress boundAddress = new InetSocketAddress(server
1315                .getInetAddress(), server.getLocalPort());
1316        client.connect(boundAddress);
1317        worker = server.accept();
1318        assertTrue("Socket indicated not bound when it should be (2)", client
1319                .isBound());
1320        worker.close();
1321        client.close();
1322        server.close();
1323
1324        // now test when we bind explicitly
1325        InetSocketAddress theLocalAddress = new InetSocketAddress(InetAddress
1326                .getLocalHost(), 0);
1327        client = new Socket();
1328        assertFalse("Socket indicated bound when it was not (3)", client
1329                .isBound());
1330        client.bind(theLocalAddress);
1331        assertTrue("Socket indicated not bound when it should be (3a)", client
1332                .isBound());
1333        client.close();
1334        assertTrue("Socket indicated not bound when it should be (3b)", client
1335                .isBound());
1336    }
1337
1338    /**
1339     * @tests java.net.Socket#isClosed()
1340     */
1341    public void test_isClosed() throws IOException {
1342        ServerSocket server = new ServerSocket(0);
1343        Socket client = new Socket(InetAddress.getLocalHost(), server
1344                .getLocalPort());
1345        Socket worker = server.accept();
1346
1347        // validate isClosed returns expected values
1348        assertFalse("Socket should indicate it is not closed(1):", client
1349                .isClosed());
1350        client.close();
1351        assertTrue("Socket should indicate it is closed(1):", client.isClosed());
1352
1353        // validate that isClosed works ok for sockets returned from
1354        // ServerSocket.accept()
1355        assertFalse("Accepted Socket should indicate it is not closed:", worker
1356                .isClosed());
1357        worker.close();
1358        assertTrue("Accepted Socket should indicate it is closed:", worker
1359                .isClosed());
1360
1361        // and finally for the server socket
1362        assertFalse("Server Socket should indicate it is not closed:", server
1363                .isClosed());
1364        server.close();
1365        assertTrue("Server Socket should indicate it is closed:", server
1366                .isClosed());
1367    }
1368
1369    /**
1370     * @tests java.net.Socket#isConnected()
1371     */
1372    public void test_isConnected() throws IOException {
1373        ServerSocket server = new ServerSocket(0);
1374        Socket client = new Socket(InetAddress.getLocalHost(), server
1375                .getLocalPort());
1376        Socket worker = server.accept();
1377
1378        assertTrue("Socket indicated  not connected when it should be", client
1379                .isConnected());
1380        client.close();
1381        worker.close();
1382        server.close();
1383
1384        // now do it with the new constructors and revalidate
1385        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
1386                .getLocalHost(), 0);
1387        client = new Socket();
1388        assertFalse("Socket indicated connected when it was not", client
1389                .isConnected());
1390
1391        server = new ServerSocket();
1392        server.bind(theAddress);
1393        InetSocketAddress boundAddress = new InetSocketAddress(server
1394                .getInetAddress(), server.getLocalPort());
1395        client.connect(boundAddress);
1396        worker = server.accept();
1397        assertTrue("Socket indicated  not connected when it should be", client
1398                .isConnected());
1399        client.close();
1400        worker.close();
1401        server.close();
1402    }
1403
1404    /**
1405     * @tests java.net.Socket#isInputShutdown()
1406     */
1407    public void test_isInputShutdown() throws IOException {
1408        ServerSocket server = new ServerSocket(0);
1409        Socket client = new Socket(InetAddress.getLocalHost(), server
1410                .getLocalPort());
1411
1412        Socket worker = server.accept();
1413        InputStream theInput = client.getInputStream();
1414        OutputStream theOutput = worker.getOutputStream();
1415
1416        // make sure we get the right answer with newly connected socket
1417        assertFalse("Socket indicated input shutdown when it should not have",
1418                client.isInputShutdown());
1419
1420        // shutdown the output
1421        client.shutdownInput();
1422
1423        // make sure we get the right answer once it is shut down
1424        assertTrue(
1425                "Socket indicated input was NOT shutdown when it should have been",
1426                client.isInputShutdown());
1427
1428        client.close();
1429        worker.close();
1430        server.close();
1431
1432        // make sure we get the right answer for closed sockets
1433        assertFalse(
1434                "Socket indicated input was shutdown when socket was closed",
1435                worker.isInputShutdown());
1436
1437        theInput.close();
1438        theOutput.close();
1439    }
1440
1441    /**
1442     * @tests java.net.Socket#isOutputShutdown()
1443     */
1444    public void test_isOutputShutdown() throws IOException {
1445        ServerSocket server = new ServerSocket(0);
1446        Socket client = new Socket(InetAddress.getLocalHost(), server
1447                .getLocalPort());
1448
1449        Socket worker = server.accept();
1450        InputStream theInput = client.getInputStream();
1451        OutputStream theOutput = worker.getOutputStream();
1452
1453        // make sure we get the right answer with newly connected socket
1454        assertFalse("Socket indicated output shutdown when it should not have",
1455                worker.isOutputShutdown());
1456
1457        // shutdown the output
1458        worker.shutdownOutput();
1459
1460        // make sure we get the right answer once it is shut down
1461        assertTrue(
1462                "Socket indicated output was NOT shutdown when it should have been",
1463                worker.isOutputShutdown());
1464
1465        client.close();
1466        worker.close();
1467        server.close();
1468
1469        // make sure we get the right answer for closed sockets
1470        assertFalse(
1471                "Socket indicated output was output shutdown when the socket was closed",
1472                client.isOutputShutdown());
1473
1474        theInput.close();
1475        theOutput.close();
1476    }
1477
1478    /**
1479     * @tests java.net.Socket#sendUrgentData(int)
1480     */
1481    public void test_sendUrgentDataI() throws Exception {
1482        /*
1483         * Some platforms may not support urgent data in this case we will not
1484         * run these tests. For now run on all platforms until we find those
1485         * that do not support urgent data
1486         */
1487        String platform = System.getProperty("os.name");
1488        if (platform.equals("Dummy")) {
1489            return;
1490        }
1491
1492        /*
1493         * Test 1: Validate that when OOBInline is false that any urgent data is
1494         * silently ignored
1495         */
1496        InetAddress localHost = InetAddress.getLocalHost();
1497        ServerSocket server = new ServerSocket(0, 5, localHost);
1498        SocketAddress serverAddress = new InetSocketAddress(localHost, server
1499                .getLocalPort());
1500
1501        Socket client = new Socket();
1502        client.setOOBInline(false);
1503
1504        client.connect(serverAddress);
1505        Socket worker = server.accept();
1506        worker.setTcpNoDelay(true);
1507        OutputStream theOutput = worker.getOutputStream();
1508
1509        // Send the regular data
1510        byte[] sendBytes = new String("Test").getBytes();
1511        theOutput.write(sendBytes);
1512        theOutput.flush();
1513
1514        // Send the urgent data byte which should not be received
1515        worker.sendUrgentData("UrgentData".getBytes()[0]);
1516        theOutput.write(sendBytes);
1517        worker.shutdownOutput();
1518        worker.close();
1519
1520        // Try to read the bytes back
1521        int totalBytesRead = 0;
1522        byte[] myBytes = new byte[100];
1523        InputStream theInput = client.getInputStream();
1524        while (true) {
1525            int bytesRead = theInput.read(myBytes, totalBytesRead,
1526                    myBytes.length - totalBytesRead);
1527            if (bytesRead == -1) {
1528                break;
1529            }
1530            totalBytesRead = totalBytesRead + bytesRead;
1531        }
1532
1533        client.close();
1534        server.close();
1535
1536        byte[] expectBytes = new byte[2 * sendBytes.length];
1537        System.arraycopy(sendBytes, 0, expectBytes, 0, sendBytes.length);
1538        System.arraycopy(sendBytes, 0, expectBytes, sendBytes.length,
1539                sendBytes.length);
1540
1541        byte[] resultBytes = new byte[totalBytesRead];
1542        System.arraycopy(myBytes, 0, resultBytes, 0, totalBytesRead);
1543
1544        assertTrue("Urgent data was received", Arrays.equals(expectBytes,
1545                resultBytes));
1546
1547        /*
1548         * Test 2: Now validate that urgent data is received as expected. Expect
1549         * that it should be between the two writes.
1550         */
1551        server = new ServerSocket(0, 5, localHost);
1552        serverAddress = new InetSocketAddress(localHost, server.getLocalPort());
1553
1554        client = new Socket();
1555        client.setOOBInline(true);
1556
1557        client.connect(serverAddress);
1558        worker = server.accept();
1559        worker.setTcpNoDelay(true);
1560        theOutput = worker.getOutputStream();
1561
1562        // Send the regular data
1563        sendBytes = new String("Test - Urgent Data").getBytes();
1564        theOutput.write(sendBytes);
1565
1566        // Send the urgent data (one byte) which should be received
1567        client.setOOBInline(true);
1568        byte urgentByte = "UrgentData".getBytes()[0];
1569        worker.sendUrgentData(urgentByte);
1570
1571        // Send more data, the urgent byte must stay in position
1572        theOutput.write(sendBytes);
1573        worker.shutdownOutput();
1574        worker.close();
1575
1576        // Try to read the bytes back
1577        totalBytesRead = 0;
1578        myBytes = new byte[100];
1579        theInput = client.getInputStream();
1580        while (true) {
1581            int bytesRead = theInput.read(myBytes, totalBytesRead,
1582                    myBytes.length - totalBytesRead);
1583            if (bytesRead == -1) {
1584                break;
1585            }
1586            totalBytesRead = totalBytesRead + bytesRead;
1587        }
1588
1589        client.close();
1590        server.close();
1591
1592        expectBytes = new byte[2 * sendBytes.length + 1];
1593        System.arraycopy(sendBytes, 0, expectBytes, 0, sendBytes.length);
1594        expectBytes[sendBytes.length] = urgentByte;
1595        System.arraycopy(sendBytes, 0, expectBytes, sendBytes.length + 1,
1596                sendBytes.length);
1597
1598        resultBytes = new byte[totalBytesRead];
1599        System.arraycopy(myBytes, 0, resultBytes, 0, totalBytesRead);
1600
1601        assertTrue("Urgent data was not received with one urgent byte", Arrays
1602                .equals(expectBytes, resultBytes));
1603
1604        /*
1605         * Test 3: Now validate that urgent data is received as expected. Expect
1606         * that it should be between the two writes.
1607         */
1608        server = new ServerSocket(0, 5, localHost);
1609        serverAddress = new InetSocketAddress(localHost, server.getLocalPort());
1610
1611        client = new Socket();
1612        client.setOOBInline(true);
1613
1614        client.connect(serverAddress);
1615        worker = server.accept();
1616        worker.setTcpNoDelay(true);
1617        theOutput = worker.getOutputStream();
1618
1619        // Send the regular data
1620        sendBytes = new String("Test - Urgent Data").getBytes();
1621        theOutput.write(sendBytes);
1622
1623        // Send the urgent data (one byte) which should be received
1624        client.setOOBInline(true);
1625        byte urgentByte1 = "UrgentData".getBytes()[0];
1626        byte urgentByte2 = "UrgentData".getBytes()[1];
1627        worker.sendUrgentData(urgentByte1);
1628        worker.sendUrgentData(urgentByte2);
1629
1630        // Send more data, the urgent byte must stay in position
1631        theOutput.write(sendBytes);
1632        worker.shutdownOutput();
1633        worker.close();
1634
1635        // Try to read the bytes back
1636        totalBytesRead = 0;
1637        myBytes = new byte[100];
1638        theInput = client.getInputStream();
1639        while (true) {
1640            int bytesRead = theInput.read(myBytes, totalBytesRead,
1641                    myBytes.length - totalBytesRead);
1642            if (bytesRead == -1) {
1643                break;
1644            }
1645            totalBytesRead = totalBytesRead + bytesRead;
1646        }
1647
1648        client.close();
1649        server.close();
1650
1651        expectBytes = new byte[2 * sendBytes.length + 2];
1652        System.arraycopy(sendBytes, 0, expectBytes, 0, sendBytes.length);
1653        expectBytes[sendBytes.length] = urgentByte1;
1654        expectBytes[sendBytes.length + 1] = urgentByte2;
1655        System.arraycopy(sendBytes, 0, expectBytes, sendBytes.length + 2,
1656                sendBytes.length);
1657
1658        resultBytes = new byte[totalBytesRead];
1659        System.arraycopy(myBytes, 0, resultBytes, 0, totalBytesRead);
1660
1661        assertTrue("Urgent data was not received with two urgent bytes", Arrays
1662                .equals(expectBytes, resultBytes));
1663
1664        /*
1665         * Test 4: Now test the case where there is only urgent data.
1666         */
1667        server = new ServerSocket(0, 5, localHost);
1668        serverAddress = new InetSocketAddress(localHost, server.getLocalPort());
1669
1670        client = new Socket();
1671        client.setOOBInline(true);
1672
1673        client.connect(serverAddress);
1674        worker = server.accept();
1675        worker.setTcpNoDelay(true);
1676
1677        // Send the urgent data (one byte) which should be received
1678        client.setOOBInline(true);
1679        urgentByte = "UrgentData".getBytes()[0];
1680        worker.sendUrgentData(urgentByte);
1681        worker.close();
1682
1683        // Try to read the bytes back
1684        theInput = client.getInputStream();
1685        int byteRead = theInput.read();
1686
1687        client.close();
1688        server.close();
1689
1690        assertEquals("Sole urgent data was not received",
1691                (int) (urgentByte & 0xff), byteRead);
1692    }
1693
1694    /**
1695     * @tests java.net.Socket#setKeepAlive(boolean)
1696     */
1697    public void test_setKeepAliveZ() throws IOException {
1698
1699        class TestSocket extends Socket {
1700            public TestSocket(SocketImpl impl) throws SocketException {
1701                super(impl);
1702            }
1703        }
1704
1705        // There is not really a good test for this as it is there to detect
1706        // crashed machines. Just make sure we can set it
1707        ServerSocket server = new ServerSocket(0);
1708        Socket client = new Socket(InetAddress.getLocalHost(), server
1709                .getLocalPort());
1710
1711        try {
1712            client.setKeepAlive(true);
1713            client.setKeepAlive(false);
1714            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
1715        } catch (Exception e) {
1716            handleException(e, SO_KEEPALIVE);
1717        } finally {
1718            client.close();
1719            server.close();
1720        }
1721
1722        // Regression test for HARMONY-1136
1723        new TestSocket((SocketImpl) null).setKeepAlive(true);
1724    }
1725
1726    /**
1727     * @tests java.net.Socket#setOOBInline(boolean)
1728     */
1729    public void test_setOOBInlineZ() {
1730        try {
1731            Socket theSocket = new Socket();
1732            theSocket.setOOBInline(true);
1733            assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
1734
1735            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_OOBINLINE);
1736        } catch (Exception e) {
1737            handleException(e, SO_OOBINLINE);
1738        }
1739    }
1740
1741    /**
1742     * @tests java.net.Socket#setPerformancePreference()
1743     */
1744    public void test_setPerformancePreference_Int_Int_Int() throws IOException {
1745        Socket theSocket = new Socket();
1746        theSocket.setPerformancePreferences(1, 1, 1);
1747    }
1748
1749    /**
1750     * @tests java.net.Socket#setReceiveBufferSize(int)
1751     */
1752    public void test_setReceiveBufferSizeI() throws IOException {
1753        ServerSocket server = new ServerSocket(0);
1754        Socket client = new Socket(InetAddress.getLocalHost(), server
1755                .getLocalPort());
1756
1757        try {
1758            client.setReceiveBufferSize(130);
1759            assertTrue("Incorrect buffer size",
1760                    client.getReceiveBufferSize() >= 130);
1761
1762            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
1763        } catch (Exception e) {
1764            handleException(e, SO_RCVBUF);
1765        } finally {
1766            client.close();
1767            server.close();
1768        }
1769    }
1770
1771    /**
1772     * @tests java.net.Socket#setReuseAddress(boolean)
1773     */
1774    public void test_setReuseAddressZ() throws UnknownHostException {
1775
1776        try {
1777            Socket theSocket = new Socket();
1778            theSocket.setReuseAddress(false);
1779            // Bind to any available port on the given address
1780            theSocket
1781                    .bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
1782            InetSocketAddress localAddress1 = new InetSocketAddress(theSocket
1783                    .getLocalAddress(), theSocket.getLocalPort());
1784
1785            Socket theSocket2 = new Socket();
1786            theSocket2.setReuseAddress(false);
1787
1788            /*
1789             * Try to invoke a bind while the port is busy (TIME_WAIT). Note
1790             * that we may not succeed, which will cause the test to pass
1791             * without testing the reuseaddr behavior.
1792             */
1793            theSocket.close();
1794            theSocket2.bind(localAddress1);
1795
1796            theSocket2.close();
1797
1798            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1799        } catch (Exception e) {
1800            handleException(e, SO_REUSEADDR);
1801        }
1802    }
1803
1804    /**
1805     * @tests java.net.Socket#setSendBufferSize(int)
1806     */
1807    public void test_setSendBufferSizeI() throws IOException {
1808        ServerSocket server = new ServerSocket(0);
1809        Socket client = new Socket(InetAddress.getLocalHost(), server
1810                .getLocalPort());
1811
1812        try {
1813            client.setSendBufferSize(134);
1814            assertTrue("Incorrect buffer size",
1815                    client.getSendBufferSize() >= 134);
1816            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
1817        } catch (Exception e) {
1818            handleException(e, SO_SNDBUF);
1819        } finally {
1820            client.close();
1821            server.close();
1822        }
1823    }
1824
1825    /**
1826     * @tests java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
1827     */
1828    public void test_setSocketImplFactoryLjava_net_SocketImplFactory() {
1829        // Cannot test as setting will cause the factory to be changed for
1830        // all subsequent sockets
1831    }
1832
1833    /**
1834     * @tests java.net.Socket#setSoLinger(boolean, int)
1835     */
1836    public void test_setSoLingerZI() throws IOException {
1837        ServerSocket server = new ServerSocket(0);
1838        Socket client = new Socket(InetAddress.getLocalHost(), server
1839                .getLocalPort());
1840
1841        try {
1842            client.setSoLinger(true, 500);
1843            assertEquals("Set incorrect linger", 500, client.getSoLinger());
1844            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
1845            client.setSoLinger(false, 0);
1846        } catch (Exception e) {
1847            handleException(e, SO_LINGER);
1848        } finally {
1849            client.close();
1850            server.close();
1851        }
1852    }
1853
1854    /**
1855     * @tests java.net.Socket#setSoTimeout(int)
1856     */
1857    public void test_setSoTimeoutI() throws IOException {
1858        ServerSocket server = new ServerSocket(0);
1859        Socket client = new Socket(InetAddress.getLocalHost(), server
1860                .getLocalPort());
1861
1862        try {
1863            client.setSoTimeout(100);
1864            assertEquals("Set incorrect sotimeout", 100, client.getSoTimeout());
1865            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
1866        } catch (Exception e) {
1867            handleException(e, SO_TIMEOUT);
1868        } finally {
1869            client.close();
1870            server.close();
1871        }
1872    }
1873
1874    /**
1875     * @tests java.net.Socket#setTcpNoDelay(boolean)
1876     */
1877    public void test_setTcpNoDelayZ() throws IOException {
1878        ServerSocket server = new ServerSocket(0);
1879        Socket client = new Socket(InetAddress.getLocalHost(), server
1880                .getLocalPort());
1881
1882        try {
1883            boolean bool;
1884            client.setTcpNoDelay(bool = !client.getTcpNoDelay());
1885            assertTrue("Failed to set no delay setting: "
1886                    + client.getTcpNoDelay(), client.getTcpNoDelay() == bool);
1887
1888            ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
1889        } catch (Exception e) {
1890            handleException(e, TCP_NODELAY);
1891        } finally {
1892            client.close();
1893            server.close();
1894        }
1895    }
1896
1897    /**
1898     * @tests java.net.Socket#setTrafficClass(int)
1899     */
1900    public void test_setTrafficClassI() {
1901        try {
1902            int IPTOS_LOWCOST = 0x2;
1903            int IPTOS_RELIABILTY = 0x4;
1904            int IPTOS_THROUGHPUT = 0x8;
1905            int IPTOS_LOWDELAY = 0x10;
1906
1907            Socket theSocket = new Socket();
1908
1909            // validate that value set must be between 0 and 255
1910            try {
1911                theSocket.setTrafficClass(256);
1912                fail("No exception was thrown when traffic class set to 256");
1913            } catch (IllegalArgumentException e) {
1914                // Expected
1915            }
1916
1917            try {
1918                theSocket.setTrafficClass(-1);
1919                fail("No exception was thrown when traffic class set to -1");
1920            } catch (IllegalArgumentException e) {
1921                // Expected
1922            }
1923
1924            // now validate that we can set it to some good values
1925            theSocket.setTrafficClass(IPTOS_LOWCOST);
1926            theSocket.setTrafficClass(IPTOS_RELIABILTY);
1927            theSocket.setTrafficClass(IPTOS_THROUGHPUT);
1928            theSocket.setTrafficClass(IPTOS_LOWDELAY);
1929
1930            ensureExceptionThrownIfOptionIsUnsupportedOnOS(IP_TOS);
1931        } catch (Exception e) {
1932            handleException(e, IP_TOS);
1933        }
1934    }
1935
1936    /**
1937     * @tests java.net.Socket#shutdownInput()
1938     */
1939    @SuppressWarnings("deprecation")
1940    public void test_shutdownInput() throws IOException {
1941        ServerSocket server = new ServerSocket(0);
1942        int port = server.getLocalPort();
1943        Socket client = new Socket(InetAddress.getLocalHost(), port);
1944
1945        Socket worker = server.accept();
1946        worker.setTcpNoDelay(true);
1947
1948        InputStream theInput = client.getInputStream();
1949        OutputStream theOutput = worker.getOutputStream();
1950
1951        // shutdown the input
1952        client.shutdownInput();
1953
1954        // send the regular data
1955        String sendString = new String("Test");
1956        theOutput.write(sendString.getBytes());
1957        theOutput.flush();
1958
1959        // RI fails here. It is a RI bug not to return 0 to indicate EOF
1960        assertEquals(0, theInput.available());
1961
1962        client.close();
1963        server.close();
1964
1965        // Regression test for HARMONY-2944
1966        // Port 0 is not allowed to be used in connect() on some platforms,
1967        // Since server has been closed here, so the port is free now
1968        Socket s = new Socket("0.0.0.0", port, false);
1969        s.shutdownInput();
1970        try {
1971            s.shutdownInput();
1972            fail("should throw SocketException");
1973        } catch (SocketException se) {
1974            // Expected
1975        }
1976        s.close();
1977    }
1978
1979    /**
1980     * @tests java.net.Socket#shutdownOutput()
1981     */
1982    @SuppressWarnings("deprecation")
1983    public void test_shutdownOutput() throws IOException {
1984        ServerSocket server = new ServerSocket(0);
1985        int port = server.getLocalPort();
1986        Socket client = new Socket(InetAddress.getLocalHost(), port);
1987
1988        Socket worker = server.accept();
1989        OutputStream theOutput = worker.getOutputStream();
1990
1991        // shutdown the output
1992        worker.shutdownOutput();
1993
1994        // send the regular data
1995        String sendString = new String("Test");
1996        try {
1997            theOutput.write(sendString.getBytes());
1998            theOutput.flush();
1999            fail("No exception when writing on socket with output shutdown");
2000        } catch (IOException e) {
2001            // Expected
2002        }
2003
2004        client.close();
2005        server.close();
2006
2007        // Regression test for HARMONY-2944
2008        // Port 0 is not allowed to be used in connect() on some platforms,
2009        // Since server has been closed here, so the port is free now
2010        Socket s = new Socket("0.0.0.0", port, false);
2011        s.shutdownOutput();
2012        try {
2013            s.shutdownOutput();
2014            fail("should throw SocketException");
2015        } catch (SocketException se) {
2016            // Expected
2017        }
2018        s.close();
2019    }
2020
2021    /**
2022     * @tests java.net.Socket#toString()
2023     */
2024    public void test_toString() throws IOException {
2025        ServerSocket server = new ServerSocket(0);
2026        Socket client = new Socket(InetAddress.getLocalHost(), server
2027                .getLocalPort());
2028
2029        String expected = "Socket[addr=" + InetAddress.getLocalHost()
2030                + ",port=" + client.getPort() + ",localport="
2031                + client.getLocalPort() + "]";
2032        assertEquals("Returned incorrect string", expected, client.toString());
2033        client.close();
2034        server.close();
2035    }
2036
2037    /**
2038     * @tests {@link java.net.Socket#setSocketImplFactory(SocketImplFactory)}
2039     */
2040    public void test_setSocketFactoryLjava_net_SocketImplFactory()
2041            throws IOException {
2042        SocketImplFactory factory = new MockSocketImplFactory();
2043        // Should not throw SocketException when set DatagramSocketImplFactory
2044        // for the first time.
2045        Socket.setSocketImplFactory(factory);
2046
2047        try {
2048            Socket.setSocketImplFactory(null);
2049            fail("Should throw SocketException");
2050        } catch (SocketException e) {
2051            // Expected
2052        }
2053
2054        try {
2055            Socket.setSocketImplFactory(factory);
2056            fail("Should throw SocketException");
2057        } catch (SocketException e) {
2058            // Expected
2059        }
2060    }
2061
2062    private class MockSocketImplFactory implements SocketImplFactory {
2063
2064        public SocketImpl createSocketImpl() {
2065            return new PlainSocketImpl();
2066        }
2067    }
2068}
2069