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