PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/luni/src/test/java/libcore/java/net/OldSocketTest.java

https://github.com/PAmoto/android_libcore
Java | 2623 lines | 2020 code | 325 blank | 278 comment | 81 complexity | 3db3c7a930b50371665dfa2c4b464775 MD5 | raw file
Possible License(s): JSON, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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. package libcore.java.net;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.net.ConnectException;
  22. import java.net.Inet4Address;
  23. import java.net.Inet6Address;
  24. import java.net.InetAddress;
  25. import java.net.InetSocketAddress;
  26. import java.net.Proxy;
  27. import java.net.ServerSocket;
  28. import java.net.Socket;
  29. import java.net.SocketAddress;
  30. import java.net.SocketException;
  31. import java.net.SocketImpl;
  32. import java.net.SocketTimeoutException;
  33. import java.net.UnknownHostException;
  34. import java.nio.channels.IllegalBlockingModeException;
  35. import java.nio.channels.SocketChannel;
  36. import java.security.Permission;
  37. import tests.support.Support_Configuration;
  38. import tests.support.Support_PortManager;
  39. public class OldSocketTest extends OldSocketTestCase {
  40. ServerSocket ss;
  41. Socket s;
  42. Thread t;
  43. SecurityManager sm = new SecurityManager() {
  44. public void checkPermission(Permission perm) {}
  45. public void checkConnect(String host, int port) {
  46. throw new SecurityException();
  47. }
  48. };
  49. public void test_Constructor() {
  50. // create the socket and then validate some basic state
  51. s = new Socket();
  52. assertFalse("new socket should not be connected", s.isConnected());
  53. assertFalse("new socket should not be bound", s.isBound());
  54. assertFalse("new socket should not be closed", s.isClosed());
  55. assertFalse("new socket should not be in InputShutdown", s
  56. .isInputShutdown());
  57. assertFalse("new socket should not be in OutputShutdown", s
  58. .isOutputShutdown());
  59. }
  60. public void test_ConstructorLjava_lang_StringI() throws IOException {
  61. // Test for method java.net.Socket(java.lang.String, int)
  62. int sport = startServer("Cons String,I");
  63. s = new Socket(InetAddress.getLocalHost().getHostName(), sport);
  64. assertTrue("Failed to create socket", s.getPort() == sport);
  65. //regression for HARMONY-946
  66. ServerSocket ss = null;
  67. Socket s = null;
  68. try {
  69. ss = new ServerSocket(0);
  70. s = new Socket("0.0.0.0", ss.getLocalPort());
  71. } finally {
  72. try {
  73. ss.close();
  74. } catch(Exception e) {
  75. //ignore
  76. }
  77. try {
  78. s.close();
  79. } catch(Exception e) {
  80. //ignore
  81. }
  82. }
  83. try {
  84. new Socket("unknown.host", 0);
  85. fail("UnknownHostException was not thrown.");
  86. } catch(UnknownHostException uhe) {
  87. //expected
  88. }
  89. Socket socket = null;
  90. try {
  91. socket = new Socket(InetAddress.getByName(null), sport);
  92. InetAddress address = socket.getLocalAddress();
  93. if (Boolean.getBoolean("java.net.preferIPv6Addresses")) {
  94. assertTrue(
  95. address.equals(InetAddress.getByName("::1")) ||
  96. address.equals(InetAddress.getByName("0:0:0:0:0:0:0:1")));
  97. } else {
  98. assertEquals(address, InetAddress.getByName("127.0.0.1"));
  99. }
  100. } finally {
  101. try {
  102. socket.close();
  103. } catch(Exception e) {}
  104. }
  105. }
  106. public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI()
  107. throws IOException {
  108. // Test for method java.net.Socket(java.lang.String, int,
  109. // java.net.InetAddress, int)
  110. int sport = startServer("Cons String,I,InetAddress,I");
  111. int portNumber = Support_PortManager.getNextPort();
  112. s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
  113. InetAddress.getLocalHost(), portNumber);
  114. assertTrue("Failed to create socket", s.getPort() == sport);
  115. if (("true".equals(System.getProperty("java.net.preferIPv6Addresses")))
  116. && !("true".equals(System
  117. .getProperty("java.net.preferIPv4Stack")))) {
  118. // ALTERNATE IPv6 TEST
  119. if ("true".equals(System.getProperty("run.ipv6tests"))) {
  120. System.out
  121. .println("Running testConstructorLjava_lang_StringILjava_net_InetAddressI(OldSocketTest) with IPv6GlobalAddressJcl4: "
  122. + Support_Configuration.IPv6GlobalAddressJcl4);
  123. int testPort = Support_PortManager.getNextPort();
  124. Socket s1 = null, s2 = null;
  125. try {
  126. s1 = new Socket(
  127. Support_Configuration.IPv6GlobalAddressJcl4, 80,
  128. InetAddress.getLocalHost(), testPort);
  129. } catch (IOException e) {
  130. // check here if InetAddress.getLocalHost() is returning the
  131. // loopback address.
  132. // if so that is likely the cause of the failure
  133. String warning = "";
  134. try {
  135. InetAddress returnedLocalHost = InetAddress
  136. .getLocalHost();
  137. // don't use isLoopbackAddress for some configurations
  138. // as they do not have it
  139. if (returnedLocalHost.isLoopbackAddress()) {
  140. warning = " - WARNING RETURNED LOCAL HOST IS THE LOOPBACK ADDRESS - MACHINE IS LIKELY NOT CONFIGURED CORRECTLY - THIS LIKELY CAUSED THE FAILURE";
  141. }
  142. } catch (Exception ex) {
  143. warning = " - WARNING COULD NOT GET LOCAL HOST - " + ex;
  144. }
  145. fail("Exception creating 1st socket" + warning + ": " + e);
  146. }
  147. boolean exception = false;
  148. try {
  149. s2 = new Socket(
  150. Support_Configuration.IPv6GlobalAddressJcl4, 80,
  151. InetAddress.getLocalHost(), testPort);
  152. } catch (IOException e) {
  153. exception = true;
  154. }
  155. try {
  156. s1.close();
  157. if (!exception)
  158. s2.close();
  159. } catch (IOException e) {
  160. }
  161. assertTrue("Was able to create two sockets on same port",
  162. exception);
  163. }
  164. } else {
  165. int testPort = Support_PortManager.getNextPort();
  166. Socket s1 = null, s2 = null;
  167. int serverPort = ss.getLocalPort();
  168. try {
  169. s1 = new Socket("127.0.0.1", serverPort, InetAddress
  170. .getLocalHost(), testPort);
  171. } catch (IOException e) {
  172. e.printStackTrace();
  173. // check here if InetAddress.getLocalHost() is returning the
  174. // loopback address.
  175. // if so that is likely the cause of the failure
  176. String warning = "";
  177. try {
  178. InetAddress returnedLocalHost = InetAddress.getLocalHost();
  179. // don't use isLoopbackAddress for some configurations as
  180. // they do not have it
  181. if (returnedLocalHost.isLoopbackAddress()) {
  182. warning = " - WARNING RETURNED LOCAL HOST IS THE LOOPBACK ADDRESS - MACHINE IS LIKELY NOT CONFIGURED CORRECTLY - THIS LIKELY CAUSED THE FAILURE";
  183. }
  184. } catch (Exception ex) {
  185. warning = " - WARNING COULD NOT GET LOCAL HOST - " + ex;
  186. }
  187. fail("Exception creating 1st socket" + warning + ": " + e);
  188. }
  189. boolean exception = false;
  190. try {
  191. s2 = new Socket("127.0.0.1", serverPort, InetAddress
  192. .getLocalHost(), testPort);
  193. } catch (IOException e) {
  194. exception = true;
  195. }
  196. try {
  197. s1.close();
  198. if (!exception)
  199. s2.close();
  200. } catch (IOException e) {
  201. }
  202. assertTrue("Was able to create two sockets on same port", exception);
  203. }
  204. }
  205. public void test_ConstructorLjava_lang_StringIZ() throws IOException {
  206. // Test for method java.net.Socket(java.lang.String, int, boolean)
  207. int sport = startServer("Cons String,I,Z");
  208. s = new Socket(InetAddress.getLocalHost().getHostName(), sport, true);
  209. assertTrue("Failed to create socket", s.getPort() == sport);
  210. s = new Socket(InetAddress.getLocalHost().getHostName(), sport, false);
  211. }
  212. public void test_ConstructorLjava_net_InetAddressI() throws IOException {
  213. // Test for method java.net.Socket(java.net.InetAddress, int)
  214. int sport = startServer("Cons InetAddress,I");
  215. s = new Socket(InetAddress.getLocalHost(), sport);
  216. assertTrue("Failed to create socket", s.getPort() == sport);
  217. }
  218. public void test_ConstructorLjava_net_InetAddressILjava_net_InetAddressI()
  219. throws IOException {
  220. // Test for method java.net.Socket(java.net.InetAddress, int,
  221. // java.net.InetAddress, int)
  222. int sport = startServer("Cons InetAddress,I,InetAddress,I");
  223. int portNumber = Support_PortManager.getNextPort();
  224. s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
  225. InetAddress.getLocalHost(), portNumber);
  226. assertTrue("Failed to create socket", s.getLocalPort() == portNumber);
  227. }
  228. public void test_ConstructorLjava_net_InetAddressIZ() throws IOException {
  229. // Test for method java.net.Socket(java.net.InetAddress, int, boolean)
  230. int sport = startServer("Cons InetAddress,I,Z");
  231. s = new Socket(InetAddress.getLocalHost(), sport, true);
  232. assertTrue("Failed to create socket", s.getPort() == sport);
  233. s = new Socket(InetAddress.getLocalHost(), sport, false);
  234. }
  235. public void test_close() throws IOException {
  236. // Test for method void java.net.Socket.close()
  237. int sport = startServer("SServer close");
  238. int portNumber = Support_PortManager.getNextPort();
  239. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  240. try {
  241. s.setSoLinger(false, 100);
  242. } catch (IOException e) {
  243. handleException(e, SO_LINGER);
  244. }
  245. s.close();
  246. try {
  247. s.getOutputStream();
  248. fail("IOException was not thrown.");
  249. } catch (java.io.IOException e) {
  250. //expected
  251. }
  252. }
  253. public void test_getInetAddress() throws IOException {
  254. // Test for method java.net.InetAddress java.net.Socket.getInetAddress()
  255. int sport = startServer("SServer getInetAddress");
  256. int portNumber = Support_PortManager.getNextPort();
  257. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  258. assertTrue("Returned incorrect InetAddress", s.getInetAddress().equals(
  259. InetAddress.getLocalHost()));
  260. }
  261. public void test_getInputStream() throws IOException {
  262. // Simple fetch test
  263. ServerSocket server = new ServerSocket(0);
  264. Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
  265. InputStream is = client.getInputStream();
  266. assertNotNull("Failed to get stream", is);
  267. is.close();
  268. client.close();
  269. server.close();
  270. }
  271. public void test_getKeepAlive() {
  272. try {
  273. int sport = startServer("SServer getKeepAlive");
  274. int portNumber = Support_PortManager.getNextPort();
  275. Socket theSocket = new Socket(InetAddress.getLocalHost(), sport,
  276. null, portNumber);
  277. theSocket.setKeepAlive(true);
  278. assertTrue("getKeepAlive false when it should be true", theSocket
  279. .getKeepAlive());
  280. theSocket.setKeepAlive(false);
  281. assertFalse("getKeepAlive true when it should be False", theSocket
  282. .getKeepAlive());
  283. theSocket.close();
  284. try {
  285. theSocket.setKeepAlive(false);
  286. fail("IOException was not thrown after calling setKeepAlive " +
  287. "method.");
  288. } catch(IOException ioe) {
  289. //expected
  290. }
  291. try {
  292. theSocket.getKeepAlive();
  293. fail("IOException was not thrown after calling getKeepAlive +" +
  294. "method.");
  295. } catch(IOException ioe) {
  296. //expected
  297. }
  298. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
  299. } catch (Exception e) {
  300. handleException(e, SO_KEEPALIVE);
  301. }
  302. }
  303. public void test_getLocalAddress() throws IOException {
  304. // Test for method java.net.InetAddress
  305. // java.net.Socket.getLocalAddress()
  306. int sport = startServer("SServer getLocAddress");
  307. int portNumber = Support_PortManager.getNextPort();
  308. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  309. assertEquals("Returned incorrect InetAddress",
  310. InetAddress.getLocalHost(), s.getLocalAddress());
  311. // now validate that behaviour when the any address is returned
  312. String preferIPv4StackValue = System
  313. .getProperty("java.net.preferIPv4Stack");
  314. String preferIPv6AddressesValue = System
  315. .getProperty("java.net.preferIPv6Addresses");
  316. s = new Socket();
  317. s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
  318. if (((preferIPv4StackValue == null) || preferIPv4StackValue
  319. .equalsIgnoreCase("false"))
  320. && (preferIPv6AddressesValue != null)
  321. && (preferIPv6AddressesValue.equals("true"))) {
  322. assertTrue(
  323. "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=false "
  324. + s.getLocalSocketAddress(),
  325. s.getLocalAddress() instanceof Inet6Address);
  326. } else {
  327. assertTrue(
  328. "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=true "
  329. + s.getLocalSocketAddress(),
  330. s.getLocalAddress() instanceof Inet4Address);
  331. }
  332. s.close();
  333. }
  334. public void test_getLocalPort() throws IOException {
  335. // Test for method int java.net.Socket.getLocalPort()
  336. int sport = startServer("SServer getLocalPort");
  337. int portNumber = Support_PortManager.getNextPort();
  338. s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
  339. InetAddress.getLocalHost(), portNumber);
  340. assertTrue("Returned incorrect port", s.getLocalPort() == portNumber);
  341. }
  342. @SuppressWarnings("deprecation")
  343. public void test_getOutputStream() throws IOException {
  344. // Test for method java.io.OutputStream
  345. // java.net.Socket.getOutputStream()
  346. int sport = startServer("SServer getOutputStream");
  347. int portNumber = Support_PortManager.getNextPort();
  348. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  349. java.io.OutputStream os = s.getOutputStream();
  350. assertNotNull("Failed to get stream", os);
  351. os.write(1);
  352. s.close();
  353. // Regression test for harmony-2934
  354. s = new Socket("127.0.0.1", Support_PortManager.getNextPort(),
  355. false);
  356. OutputStream o = s.getOutputStream();
  357. o.write(1);
  358. try {
  359. Thread.sleep(1000);
  360. } catch (InterruptedException e) {
  361. }
  362. o.close();
  363. s.close();
  364. // Regression test for harmony-2942
  365. s = new Socket("0.0.0.0", Support_PortManager.getNextPort(),
  366. false);
  367. o = s.getOutputStream();
  368. o.write(1);
  369. try {
  370. Thread.sleep(1000);
  371. } catch (InterruptedException e) {
  372. }
  373. o.close();
  374. s.close();
  375. }
  376. public void test_getPort() throws IOException {
  377. // Test for method int java.net.Socket.getPort()
  378. int sport = startServer("SServer getPort");
  379. int portNumber = Support_PortManager.getNextPort();
  380. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  381. assertTrue("Returned incorrect port" + s.getPort(),
  382. s.getPort() == sport);
  383. }
  384. public void test_getSoLinger() {
  385. // Test for method int java.net.Socket.getSoLinger()
  386. int sport = startServer("SServer getSoLinger");
  387. try {
  388. int portNumber = Support_PortManager.getNextPort();
  389. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  390. s.setSoLinger(true, 200);
  391. assertEquals("Returned incorrect linger", 200, s.getSoLinger());
  392. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
  393. s.setSoLinger(false, 0);
  394. } catch (Exception e) {
  395. handleException(e, SO_LINGER);
  396. }
  397. try {
  398. int portNumber = Support_PortManager.getNextPort();
  399. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  400. s.close();
  401. try {
  402. s.getSoLinger();
  403. fail("SocketException was not thrown.");
  404. } catch(SocketException ioe) {
  405. //expected
  406. }
  407. } catch(Exception e) {
  408. fail("Unexpected exception was thrown: " + e.toString());
  409. }
  410. }
  411. public void test_getReceiveBufferSize() {
  412. try {
  413. int sport = startServer("SServer getReceiveBufferSize");
  414. int portNumber = Support_PortManager.getNextPort();
  415. s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
  416. null, portNumber);
  417. s.setReceiveBufferSize(130);
  418. assertTrue("Incorrect buffer size", s.getReceiveBufferSize() >= 130);
  419. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
  420. } catch (Exception e) {
  421. handleException(e, SO_RCVBUF);
  422. }
  423. try {
  424. Socket newSocket = new Socket();
  425. newSocket.close();
  426. try {
  427. newSocket.getReceiveBufferSize();
  428. fail("SocketException was not thrown.");
  429. } catch(SocketException e) {
  430. //expected
  431. }
  432. } catch(Exception e) {
  433. fail("Unexpected exception.");
  434. }
  435. }
  436. public void test_getSendBufferSize() {
  437. int sport = startServer("SServer setSendBufferSize");
  438. try {
  439. int portNumber = Support_PortManager.getNextPort();
  440. s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
  441. null, portNumber);
  442. s.setSendBufferSize(134);
  443. assertTrue("Incorrect buffer size", s.getSendBufferSize() >= 134);
  444. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
  445. } catch (Exception e) {
  446. handleException(e, SO_SNDBUF);
  447. }
  448. try {
  449. int portNumber = Support_PortManager.getNextPort();
  450. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  451. s.close();
  452. try {
  453. s.getSendBufferSize();
  454. fail("IOException was not thrown.");
  455. } catch(IOException ioe) {
  456. //expected
  457. }
  458. } catch(Exception e) {
  459. fail("Unexpected exception was thrown: " + e.toString());
  460. }
  461. }
  462. public void test_getSoTimeout() {
  463. // Test for method int java.net.Socket.getSoTimeout()
  464. int sport = startServer("SServer getSoTimeout");
  465. try {
  466. s = new Socket(InetAddress.getLocalHost(), sport);
  467. s.setSoTimeout(100);
  468. assertEquals("Returned incorrect sotimeout", 100, s.getSoTimeout());
  469. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
  470. } catch (Exception e) {
  471. handleException(e, SO_TIMEOUT);
  472. }
  473. try {
  474. int portNumber = Support_PortManager.getNextPort();
  475. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  476. s.close();
  477. try {
  478. s.getSoTimeout();
  479. fail("SocketException was not thrown.");
  480. } catch(SocketException ioe) {
  481. //expected
  482. }
  483. } catch(Exception e) {
  484. fail("Unexpected exception was thrown: " + e.toString());
  485. }
  486. }
  487. public void test_getTcpNoDelay() {
  488. // Test for method boolean java.net.Socket.getTcpNoDelay()
  489. int sport = startServer("SServer getTcpNoDelay");
  490. try {
  491. int portNumber = Support_PortManager.getNextPort();
  492. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  493. boolean bool = !s.getTcpNoDelay();
  494. s.setTcpNoDelay(bool);
  495. assertTrue("Failed to get no delay setting: " + s.getTcpNoDelay(),
  496. s.getTcpNoDelay() == bool);
  497. ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
  498. } catch (Exception e) {
  499. handleException(e, TCP_NODELAY);
  500. }
  501. try {
  502. int portNumber = Support_PortManager.getNextPort();
  503. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  504. s.close();
  505. try {
  506. s.getTcpNoDelay();
  507. fail("SocketException was not thrown.");
  508. } catch(SocketException ioe) {
  509. //expected
  510. }
  511. } catch(Exception e) {
  512. fail("Unexpected exception was thrown: " + e.toString());
  513. }
  514. }
  515. public void test_setKeepAliveZ() throws Exception {
  516. // There is not really a good test for this as it is there to detect
  517. // crashed machines. Just make sure we can set it
  518. try {
  519. int sport = startServer("SServer setKeepAlive");
  520. int portNumber = Support_PortManager.getNextPort();
  521. Socket theSocket = new Socket(InetAddress.getLocalHost(), sport,
  522. null, portNumber);
  523. theSocket.setKeepAlive(true);
  524. theSocket.setKeepAlive(false);
  525. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
  526. } catch (Exception e) {
  527. handleException(e, SO_KEEPALIVE);
  528. }
  529. // regression test for HARMONY-1136
  530. new TestSocket((SocketImpl) null).setKeepAlive(true);
  531. try {
  532. Socket theSocket = new Socket();
  533. theSocket.close();
  534. theSocket.setKeepAlive(true);
  535. fail("SocketException was not thrown.");
  536. } catch(SocketException ioe) {
  537. //expected
  538. }
  539. }
  540. class TestSocket extends Socket {
  541. public TestSocket(SocketImpl impl) throws SocketException {
  542. super(impl);
  543. }
  544. }
  545. public void test_setSocketImplFactoryLjava_net_SocketImplFactory() {
  546. // Test for method void
  547. // java.net.Socket.setSocketImplFactory(java.net.SocketImplFactory)
  548. // Cannot test as setting will cause the factory to be changed for
  549. // all subsequent sockets
  550. SecurityManager sm = new SecurityManager() {
  551. public void checkPermission(Permission perm) {
  552. }
  553. public void checkSetFactory() {
  554. throw new SecurityException();
  555. }
  556. };
  557. }
  558. public void test_setSendBufferSizeI() {
  559. try {
  560. int sport = startServer("SServer setSendBufferSizeI");
  561. int portNumber = Support_PortManager.getNextPort();
  562. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  563. s.setSendBufferSize(134);
  564. assertTrue("Incorrect buffer size", s.getSendBufferSize() >= 134);
  565. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
  566. } catch (Exception e) {
  567. handleException(e, SO_SNDBUF);
  568. }
  569. try {
  570. Socket theSocket = new Socket();
  571. theSocket.close();
  572. theSocket.setSendBufferSize(1);
  573. fail("SocketException was not thrown.");
  574. } catch(SocketException ioe) {
  575. //expected
  576. } catch(IOException ioe) {
  577. fail("IOException was thrown.");
  578. }
  579. }
  580. public void test_setReceiveBufferSizeI() {
  581. try {
  582. int sport = startServer("SServer setReceiveBufferSizeI");
  583. int portNumber = Support_PortManager.getNextPort();
  584. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  585. s.setReceiveBufferSize(130);
  586. assertTrue("Incorrect buffer size", s.getReceiveBufferSize() >= 130);
  587. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
  588. } catch (Exception e) {
  589. handleException(e, SO_RCVBUF);
  590. }
  591. try {
  592. Socket theSocket = new Socket();
  593. theSocket.close();
  594. theSocket.setReceiveBufferSize(1);
  595. fail("SocketException was not thrown.");
  596. } catch(SocketException ioe) {
  597. //expected
  598. } catch(IOException ioe) {
  599. fail("IOException was thrown.");
  600. }
  601. }
  602. public void test_setSoLingerZI() {
  603. // Test for method void java.net.Socket.setSoLinger(boolean, int)
  604. try {
  605. int sport = startServer("SServer setSoLingerZI");
  606. int portNumber = Support_PortManager.getNextPort();
  607. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  608. s.setSoLinger(true, 500);
  609. assertEquals("Set incorrect linger", 500, s.getSoLinger());
  610. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
  611. s.setSoLinger(false, 0);
  612. } catch (Exception e) {
  613. handleException(e, SO_LINGER);
  614. }
  615. try {
  616. Socket theSocket = new Socket();
  617. theSocket.close();
  618. theSocket.setSoLinger(true, 1);
  619. fail("SocketException was not thrown.");
  620. } catch(SocketException ioe) {
  621. //expected
  622. } catch(IOException ioe) {
  623. fail("IOException was thrown.");
  624. }
  625. }
  626. public void test_setSoTimeoutI() {
  627. // Test for method void java.net.Socket.setSoTimeout(int)
  628. try {
  629. int sport = startServer("SServer seSoTimeoutI");
  630. int portNumber = Support_PortManager.getNextPort();
  631. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  632. s.setSoTimeout(100);
  633. assertEquals("Set incorrect sotimeout", 100, s.getSoTimeout());
  634. ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
  635. } catch (Exception e) {
  636. handleException(e, SO_TIMEOUT);
  637. }
  638. try {
  639. Socket theSocket = new Socket();
  640. theSocket.close();
  641. theSocket.setSoTimeout(1);
  642. fail("SocketException was not thrown.");
  643. } catch(SocketException ioe) {
  644. //expected
  645. } catch(IOException ioe) {
  646. fail("IOException was thrown.");
  647. }
  648. }
  649. public void test_setTcpNoDelayZ() {
  650. // Test for method void java.net.Socket.setTcpNoDelay(boolean)
  651. try {
  652. int sport = startServer("SServer setTcpNoDelayZ");
  653. int portNumber = Support_PortManager.getNextPort();
  654. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  655. boolean bool;
  656. s.setTcpNoDelay(bool = !s.getTcpNoDelay());
  657. assertTrue("Failed to set no delay setting: " + s.getTcpNoDelay(),
  658. s.getTcpNoDelay() == bool);
  659. ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
  660. } catch (Exception e) {
  661. handleException(e, TCP_NODELAY);
  662. }
  663. try {
  664. Socket theSocket = new Socket();
  665. theSocket.close();
  666. theSocket.setTcpNoDelay(true);
  667. fail("SocketException was not thrown.");
  668. } catch(SocketException ioe) {
  669. //expected
  670. } catch(IOException ioe) {
  671. fail("IOException was thrown.");
  672. }
  673. }
  674. public void test_toString() throws IOException {
  675. // Test for method java.lang.String java.net.Socket.toString()
  676. int sport = startServer("SServer toString");
  677. int portNumber = Support_PortManager.getNextPort();
  678. s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
  679. InetAddress.getLocalHost(), portNumber);
  680. assertTrue("Returned incorrect string: " + s.toString()
  681. + " localHost: " + InetAddress.getLocalHost(), s.toString()
  682. .equals(
  683. "Socket[addr=" + InetAddress.getLocalHost() + ",port="
  684. + s.getPort() + ",localport="
  685. + s.getLocalPort() + "]"));
  686. }
  687. // AndroidOnly: RI returns wrong value for EOF
  688. public void test_shutdownInput() throws Exception {
  689. InetAddress addr = InetAddress.getLocalHost();
  690. int port = Support_PortManager.getNextPort();
  691. ServerSocket serverSocket = new ServerSocket(port, 5, addr);
  692. Socket theSocket = new Socket(addr, port);
  693. Socket servSock = serverSocket.accept();
  694. InputStream theInput = theSocket.getInputStream();
  695. OutputStream theOutput = servSock.getOutputStream();
  696. // shutdown the input
  697. theSocket.shutdownInput();
  698. // send the regular data
  699. String sendString = new String("Test");
  700. theOutput.write(sendString.getBytes());
  701. theOutput.flush();
  702. // give things some time to settle
  703. Thread.sleep(1000);
  704. // RI fails here. It is a RI bug not to return 0 to indicate EOF
  705. assertEquals(0, theInput.available());
  706. theSocket.close();
  707. serverSocket.close();
  708. Socket socket = new Socket();
  709. socket.close();
  710. try {
  711. socket.shutdownInput();
  712. fail("IOException was not thrown.");
  713. } catch(IOException ioe) {
  714. //expected
  715. }
  716. }
  717. public void test_shutdownOutput() throws IOException {
  718. InetAddress addr = InetAddress.getLocalHost();
  719. int port = Support_PortManager.getNextPort();
  720. ServerSocket serverSocket = new ServerSocket(port, 5, addr);
  721. Socket theSocket = new Socket(addr, port);
  722. Socket servSock = serverSocket.accept();
  723. InputStream theInput = theSocket.getInputStream();
  724. OutputStream theOutput = servSock.getOutputStream();
  725. // shutdown the output
  726. servSock.shutdownOutput();
  727. // send the regular data
  728. String sendString = new String("Test");
  729. try {
  730. theOutput.write(sendString.getBytes());
  731. theOutput.flush();
  732. fail("No exception when writing on socket with output shutdown");
  733. } catch (Exception e) {
  734. }
  735. theSocket.close();
  736. serverSocket.close();
  737. try {
  738. theSocket.shutdownInput();
  739. fail("IOException was not thrown.");
  740. } catch(IOException ioe) {
  741. //expected
  742. }
  743. }
  744. public void test_getLocalSocketAddress() throws IOException {
  745. // set up server connect and then validate that we get the right
  746. // response for the local address
  747. int sport = startServer("SServer getLocSocketAddress");
  748. int portNumber = Support_PortManager.getNextPort();
  749. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  750. assertTrue(
  751. "Returned incorrect InetSocketAddress(1):"
  752. + s.getLocalSocketAddress().toString()
  753. + "Expected: "
  754. + (new InetSocketAddress(InetAddress.getLocalHost(),
  755. portNumber)).toString(), s
  756. .getLocalSocketAddress().equals(
  757. new InetSocketAddress(InetAddress
  758. .getLocalHost(), portNumber)));
  759. s.close();
  760. // now create a socket that is not bound and validate we get the
  761. // right answer
  762. Socket theSocket = new Socket();
  763. assertNull(
  764. "Returned incorrect InetSocketAddress -unbound socket- Expected null",
  765. theSocket.getLocalSocketAddress());
  766. // now bind the socket and make sure we get the right answer
  767. portNumber = Support_PortManager.getNextPort();
  768. theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
  769. portNumber));
  770. assertTrue(
  771. "Returned incorrect InetSocketAddress(2):"
  772. + theSocket.getLocalSocketAddress().toString()
  773. + "Expected: "
  774. + (new InetSocketAddress(InetAddress.getLocalHost(),
  775. portNumber)).toString(), theSocket
  776. .getLocalSocketAddress().equals(
  777. new InetSocketAddress(InetAddress
  778. .getLocalHost(), portNumber)));
  779. theSocket.close();
  780. // now validate that behaviour when the any address is returned
  781. s = new Socket();
  782. s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
  783. String preferIPv4StackValue = System
  784. .getProperty("java.net.preferIPv4Stack");
  785. String preferIPv6AddressesValue = System
  786. .getProperty("java.net.preferIPv6Addresses");
  787. if (((preferIPv4StackValue == null) || preferIPv4StackValue
  788. .equalsIgnoreCase("false"))
  789. && (preferIPv6AddressesValue != null)
  790. && (preferIPv6AddressesValue.equals("true"))) {
  791. assertTrue(
  792. "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=false "
  793. + s.getLocalSocketAddress(),
  794. ((InetSocketAddress) s.getLocalSocketAddress())
  795. .getAddress() instanceof Inet6Address);
  796. } else {
  797. assertTrue(
  798. "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=true "
  799. + s.getLocalSocketAddress(),
  800. ((InetSocketAddress) s.getLocalSocketAddress())
  801. .getAddress() instanceof Inet4Address);
  802. }
  803. s.close();
  804. // now validate the same for getLocalAddress
  805. s = new Socket();
  806. s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
  807. if (((preferIPv4StackValue == null) || preferIPv4StackValue
  808. .equalsIgnoreCase("false"))
  809. && (preferIPv6AddressesValue != null)
  810. && (preferIPv6AddressesValue.equals("true"))) {
  811. assertTrue(
  812. "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=false "
  813. + s.getLocalSocketAddress(),
  814. ((InetSocketAddress) s.getLocalSocketAddress())
  815. .getAddress() instanceof Inet6Address);
  816. } else {
  817. assertTrue(
  818. "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=true "
  819. + s.getLocalSocketAddress(),
  820. ((InetSocketAddress) s.getLocalSocketAddress())
  821. .getAddress() instanceof Inet4Address);
  822. }
  823. s.close();
  824. }
  825. public void test_getRemoteSocketAddress() throws IOException {
  826. // set up server connect and then validate that we get the right
  827. // response for the remote address
  828. int sport = startServer("SServer getLocRemoteAddress");
  829. int portNumber = Support_PortManager.getNextPort();
  830. s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
  831. assertTrue("Returned incorrect InetSocketAddress(1):"
  832. + s.getLocalSocketAddress().toString(),
  833. s.getRemoteSocketAddress()
  834. .equals(
  835. new InetSocketAddress(InetAddress
  836. .getLocalHost(), sport)));
  837. s.close();
  838. // now create one that is not connect and validate that we get the
  839. // right answer
  840. Socket theSocket = new Socket();
  841. portNumber = Support_PortManager.getNextPort();
  842. theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
  843. portNumber));
  844. assertNull("Returned incorrect InetSocketAddress -unconnected socket:"
  845. + "Expected: NULL", theSocket.getRemoteSocketAddress());
  846. // now connect and validate we get the right answer
  847. theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
  848. sport));
  849. assertTrue("Returned incorrect InetSocketAddress(2):"
  850. + theSocket.getRemoteSocketAddress().toString(),
  851. theSocket.getRemoteSocketAddress()
  852. .equals(
  853. new InetSocketAddress(InetAddress
  854. .getLocalHost(), sport)));
  855. theSocket.close();
  856. }
  857. public void test_isBound() throws IOException {
  858. InetAddress addr = InetAddress.getLocalHost();
  859. int port = Support_PortManager.getNextPort();
  860. ServerSocket serverSocket = new ServerSocket(port, 5, addr);
  861. Socket theSocket = new Socket(addr, port);
  862. Socket servSock = serverSocket.accept();
  863. assertTrue("Socket indicated not bound when it should be (1)",
  864. theSocket.isBound());
  865. theSocket.close();
  866. serverSocket.close();
  867. // now do it with the new constructors and revalidate. Connect causes
  868. // the socket to be bound
  869. InetSocketAddress theAddress = new InetSocketAddress(InetAddress
  870. .getLocalHost(), Support_PortManager.getNextPort());
  871. theSocket = new Socket();
  872. assertFalse("Socket indicated bound when it was not (2)", theSocket
  873. .isBound());
  874. serverSocket = new ServerSocket();
  875. serverSocket.bind(theAddress);
  876. theSocket.connect(theAddress);
  877. servSock = serverSocket.accept();
  878. assertTrue("Socket indicated not bound when it should be (2)",
  879. theSocket.isBound());
  880. theSocket.close();
  881. serverSocket.close();
  882. // now test when we bind explicitly
  883. InetSocketAddress theLocalAddress = new InetSocketAddress(InetAddress
  884. .getLocalHost(), Support_PortManager.getNextPort());
  885. theSocket = new Socket();
  886. assertFalse("Socket indicated bound when it was not (3)", theSocket
  887. .isBound());
  888. theSocket.bind(theLocalAddress);
  889. assertTrue("Socket indicated not bound when it should be (3a)",
  890. theSocket.isBound());
  891. theSocket.close();
  892. assertTrue("Socket indicated not bound when it should be (3b)",
  893. theSocket.isBound());
  894. }
  895. public void test_isConnected() throws IOException {
  896. InetAddress addr = InetAddress.getLocalHost();
  897. int port = Support_PortManager.getNextPort();
  898. ServerSocket serverSocket = new ServerSocket(port, 5, addr);
  899. Socket theSocket = new Socket(addr, port);
  900. Socket servSock = serverSocket.accept();
  901. assertTrue("Socket indicated not connected when it should be",
  902. theSocket.isConnected());
  903. theSocket.close();
  904. serverSocket.close();
  905. // now do it with the new constructors and revalidate
  906. InetSocketAddress theAddress = new InetSocketAddress(InetAddress
  907. .getLocalHost(), Support_PortManager.getNextPort());
  908. theSocket = new Socket();
  909. assertFalse("Socket indicated connected when it was not", theSocket
  910. .isConnected());
  911. serverSocket = new ServerSocket();
  912. serverSocket.bind(theAddress);
  913. theSocket.connect(theAddress);
  914. servSock = serverSocket.accept();
  915. assertTrue("Socket indicated not connected when it should be",
  916. theSocket.isConnected());
  917. theSocket.close();
  918. serverSocket.close();
  919. }
  920. public void test_isClosed() throws IOException {
  921. InetAddress addr = InetAddress.getLocalHost();
  922. int port = Support_PortManager.getNextPort();
  923. ServerSocket serverSocket = new ServerSocket(port, 5, addr);
  924. Socket theSocket = new Socket(addr, port);
  925. Socket servSock = serverSocket.accept();
  926. // validate isClosed returns expected values
  927. assertFalse("Socket should indicate it is not closed(1):", theSocket
  928. .isClosed());
  929. theSocket.close();
  930. assertTrue("Socket should indicate it is closed(1):", theSocket
  931. .isClosed());
  932. theSocket = new Socket(addr, port);
  933. assertFalse("Socket should indicate it is not closed(2):", theSocket
  934. .isClosed());
  935. theSocket.close();
  936. assertTrue("Socket should indicate it is closed(2):", theSocket
  937. .isClosed());
  938. // validate that isClosed works ok for sockets returned from
  939. // ServerSocket.accept()
  940. assertFalse("Server Socket should indicate it is not closed:", servSock
  941. .isClosed());
  942. servSock.close();
  943. assertTrue("Server Socket should indicate it is closed:", servSock
  944. .isClosed());
  945. }
  946. public void test_bindLjava_net_SocketAddress() throws IOException {
  947. class mySocketAddress extends SocketAddress {
  948. public mySocketAddress() {
  949. }
  950. }
  951. // Address we cannot bind to
  952. Socket theSocket = new Socket();
  953. try {
  954. theSocket.bind(new InetSocketAddress(InetAddress
  955. .getByAddress(Support_Configuration.nonLocalAddressBytes),
  956. Support_PortManager.getNextPort()));
  957. fail("No exception when binding to bad address:"
  958. + theSocket.getLocalSocketAddress().toString());
  959. } catch (IOException ex) {
  960. }
  961. theSocket.close();
  962. // now create a socket that is not bound and then bind it
  963. theSocket = new Socket();
  964. int portNumber = Support_PortManager.getNextPort();
  965. theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
  966. portNumber));
  967. // validate that the localSocketAddress reflects the address we
  968. // bound to
  969. assertTrue(
  970. "Local address not correct after bind:"
  971. + theSocket.getLocalSocketAddress().toString()
  972. + " Expected: "
  973. + (new InetSocketAddress(InetAddress.getLocalHost(),
  974. portNumber)).toString(), theSocket
  975. .getLocalSocketAddress().equals(
  976. new InetSocketAddress(InetAddress
  977. .getLocalHost(), portNumber)));
  978. // make sure we can now connect and that connections appear to come
  979. // from the address we bound to.
  980. InetSocketAddress theAddress = new InetSocketAddress(InetAddress
  981. .getLocalHost(), Support_PortManager.getNextPort());
  982. ServerSocket serverSocket = new ServerSocket();
  983. serverSocket.bind(theAddress);
  984. theSocket.connect(theAddress);
  985. Socket servSock = serverSocket.accept();
  986. assertTrue(
  987. "Returned Remote address from server connected to does not match expected local address:"
  988. + servSock.getRemoteSocketAddress().toString()
  989. + " Expected: "
  990. + (new InetSocketAddress(InetAddress.getLocalHost(),
  991. portNumber)).toString(), servSock
  992. .getRemoteSocketAddress().equals(
  993. new InetSocketAddress(InetAddress
  994. .getLocalHost(), portNumber)));
  995. theSocket.close();
  996. servSock.close();
  997. serverSocket.close();
  998. // validate if we pass in null that it picks an address for us and
  999. // all is ok
  1000. theSocket = new Socket();
  1001. theSocket.bind(null);
  1002. assertNotNull("Bind with null did not work", theSocket
  1003. .getLocalSocketAddress());
  1004. theSocket.close();
  1005. // now check the error conditions
  1006. // Address that we have already bound to
  1007. theSocket = new Socket();
  1008. Socket theSocket2 = new Socket();
  1009. try {
  1010. theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
  1011. Support_PortManager.getNextPort());
  1012. theSocket.bind(theAddress);
  1013. theSocket2.bind(theAddress);
  1014. fail("No exception binding to address that is not available");
  1015. } catch (IOException ex) {
  1016. }
  1017. theSocket.close();
  1018. theSocket2.close();
  1019. // unsupported SocketAddress subclass
  1020. theSocket = new Socket();
  1021. try {
  1022. theSocket.bind(new mySocketAddress());
  1023. fail("No exception when binding using unsupported SocketAddress subclass");
  1024. } catch (IllegalArgumentException ex) {
  1025. }
  1026. theSocket.close();
  1027. }
  1028. public void test_bindLjava_net_SocketAddress_Proxy() throws IOException {
  1029. //The Proxy will not impact on the bind operation.It can be assigned with any address.
  1030. Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 0));
  1031. Socket socket = new Socket(proxy);
  1032. try {
  1033. InetAddress address = InetAddress.getByName("localhost");
  1034. int port = 0;
  1035. socket.bind(new InetSocketAddress(address, port));
  1036. assertEquals(address, socket.getLocalAddress());
  1037. assertTrue(port!=socket.getLocalPort());
  1038. } finally {
  1039. socket.close();
  1040. }
  1041. }
  1042. public void test_connectLjava_net_SocketAddress() throws Exception {
  1043. // needed for some tests
  1044. class mySocketAddress extends SocketAddress {
  1045. public mySocketAddress() {
  1046. }
  1047. }
  1048. class SocketCloser extends Thread {
  1049. int timeout = 0;
  1050. Socket theSocket = null;
  1051. public void run() {
  1052. try {
  1053. Thread.sleep(timeout);
  1054. theSocket.close();
  1055. } catch (Exception e) {
  1056. }
  1057. ;
  1058. return;
  1059. }
  1060. public SocketCloser(int timeout, Socket theSocket) {
  1061. this.timeout = timeout;
  1062. this.theSocket = theSocket;
  1063. }
  1064. }
  1065. // start by validating the error checks
  1066. int portNumber = Support_PortManager.getNextPort();
  1067. Socket theSocket = null;
  1068. ServerSocket serverSocket = null;
  1069. SocketAddress theAddress = null;
  1070. SocketAddress nonConnectableAddress = null;
  1071. SocketAddress nonReachableAddress = null;
  1072. SocketAddress invalidType = null;
  1073. // byte[] theBytes = {-1,-1,-1,-1};
  1074. byte[] theBytes = { 0, 0, 0, 0 };
  1075. theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
  1076. portNumber);
  1077. nonConnectableAddress = new InetSocketAddress(InetAddress
  1078. .getByAddress(theBytes), portNumber);
  1079. nonReachableAddress = new InetSocketAddress(InetAddress
  1080. .getByName(Support_Configuration.ResolvedNotExistingHost),
  1081. portNumber);
  1082. invalidType = new mySocketAddress();
  1083. try {
  1084. theSocket = new Socket();
  1085. theSocket.connect(null);
  1086. fail("No exception after null address passed in");
  1087. } catch (Exception e) {
  1088. assertTrue("Wrong exception null address passed in: "
  1089. + e.toString(), (e instanceof IllegalArgumentException));
  1090. }
  1091. try {
  1092. theSocket = new Socket();
  1093. theSocket.connect(invalidType);
  1094. fail("No exception when invalid socket address type passed in: ");
  1095. } catch (Exception e) {
  1096. assertTrue(
  1097. "Wrong exception when when invalid socket address type passed in: "
  1098. + e.toString(),
  1099. (e instanceof IllegalArgumentException));
  1100. }
  1101. try {
  1102. theSocket = new Socket();
  1103. theSocket.connect(nonConnectableAddress);
  1104. fail("No exception when non Connectable Address passed in: ");
  1105. } catch (Exception e) {
  1106. assertTrue(
  1107. "Wrong exception when non Connectable Address passed in: "
  1108. + e.toString(), (e instan

Large files files are truncated, but you can click here to view the full file