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