PageRenderTime 72ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/jdk/src/share/classes/java/net/Socket.java

https://bitbucket.org/nkabir/jdk-6
Java | 1594 lines | 551 code | 81 blank | 962 comment | 134 complexity | b9f54c64fdb892bca55b83d7bfdde8fc MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, BSD-3-Clause
  1. /*
  2. * Copyright (c) 1995, 2007, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Oracle designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Oracle in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22. * or visit www.oracle.com if you need additional information or have any
  23. * questions.
  24. */
  25. package java.net;
  26. import java.io.InputStream;
  27. import java.io.OutputStream;
  28. import java.io.IOException;
  29. import java.io.InterruptedIOException;
  30. import java.nio.channels.SocketChannel;
  31. import java.security.AccessController;
  32. import java.security.PrivilegedExceptionAction;
  33. import java.security.PrivilegedAction;
  34. /**
  35. * This class implements client sockets (also called just
  36. * "sockets"). A socket is an endpoint for communication
  37. * between two machines.
  38. * <p>
  39. * The actual work of the socket is performed by an instance of the
  40. * <code>SocketImpl</code> class. An application, by changing
  41. * the socket factory that creates the socket implementation,
  42. * can configure itself to create sockets appropriate to the local
  43. * firewall.
  44. *
  45. * @author unascribed
  46. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  47. * @see java.net.SocketImpl
  48. * @see java.nio.channels.SocketChannel
  49. * @since JDK1.0
  50. */
  51. public
  52. class Socket {
  53. /**
  54. * Various states of this socket.
  55. */
  56. private boolean created = false;
  57. private boolean bound = false;
  58. private boolean connected = false;
  59. private boolean closed = false;
  60. private Object closeLock = new Object();
  61. private boolean shutIn = false;
  62. private boolean shutOut = false;
  63. /**
  64. * The implementation of this Socket.
  65. */
  66. SocketImpl impl;
  67. /**
  68. * Are we using an older SocketImpl?
  69. */
  70. private boolean oldImpl = false;
  71. /**
  72. * Creates an unconnected socket, with the
  73. * system-default type of SocketImpl.
  74. *
  75. * @since JDK1.1
  76. * @revised 1.4
  77. */
  78. public Socket() {
  79. setImpl();
  80. }
  81. /**
  82. * Creates an unconnected socket, specifying the type of proxy, if any,
  83. * that should be used regardless of any other settings.
  84. * <P>
  85. * If there is a security manager, its <code>checkConnect</code> method
  86. * is called with the proxy host address and port number
  87. * as its arguments. This could result in a SecurityException.
  88. * <P>
  89. * Examples:
  90. * <UL> <LI><code>Socket s = new Socket(Proxy.NO_PROXY);</code> will create
  91. * a plain socket ignoring any other proxy configuration.</LI>
  92. * <LI><code>Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("socks.mydom.com", 1080)));</code>
  93. * will create a socket connecting through the specified SOCKS proxy
  94. * server.</LI>
  95. * </UL>
  96. *
  97. * @param proxy a {@link java.net.Proxy Proxy} object specifying what kind
  98. * of proxying should be used.
  99. * @throws IllegalArgumentException if the proxy is of an invalid type
  100. * or <code>null</code>.
  101. * @throws SecurityException if a security manager is present and
  102. * permission to connect to the proxy is
  103. * denied.
  104. * @see java.net.ProxySelector
  105. * @see java.net.Proxy
  106. *
  107. * @since 1.5
  108. */
  109. public Socket(Proxy proxy) {
  110. // Create a copy of Proxy as a security measure
  111. if (proxy == null) {
  112. throw new IllegalArgumentException("Invalid Proxy");
  113. }
  114. Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : sun.net.ApplicationProxy.create(proxy);
  115. if (p.type() == Proxy.Type.SOCKS) {
  116. SecurityManager security = System.getSecurityManager();
  117. InetSocketAddress epoint = (InetSocketAddress) p.address();
  118. if (epoint.getAddress() != null) {
  119. checkAddress (epoint.getAddress(), "Socket");
  120. }
  121. if (security != null) {
  122. if (epoint.isUnresolved())
  123. epoint = new InetSocketAddress(epoint.getHostName(), epoint.getPort());
  124. if (epoint.isUnresolved())
  125. security.checkConnect(epoint.getHostName(),
  126. epoint.getPort());
  127. else
  128. security.checkConnect(epoint.getAddress().getHostAddress(),
  129. epoint.getPort());
  130. }
  131. impl = new SocksSocketImpl(p);
  132. impl.setSocket(this);
  133. } else {
  134. if (p == Proxy.NO_PROXY) {
  135. if (factory == null) {
  136. impl = new PlainSocketImpl();
  137. impl.setSocket(this);
  138. } else
  139. setImpl();
  140. } else
  141. throw new IllegalArgumentException("Invalid Proxy");
  142. }
  143. }
  144. /**
  145. * Creates an unconnected Socket with a user-specified
  146. * SocketImpl.
  147. * <P>
  148. * @param impl an instance of a <B>SocketImpl</B>
  149. * the subclass wishes to use on the Socket.
  150. *
  151. * @exception SocketException if there is an error in the underlying protocol,
  152. * such as a TCP error.
  153. * @since JDK1.1
  154. */
  155. protected Socket(SocketImpl impl) throws SocketException {
  156. this.impl = impl;
  157. if (impl != null) {
  158. checkOldImpl();
  159. this.impl.setSocket(this);
  160. }
  161. }
  162. /**
  163. * Creates a stream socket and connects it to the specified port
  164. * number on the named host.
  165. * <p>
  166. * If the specified host is <tt>null</tt> it is the equivalent of
  167. * specifying the address as <tt>{@link java.net.InetAddress#getByName InetAddress.getByName}(null)</tt>.
  168. * In other words, it is equivalent to specifying an address of the
  169. * loopback interface. </p>
  170. * <p>
  171. * If the application has specified a server socket factory, that
  172. * factory's <code>createSocketImpl</code> method is called to create
  173. * the actual socket implementation. Otherwise a "plain" socket is created.
  174. * <p>
  175. * If there is a security manager, its
  176. * <code>checkConnect</code> method is called
  177. * with the host address and <code>port</code>
  178. * as its arguments. This could result in a SecurityException.
  179. *
  180. * @param host the host name, or <code>null</code> for the loopback address.
  181. * @param port the port number.
  182. *
  183. * @exception UnknownHostException if the IP address of
  184. * the host could not be determined.
  185. *
  186. * @exception IOException if an I/O error occurs when creating the socket.
  187. * @exception SecurityException if a security manager exists and its
  188. * <code>checkConnect</code> method doesn't allow the operation.
  189. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  190. * @see java.net.SocketImpl
  191. * @see java.net.SocketImplFactory#createSocketImpl()
  192. * @see SecurityManager#checkConnect
  193. */
  194. public Socket(String host, int port)
  195. throws UnknownHostException, IOException
  196. {
  197. this(host != null ? new InetSocketAddress(host, port) :
  198. new InetSocketAddress(InetAddress.getByName(null), port),
  199. (SocketAddress) null, true);
  200. }
  201. /**
  202. * Creates a stream socket and connects it to the specified port
  203. * number at the specified IP address.
  204. * <p>
  205. * If the application has specified a socket factory, that factory's
  206. * <code>createSocketImpl</code> method is called to create the
  207. * actual socket implementation. Otherwise a "plain" socket is created.
  208. * <p>
  209. * If there is a security manager, its
  210. * <code>checkConnect</code> method is called
  211. * with the host address and <code>port</code>
  212. * as its arguments. This could result in a SecurityException.
  213. *
  214. * @param address the IP address.
  215. * @param port the port number.
  216. * @exception IOException if an I/O error occurs when creating the socket.
  217. * @exception SecurityException if a security manager exists and its
  218. * <code>checkConnect</code> method doesn't allow the operation.
  219. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  220. * @see java.net.SocketImpl
  221. * @see java.net.SocketImplFactory#createSocketImpl()
  222. * @see SecurityManager#checkConnect
  223. */
  224. public Socket(InetAddress address, int port) throws IOException {
  225. this(address != null ? new InetSocketAddress(address, port) : null,
  226. (SocketAddress) null, true);
  227. }
  228. /**
  229. * Creates a socket and connects it to the specified remote host on
  230. * the specified remote port. The Socket will also bind() to the local
  231. * address and port supplied.
  232. * <p>
  233. * If the specified host is <tt>null</tt> it is the equivalent of
  234. * specifying the address as <tt>{@link java.net.InetAddress#getByName InetAddress.getByName}(null)</tt>.
  235. * In other words, it is equivalent to specifying an address of the
  236. * loopback interface. </p>
  237. * <p>
  238. * If there is a security manager, its
  239. * <code>checkConnect</code> method is called
  240. * with the host address and <code>port</code>
  241. * as its arguments. This could result in a SecurityException.
  242. *
  243. * @param host the name of the remote host, or <code>null</code> for the loopback address.
  244. * @param port the remote port
  245. * @param localAddr the local address the socket is bound to
  246. * @param localPort the local port the socket is bound to
  247. * @exception IOException if an I/O error occurs when creating the socket.
  248. * @exception SecurityException if a security manager exists and its
  249. * <code>checkConnect</code> method doesn't allow the operation.
  250. * @see SecurityManager#checkConnect
  251. * @since JDK1.1
  252. */
  253. public Socket(String host, int port, InetAddress localAddr,
  254. int localPort) throws IOException {
  255. this(host != null ? new InetSocketAddress(host, port) :
  256. new InetSocketAddress(InetAddress.getByName(null), port),
  257. new InetSocketAddress(localAddr, localPort), true);
  258. }
  259. /**
  260. * Creates a socket and connects it to the specified remote address on
  261. * the specified remote port. The Socket will also bind() to the local
  262. * address and port supplied.
  263. * <p>
  264. * If there is a security manager, its
  265. * <code>checkConnect</code> method is called
  266. * with the host address and <code>port</code>
  267. * as its arguments. This could result in a SecurityException.
  268. *
  269. * @param address the remote address
  270. * @param port the remote port
  271. * @param localAddr the local address the socket is bound to
  272. * @param localPort the local port the socket is bound to
  273. * @exception IOException if an I/O error occurs when creating the socket.
  274. * @exception SecurityException if a security manager exists and its
  275. * <code>checkConnect</code> method doesn't allow the operation.
  276. * @see SecurityManager#checkConnect
  277. * @since JDK1.1
  278. */
  279. public Socket(InetAddress address, int port, InetAddress localAddr,
  280. int localPort) throws IOException {
  281. this(address != null ? new InetSocketAddress(address, port) : null,
  282. new InetSocketAddress(localAddr, localPort), true);
  283. }
  284. /**
  285. * Creates a stream socket and connects it to the specified port
  286. * number on the named host.
  287. * <p>
  288. * If the specified host is <tt>null</tt> it is the equivalent of
  289. * specifying the address as <tt>{@link java.net.InetAddress#getByName InetAddress.getByName}(null)</tt>.
  290. * In other words, it is equivalent to specifying an address of the
  291. * loopback interface. </p>
  292. * <p>
  293. * If the stream argument is <code>true</code>, this creates a
  294. * stream socket. If the stream argument is <code>false</code>, it
  295. * creates a datagram socket.
  296. * <p>
  297. * If the application has specified a server socket factory, that
  298. * factory's <code>createSocketImpl</code> method is called to create
  299. * the actual socket implementation. Otherwise a "plain" socket is created.
  300. * <p>
  301. * If there is a security manager, its
  302. * <code>checkConnect</code> method is called
  303. * with the host address and <code>port</code>
  304. * as its arguments. This could result in a SecurityException.
  305. * <p>
  306. * If a UDP socket is used, TCP/IP related socket options will not apply.
  307. *
  308. * @param host the host name, or <code>null</code> for the loopback address.
  309. * @param port the port number.
  310. * @param stream a <code>boolean</code> indicating whether this is
  311. * a stream socket or a datagram socket.
  312. * @exception IOException if an I/O error occurs when creating the socket.
  313. * @exception SecurityException if a security manager exists and its
  314. * <code>checkConnect</code> method doesn't allow the operation.
  315. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  316. * @see java.net.SocketImpl
  317. * @see java.net.SocketImplFactory#createSocketImpl()
  318. * @see SecurityManager#checkConnect
  319. * @deprecated Use DatagramSocket instead for UDP transport.
  320. */
  321. @Deprecated
  322. public Socket(String host, int port, boolean stream) throws IOException {
  323. this(host != null ? new InetSocketAddress(host, port) :
  324. new InetSocketAddress(InetAddress.getByName(null), port),
  325. (SocketAddress) null, stream);
  326. }
  327. /**
  328. * Creates a socket and connects it to the specified port number at
  329. * the specified IP address.
  330. * <p>
  331. * If the stream argument is <code>true</code>, this creates a
  332. * stream socket. If the stream argument is <code>false</code>, it
  333. * creates a datagram socket.
  334. * <p>
  335. * If the application has specified a server socket factory, that
  336. * factory's <code>createSocketImpl</code> method is called to create
  337. * the actual socket implementation. Otherwise a "plain" socket is created.
  338. *
  339. * <p>If there is a security manager, its
  340. * <code>checkConnect</code> method is called
  341. * with <code>host.getHostAddress()</code> and <code>port</code>
  342. * as its arguments. This could result in a SecurityException.
  343. * <p>
  344. * If UDP socket is used, TCP/IP related socket options will not apply.
  345. *
  346. * @param host the IP address.
  347. * @param port the port number.
  348. * @param stream if <code>true</code>, create a stream socket;
  349. * otherwise, create a datagram socket.
  350. * @exception IOException if an I/O error occurs when creating the socket.
  351. * @exception SecurityException if a security manager exists and its
  352. * <code>checkConnect</code> method doesn't allow the operation.
  353. * @see java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
  354. * @see java.net.SocketImpl
  355. * @see java.net.SocketImplFactory#createSocketImpl()
  356. * @see SecurityManager#checkConnect
  357. * @deprecated Use DatagramSocket instead for UDP transport.
  358. */
  359. @Deprecated
  360. public Socket(InetAddress host, int port, boolean stream) throws IOException {
  361. this(host != null ? new InetSocketAddress(host, port) : null,
  362. new InetSocketAddress(0), stream);
  363. }
  364. private Socket(SocketAddress address, SocketAddress localAddr,
  365. boolean stream) throws IOException {
  366. setImpl();
  367. // backward compatibility
  368. if (address == null)
  369. throw new NullPointerException();
  370. try {
  371. createImpl(stream);
  372. if (localAddr != null)
  373. bind(localAddr);
  374. if (address != null)
  375. connect(address);
  376. } catch (IOException e) {
  377. close();
  378. throw e;
  379. }
  380. }
  381. /**
  382. * Creates the socket implementation.
  383. *
  384. * @param stream a <code>boolean</code> value : <code>true</code> for a TCP socket,
  385. * <code>false</code> for UDP.
  386. * @throws IOException if creation fails
  387. * @since 1.4
  388. */
  389. void createImpl(boolean stream) throws SocketException {
  390. if (impl == null)
  391. setImpl();
  392. try {
  393. impl.create(stream);
  394. created = true;
  395. } catch (IOException e) {
  396. throw new SocketException(e.getMessage());
  397. }
  398. }
  399. private void checkOldImpl() {
  400. if (impl == null)
  401. return;
  402. // SocketImpl.connect() is a protected method, therefore we need to use
  403. // getDeclaredMethod, therefore we need permission to access the member
  404. oldImpl = AccessController.doPrivileged
  405. (new PrivilegedAction<Boolean>() {
  406. public Boolean run() {
  407. Class[] cl = new Class[2];
  408. cl[0] = SocketAddress.class;
  409. cl[1] = Integer.TYPE;
  410. Class clazz = impl.getClass();
  411. while (true) {
  412. try {
  413. clazz.getDeclaredMethod("connect", cl);
  414. return Boolean.FALSE;
  415. } catch (NoSuchMethodException e) {
  416. clazz = clazz.getSuperclass();
  417. // java.net.SocketImpl class will always have this abstract method.
  418. // If we have not found it by now in the hierarchy then it does not
  419. // exist, we are an old style impl.
  420. if (clazz.equals(java.net.SocketImpl.class)) {
  421. return Boolean.TRUE;
  422. }
  423. }
  424. }
  425. }
  426. });
  427. }
  428. /**
  429. * Sets impl to the system-default type of SocketImpl.
  430. * @since 1.4
  431. */
  432. void setImpl() {
  433. if (factory != null) {
  434. impl = factory.createSocketImpl();
  435. checkOldImpl();
  436. } else {
  437. // No need to do a checkOldImpl() here, we know it's an up to date
  438. // SocketImpl!
  439. impl = new SocksSocketImpl();
  440. }
  441. if (impl != null)
  442. impl.setSocket(this);
  443. }
  444. /**
  445. * Get the <code>SocketImpl</code> attached to this socket, creating
  446. * it if necessary.
  447. *
  448. * @return the <code>SocketImpl</code> attached to that ServerSocket.
  449. * @throws SocketException if creation fails
  450. * @since 1.4
  451. */
  452. SocketImpl getImpl() throws SocketException {
  453. if (!created)
  454. createImpl(true);
  455. return impl;
  456. }
  457. /**
  458. * Connects this socket to the server.
  459. *
  460. * @param endpoint the <code>SocketAddress</code>
  461. * @throws IOException if an error occurs during the connection
  462. * @throws java.nio.channels.IllegalBlockingModeException
  463. * if this socket has an associated channel,
  464. * and the channel is in non-blocking mode
  465. * @throws IllegalArgumentException if endpoint is null or is a
  466. * SocketAddress subclass not supported by this socket
  467. * @since 1.4
  468. * @spec JSR-51
  469. */
  470. public void connect(SocketAddress endpoint) throws IOException {
  471. connect(endpoint, 0);
  472. }
  473. /**
  474. * Connects this socket to the server with a specified timeout value.
  475. * A timeout of zero is interpreted as an infinite timeout. The connection
  476. * will then block until established or an error occurs.
  477. *
  478. * @param endpoint the <code>SocketAddress</code>
  479. * @param timeout the timeout value to be used in milliseconds.
  480. * @throws IOException if an error occurs during the connection
  481. * @throws SocketTimeoutException if timeout expires before connecting
  482. * @throws java.nio.channels.IllegalBlockingModeException
  483. * if this socket has an associated channel,
  484. * and the channel is in non-blocking mode
  485. * @throws IllegalArgumentException if endpoint is null or is a
  486. * SocketAddress subclass not supported by this socket
  487. * @since 1.4
  488. * @spec JSR-51
  489. */
  490. public void connect(SocketAddress endpoint, int timeout) throws IOException {
  491. if (endpoint == null)
  492. throw new IllegalArgumentException("connect: The address can't be null");
  493. if (timeout < 0)
  494. throw new IllegalArgumentException("connect: timeout can't be negative");
  495. if (isClosed())
  496. throw new SocketException("Socket is closed");
  497. if (!oldImpl && isConnected())
  498. throw new SocketException("already connected");
  499. if (!(endpoint instanceof InetSocketAddress))
  500. throw new IllegalArgumentException("Unsupported address type");
  501. InetSocketAddress epoint = (InetSocketAddress) endpoint;
  502. InetAddress addr = epoint.getAddress ();
  503. int port = epoint.getPort();
  504. checkAddress(addr, "connect");
  505. SecurityManager security = System.getSecurityManager();
  506. if (security != null) {
  507. if (epoint.isUnresolved())
  508. security.checkConnect(epoint.getHostName(), port);
  509. else
  510. security.checkConnect(addr.getHostAddress(), port);
  511. }
  512. if (!created)
  513. createImpl(true);
  514. if (!oldImpl)
  515. impl.connect(epoint, timeout);
  516. else if (timeout == 0) {
  517. if (epoint.isUnresolved())
  518. impl.connect(addr.getHostName(), port);
  519. else
  520. impl.connect(addr, port);
  521. } else
  522. throw new UnsupportedOperationException("SocketImpl.connect(addr, timeout)");
  523. connected = true;
  524. /*
  525. * If the socket was not bound before the connect, it is now because
  526. * the kernel will have picked an ephemeral port & a local address
  527. */
  528. bound = true;
  529. }
  530. /**
  531. * Binds the socket to a local address.
  532. * <P>
  533. * If the address is <code>null</code>, then the system will pick up
  534. * an ephemeral port and a valid local address to bind the socket.
  535. *
  536. * @param bindpoint the <code>SocketAddress</code> to bind to
  537. * @throws IOException if the bind operation fails, or if the socket
  538. * is already bound.
  539. * @throws IllegalArgumentException if bindpoint is a
  540. * SocketAddress subclass not supported by this socket
  541. *
  542. * @since 1.4
  543. * @see #isBound
  544. */
  545. public void bind(SocketAddress bindpoint) throws IOException {
  546. if (isClosed())
  547. throw new SocketException("Socket is closed");
  548. if (!oldImpl && isBound())
  549. throw new SocketException("Already bound");
  550. if (bindpoint != null && (!(bindpoint instanceof InetSocketAddress)))
  551. throw new IllegalArgumentException("Unsupported address type");
  552. InetSocketAddress epoint = (InetSocketAddress) bindpoint;
  553. if (epoint != null && epoint.isUnresolved())
  554. throw new SocketException("Unresolved address");
  555. if (epoint == null) {
  556. epoint = new InetSocketAddress(0);
  557. }
  558. InetAddress addr = epoint.getAddress();
  559. int port = epoint.getPort();
  560. checkAddress (addr, "bind");
  561. getImpl().bind (addr, port);
  562. bound = true;
  563. }
  564. private void checkAddress (InetAddress addr, String op) {
  565. if (addr == null) {
  566. return;
  567. }
  568. if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) {
  569. throw new IllegalArgumentException(op + ": invalid address type");
  570. }
  571. }
  572. /**
  573. * set the flags after an accept() call.
  574. */
  575. final void postAccept() {
  576. connected = true;
  577. created = true;
  578. bound = true;
  579. }
  580. void setCreated() {
  581. created = true;
  582. }
  583. void setBound() {
  584. bound = true;
  585. }
  586. void setConnected() {
  587. connected = true;
  588. }
  589. /**
  590. * Returns the address to which the socket is connected.
  591. *
  592. * @return the remote IP address to which this socket is connected,
  593. * or <code>null</code> if the socket is not connected.
  594. */
  595. public InetAddress getInetAddress() {
  596. if (!isConnected())
  597. return null;
  598. try {
  599. return getImpl().getInetAddress();
  600. } catch (SocketException e) {
  601. }
  602. return null;
  603. }
  604. /**
  605. * Gets the local address to which the socket is bound.
  606. *
  607. * @return the local address to which the socket is bound or
  608. * <code>InetAddress.anyLocalAddress()</code>
  609. * if the socket is not bound yet.
  610. * @since JDK1.1
  611. */
  612. public InetAddress getLocalAddress() {
  613. // This is for backward compatibility
  614. if (!isBound())
  615. return InetAddress.anyLocalAddress();
  616. InetAddress in = null;
  617. try {
  618. in = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR);
  619. if (in.isAnyLocalAddress()) {
  620. in = InetAddress.anyLocalAddress();
  621. }
  622. } catch (Exception e) {
  623. in = InetAddress.anyLocalAddress(); // "0.0.0.0"
  624. }
  625. return in;
  626. }
  627. /**
  628. * Returns the remote port number to which this socket is connected.
  629. *
  630. * @return the remote port number to which this socket is connected, or
  631. * 0 if the socket is not connected yet.
  632. */
  633. public int getPort() {
  634. if (!isConnected())
  635. return 0;
  636. try {
  637. return getImpl().getPort();
  638. } catch (SocketException e) {
  639. // Shouldn't happen as we're connected
  640. }
  641. return -1;
  642. }
  643. /**
  644. * Returns the local port number to which this socket is bound.
  645. *
  646. * @return the local port number to which this socket is bound or -1
  647. * if the socket is not bound yet.
  648. */
  649. public int getLocalPort() {
  650. if (!isBound())
  651. return -1;
  652. try {
  653. return getImpl().getLocalPort();
  654. } catch(SocketException e) {
  655. // shouldn't happen as we're bound
  656. }
  657. return -1;
  658. }
  659. /**
  660. * Returns the address of the endpoint this socket is connected to, or
  661. * <code>null</code> if it is unconnected.
  662. *
  663. * @return a <code>SocketAddress</code> reprensenting the remote endpoint of this
  664. * socket, or <code>null</code> if it is not connected yet.
  665. * @see #getInetAddress()
  666. * @see #getPort()
  667. * @see #connect(SocketAddress, int)
  668. * @see #connect(SocketAddress)
  669. * @since 1.4
  670. */
  671. public SocketAddress getRemoteSocketAddress() {
  672. if (!isConnected())
  673. return null;
  674. return new InetSocketAddress(getInetAddress(), getPort());
  675. }
  676. /**
  677. * Returns the address of the endpoint this socket is bound to, or
  678. * <code>null</code> if it is not bound yet.
  679. *
  680. * @return a <code>SocketAddress</code> representing the local endpoint of this
  681. * socket, or <code>null</code> if it is not bound yet.
  682. * @see #getLocalAddress()
  683. * @see #getLocalPort()
  684. * @see #bind(SocketAddress)
  685. * @since 1.4
  686. */
  687. public SocketAddress getLocalSocketAddress() {
  688. if (!isBound())
  689. return null;
  690. return new InetSocketAddress(getLocalAddress(), getLocalPort());
  691. }
  692. /**
  693. * Returns the unique {@link java.nio.channels.SocketChannel SocketChannel}
  694. * object associated with this socket, if any.
  695. *
  696. * <p> A socket will have a channel if, and only if, the channel itself was
  697. * created via the {@link java.nio.channels.SocketChannel#open
  698. * SocketChannel.open} or {@link
  699. * java.nio.channels.ServerSocketChannel#accept ServerSocketChannel.accept}
  700. * methods.
  701. *
  702. * @return the socket channel associated with this socket,
  703. * or <tt>null</tt> if this socket was not created
  704. * for a channel
  705. *
  706. * @since 1.4
  707. * @spec JSR-51
  708. */
  709. public SocketChannel getChannel() {
  710. return null;
  711. }
  712. /**
  713. * Returns an input stream for this socket.
  714. *
  715. * <p> If this socket has an associated channel then the resulting input
  716. * stream delegates all of its operations to the channel. If the channel
  717. * is in non-blocking mode then the input stream's <tt>read</tt> operations
  718. * will throw an {@link java.nio.channels.IllegalBlockingModeException}.
  719. *
  720. * <p>Under abnormal conditions the underlying connection may be
  721. * broken by the remote host or the network software (for example
  722. * a connection reset in the case of TCP connections). When a
  723. * broken connection is detected by the network software the
  724. * following applies to the returned input stream :-
  725. *
  726. * <ul>
  727. *
  728. * <li><p>The network software may discard bytes that are buffered
  729. * by the socket. Bytes that aren't discarded by the network
  730. * software can be read using {@link java.io.InputStream#read read}.
  731. *
  732. * <li><p>If there are no bytes buffered on the socket, or all
  733. * buffered bytes have been consumed by
  734. * {@link java.io.InputStream#read read}, then all subsequent
  735. * calls to {@link java.io.InputStream#read read} will throw an
  736. * {@link java.io.IOException IOException}.
  737. *
  738. * <li><p>If there are no bytes buffered on the socket, and the
  739. * socket has not been closed using {@link #close close}, then
  740. * {@link java.io.InputStream#available available} will
  741. * return <code>0</code>.
  742. *
  743. * </ul>
  744. *
  745. * <p> Closing the returned {@link java.io.InputStream InputStream}
  746. * will close the associated socket.
  747. *
  748. * @return an input stream for reading bytes from this socket.
  749. * @exception IOException if an I/O error occurs when creating the
  750. * input stream, the socket is closed, the socket is
  751. * not connected, or the socket input has been shutdown
  752. * using {@link #shutdownInput()}
  753. *
  754. * @revised 1.4
  755. * @spec JSR-51
  756. */
  757. public InputStream getInputStream() throws IOException {
  758. if (isClosed())
  759. throw new SocketException("Socket is closed");
  760. if (!isConnected())
  761. throw new SocketException("Socket is not connected");
  762. if (isInputShutdown())
  763. throw new SocketException("Socket input is shutdown");
  764. final Socket s = this;
  765. InputStream is = null;
  766. try {
  767. is = (InputStream)
  768. AccessController.doPrivileged(new PrivilegedExceptionAction() {
  769. public Object run() throws IOException {
  770. return impl.getInputStream();
  771. }
  772. });
  773. } catch (java.security.PrivilegedActionException e) {
  774. throw (IOException) e.getException();
  775. }
  776. return is;
  777. }
  778. /**
  779. * Returns an output stream for this socket.
  780. *
  781. * <p> If this socket has an associated channel then the resulting output
  782. * stream delegates all of its operations to the channel. If the channel
  783. * is in non-blocking mode then the output stream's <tt>write</tt>
  784. * operations will throw an {@link
  785. * java.nio.channels.IllegalBlockingModeException}.
  786. *
  787. * <p> Closing the returned {@link java.io.OutputStream OutputStream}
  788. * will close the associated socket.
  789. *
  790. * @return an output stream for writing bytes to this socket.
  791. * @exception IOException if an I/O error occurs when creating the
  792. * output stream or if the socket is not connected.
  793. * @revised 1.4
  794. * @spec JSR-51
  795. */
  796. public OutputStream getOutputStream() throws IOException {
  797. if (isClosed())
  798. throw new SocketException("Socket is closed");
  799. if (!isConnected())
  800. throw new SocketException("Socket is not connected");
  801. if (isOutputShutdown())
  802. throw new SocketException("Socket output is shutdown");
  803. final Socket s = this;
  804. OutputStream os = null;
  805. try {
  806. os = (OutputStream)
  807. AccessController.doPrivileged(new PrivilegedExceptionAction() {
  808. public Object run() throws IOException {
  809. return impl.getOutputStream();
  810. }
  811. });
  812. } catch (java.security.PrivilegedActionException e) {
  813. throw (IOException) e.getException();
  814. }
  815. return os;
  816. }
  817. /**
  818. * Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).
  819. *
  820. * @param on <code>true</code> to enable TCP_NODELAY,
  821. * <code>false</code> to disable.
  822. *
  823. * @exception SocketException if there is an error
  824. * in the underlying protocol, such as a TCP error.
  825. *
  826. * @since JDK1.1
  827. *
  828. * @see #getTcpNoDelay()
  829. */
  830. public void setTcpNoDelay(boolean on) throws SocketException {
  831. if (isClosed())
  832. throw new SocketException("Socket is closed");
  833. getImpl().setOption(SocketOptions.TCP_NODELAY, Boolean.valueOf(on));
  834. }
  835. /**
  836. * Tests if TCP_NODELAY is enabled.
  837. *
  838. * @return a <code>boolean</code> indicating whether or not TCP_NODELAY is enabled.
  839. * @exception SocketException if there is an error
  840. * in the underlying protocol, such as a TCP error.
  841. * @since JDK1.1
  842. * @see #setTcpNoDelay(boolean)
  843. */
  844. public boolean getTcpNoDelay() throws SocketException {
  845. if (isClosed())
  846. throw new SocketException("Socket is closed");
  847. return ((Boolean) getImpl().getOption(SocketOptions.TCP_NODELAY)).booleanValue();
  848. }
  849. /**
  850. * Enable/disable SO_LINGER with the specified linger time in seconds.
  851. * The maximum timeout value is platform specific.
  852. *
  853. * The setting only affects socket close.
  854. *
  855. * @param on whether or not to linger on.
  856. * @param linger how long to linger for, if on is true.
  857. * @exception SocketException if there is an error
  858. * in the underlying protocol, such as a TCP error.
  859. * @exception IllegalArgumentException if the linger value is negative.
  860. * @since JDK1.1
  861. * @see #getSoLinger()
  862. */
  863. public void setSoLinger(boolean on, int linger) throws SocketException {
  864. if (isClosed())
  865. throw new SocketException("Socket is closed");
  866. if (!on) {
  867. getImpl().setOption(SocketOptions.SO_LINGER, new Boolean(on));
  868. } else {
  869. if (linger < 0) {
  870. throw new IllegalArgumentException("invalid value for SO_LINGER");
  871. }
  872. if (linger > 65535)
  873. linger = 65535;
  874. getImpl().setOption(SocketOptions.SO_LINGER, new Integer(linger));
  875. }
  876. }
  877. /**
  878. * Returns setting for SO_LINGER. -1 returns implies that the
  879. * option is disabled.
  880. *
  881. * The setting only affects socket close.
  882. *
  883. * @return the setting for SO_LINGER.
  884. * @exception SocketException if there is an error
  885. * in the underlying protocol, such as a TCP error.
  886. * @since JDK1.1
  887. * @see #setSoLinger(boolean, int)
  888. */
  889. public int getSoLinger() throws SocketException {
  890. if (isClosed())
  891. throw new SocketException("Socket is closed");
  892. Object o = getImpl().getOption(SocketOptions.SO_LINGER);
  893. if (o instanceof Integer) {
  894. return ((Integer) o).intValue();
  895. } else {
  896. return -1;
  897. }
  898. }
  899. /**
  900. * Send one byte of urgent data on the socket. The byte to be sent is the lowest eight
  901. * bits of the data parameter. The urgent byte is
  902. * sent after any preceding writes to the socket OutputStream
  903. * and before any future writes to the OutputStream.
  904. * @param data The byte of data to send
  905. * @exception IOException if there is an error
  906. * sending the data.
  907. * @since 1.4
  908. */
  909. public void sendUrgentData (int data) throws IOException {
  910. if (!getImpl().supportsUrgentData ()) {
  911. throw new SocketException ("Urgent data not supported");
  912. }
  913. getImpl().sendUrgentData (data);
  914. }
  915. /**
  916. * Enable/disable OOBINLINE (receipt of TCP urgent data)
  917. *
  918. * By default, this option is disabled and TCP urgent data received on a
  919. * socket is silently discarded. If the user wishes to receive urgent data, then
  920. * this option must be enabled. When enabled, urgent data is received
  921. * inline with normal data.
  922. * <p>
  923. * Note, only limited support is provided for handling incoming urgent
  924. * data. In particular, no notification of incoming urgent data is provided
  925. * and there is no capability to distinguish between normal data and urgent
  926. * data unless provided by a higher level protocol.
  927. *
  928. * @param on <code>true</code> to enable OOBINLINE,
  929. * <code>false</code> to disable.
  930. *
  931. * @exception SocketException if there is an error
  932. * in the underlying protocol, such as a TCP error.
  933. *
  934. * @since 1.4
  935. *
  936. * @see #getOOBInline()
  937. */
  938. public void setOOBInline(boolean on) throws SocketException {
  939. if (isClosed())
  940. throw new SocketException("Socket is closed");
  941. getImpl().setOption(SocketOptions.SO_OOBINLINE, Boolean.valueOf(on));
  942. }
  943. /**
  944. * Tests if OOBINLINE is enabled.
  945. *
  946. * @return a <code>boolean</code> indicating whether or not OOBINLINE is enabled.
  947. * @exception SocketException if there is an error
  948. * in the underlying protocol, such as a TCP error.
  949. * @since 1.4
  950. * @see #setOOBInline(boolean)
  951. */
  952. public boolean getOOBInline() throws SocketException {
  953. if (isClosed())
  954. throw new SocketException("Socket is closed");
  955. return ((Boolean) getImpl().getOption(SocketOptions.SO_OOBINLINE)).booleanValue();
  956. }
  957. /**
  958. * Enable/disable SO_TIMEOUT with the specified timeout, in
  959. * milliseconds. With this option set to a non-zero timeout,
  960. * a read() call on the InputStream associated with this Socket
  961. * will block for only this amount of time. If the timeout expires,
  962. * a <B>java.net.SocketTimeoutException</B> is raised, though the
  963. * Socket is still valid. The option <B>must</B> be enabled
  964. * prior to entering the blocking operation to have effect. The
  965. * timeout must be > 0.
  966. * A timeout of zero is interpreted as an infinite timeout.
  967. * @param timeout the specified timeout, in milliseconds.
  968. * @exception SocketException if there is an error
  969. * in the underlying protocol, such as a TCP error.
  970. * @since JDK 1.1
  971. * @see #getSoTimeout()
  972. */
  973. public synchronized void setSoTimeout(int timeout) throws SocketException {
  974. if (isClosed())
  975. throw new SocketException("Socket is closed");
  976. if (timeout < 0)
  977. throw new IllegalArgumentException("timeout can't be negative");
  978. getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
  979. }
  980. /**
  981. * Returns setting for SO_TIMEOUT. 0 returns implies that the
  982. * option is disabled (i.e., timeout of infinity).
  983. * @return the setting for SO_TIMEOUT
  984. * @exception SocketException if there is an error
  985. * in the underlying protocol, such as a TCP error.
  986. * @since JDK1.1
  987. * @see #setSoTimeout(int)
  988. */
  989. public synchronized int getSoTimeout() throws SocketException {
  990. if (isClosed())
  991. throw new SocketException("Socket is closed");
  992. Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
  993. /* extra type safety */
  994. if (o instanceof Integer) {
  995. return ((Integer) o).intValue();
  996. } else {
  997. return 0;
  998. }
  999. }
  1000. /**
  1001. * Sets the SO_SNDBUF option to the specified value for this
  1002. * <tt>Socket</tt>. The SO_SNDBUF option is used by the platform's
  1003. * networking code as a hint for the size to set
  1004. * the underlying network I/O buffers.
  1005. *
  1006. * <p>Because SO_SNDBUF is a hint, applications that want to
  1007. * verify what size the buffers were set to should call
  1008. * {@link #getSendBufferSize()}.
  1009. *
  1010. * @exception SocketException if there is an error
  1011. * in the underlying protocol, such as a TCP error.
  1012. *
  1013. * @param size the size to which to set the send buffer
  1014. * size. This value must be greater than 0.
  1015. *
  1016. * @exception IllegalArgumentException if the
  1017. * value is 0 or is negative.
  1018. *
  1019. * @see #getSendBufferSize()
  1020. * @since 1.2
  1021. */
  1022. public synchronized void setSendBufferSize(int size)
  1023. throws SocketException{
  1024. if (!(size > 0)) {
  1025. throw new IllegalArgumentException("negative send size");
  1026. }
  1027. if (isClosed())
  1028. throw new SocketException("Socket is closed");
  1029. getImpl().setOption(SocketOptions.SO_SNDBUF, new Integer(size));
  1030. }
  1031. /**
  1032. * Get value of the SO_SNDBUF option for this <tt>Socket</tt>,
  1033. * that is the buffer size used by the platform
  1034. * for output on this <tt>Socket</tt>.
  1035. * @return the value of the SO_SNDBUF option for this <tt>Socket</tt>.
  1036. *
  1037. * @exception SocketException if there is an error
  1038. * in the underlying protocol, such as a TCP error.
  1039. *
  1040. * @see #setSendBufferSize(int)
  1041. * @since 1.2
  1042. */
  1043. public synchronized int getSendBufferSize() throws SocketException {
  1044. if (isClosed())
  1045. throw new SocketException("Socket is closed");
  1046. int result = 0;
  1047. Object o = getImpl().getOption(SocketOptions.SO_SNDBUF);
  1048. if (o instanceof Integer) {
  1049. result = ((Integer)o).intValue();
  1050. }
  1051. return result;
  1052. }
  1053. /**
  1054. * Sets the SO_RCVBUF option to the specified value for this
  1055. * <tt>Socket</tt>. The SO_RCVBUF option is used by the platform's
  1056. * networking code as a hint for the size to set
  1057. * the underlying network I/O buffers.
  1058. *
  1059. * <p>Increasing the receive buffer size can increase the performance of
  1060. * network I/O for high-volume connection, while decreasing it can
  1061. * help reduce the backlog of incoming data.
  1062. *
  1063. * <p>Because SO_RCVBUF is a hint, applications that want to
  1064. * verify what size the buffers were set to should call
  1065. * {@link #getReceiveBufferSize()}.
  1066. *
  1067. * <p>The value of SO_RCVBUF is also used to set the TCP receive window
  1068. * that is advertized to the remote peer. Generally, the window size
  1069. * can be modified at any time when a socket is connected. However, if
  1070. * a receive window larger than 64K is required then this must be requested
  1071. * <B>before</B> the socket is connected to the remote peer. There are two
  1072. * cases to be aware of:<p>
  1073. * <ol>
  1074. * <li>For sockets accepted from a ServerSocket, this must be done by calling
  1075. * {@link ServerSocket#setReceiveBufferSize(int)} before the ServerSocket
  1076. * is bound to a local address.<p></li>
  1077. * <li>For client sockets, setReceiveBufferSize() must be called before
  1078. * connecting the socket to its remote peer.<p></li></ol>
  1079. * @param size the size to which to set the receive buffer
  1080. * size. This value must be greater than 0.
  1081. *
  1082. * @exception IllegalArgumentException if the value is 0 or is
  1083. * negative.
  1084. *
  1085. * @exception SocketException if there is an error
  1086. * in the underlying protocol, such as a TCP error.
  1087. *
  1088. * @see #getReceiveBufferSize()
  1089. * @see ServerSocket#setReceiveBufferSize(int)
  1090. * @since 1.2
  1091. */
  1092. public synchronized void setReceiveBufferSize(int size)
  1093. throws SocketException{
  1094. if (size <= 0) {
  1095. throw new IllegalArgumentException("invalid receive size");
  1096. }
  1097. if (isClosed())
  1098. throw new SocketException("Socket is closed");
  1099. getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
  1100. }
  1101. /**
  1102. * Gets the value of the SO_RCVBUF option for this <tt>Socket</tt>,
  1103. * that is the buffer size used by the platform for
  1104. * input on this <tt>Socket</tt>.
  1105. *
  1106. * @return the value of the SO_RCVBUF option for this <tt>Socket</tt>.
  1107. * @exception SocketException if there is an error
  1108. * in the underlying protocol, such as a TCP error.
  1109. * @see #setReceiveBufferSize(int)
  1110. * @since 1.2
  1111. */
  1112. public synchronized int getReceiveBufferSize()
  1113. throws SocketException{
  1114. if (isClosed())
  1115. throw new SocketException("Socket is closed");
  1116. int result = 0;
  1117. Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
  1118. if (o instanceof Integer) {
  1119. result = ((Integer)o).intValue();
  1120. }
  1121. return result;
  1122. }
  1123. /**
  1124. * Enable/disable SO_KEEPALIVE.
  1125. *
  1126. * @param on whether or not to have socket keep alive turned on.
  1127. * @exception SocketException if there is an error
  1128. * in the underlying protocol, such as a TCP error.
  1129. * @since 1.3
  1130. * @see #getKeepAlive()
  1131. */
  1132. public void setKeepAlive(boolean on) throws SocketException {
  1133. if (isClosed())
  1134. throw new SocketException("Socket is closed");
  1135. getImpl().setOption(SocketOptions.SO_KEEPALIVE, Boolean.valueOf(on));
  1136. }
  1137. /**
  1138. * Tests if SO_KEEPALIVE is enabled.
  1139. *
  1140. * @return a <code>boolean</code> indicating whether or not SO_KEEPALIVE is enabled.
  1141. * @exception SocketException if there is an error
  1142. * in the underlying protocol, such as a TCP error.
  1143. * @since 1.3
  1144. * @see #setKeepAlive(boolean)
  1145. */
  1146. public boolean getKeepAlive() throws SocketException {
  1147. if (isClosed())
  1148. throw new SocketException("Socket is closed");
  1149. return ((Boolean) getImpl().getOption(SocketOptions.SO_KEEPALIVE)).booleanValue();
  1150. }
  1151. /**
  1152. * Sets traffic class or type-of-service octet in the IP
  1153. * header for packets sent from this Socket.
  1154. * As the underlying network implementation may ignore this
  1155. * value applications should consider it a hint.
  1156. *
  1157. * <P> The tc <B>must</B> be in the range <code> 0 <= tc <=
  1158. * 255</code> or an IllegalArgumentException will be thrown.
  1159. * <p>Notes:
  1160. * <p> For Internet Protocol v4 the value consists of an octet
  1161. * with precedence and TOS fields as detailed in RFC 1349. The
  1162. * TOS field is bitset created by bitwise-or'ing values such
  1163. * the following :-
  1164. * <p>
  1165. * <UL>
  1166. * <LI><CODE>IPTOS_LOWCOST (0x02)</CODE></LI>
  1167. * <LI><CODE>IPTOS_RELIABILITY (0x04)</CODE></LI>
  1168. * <LI><CODE>IPTOS_THROUGHPUT (0x08)</CODE></LI>
  1169. * <LI><CODE>IPTOS_LOWDELAY (0x10)</CODE></LI>
  1170. * </UL>
  1171. * The last low order bit is always ignored as this
  1172. * corresponds to the MBZ (must be zero) bit.
  1173. * <p>
  1174. * Setting bits in the precedence field may result in a
  1175. * SocketException indicating that the operation is not
  1176. * permitted.
  1177. * <p>
  1178. * As RFC 1122 section 4.2.4.2 indicates, a compliant TCP
  1179. * implementation should, but is not required to, let application
  1180. * change the TOS field during the lifetime of a connection.
  1181. * So whether the type-of-service field can be changed after the
  1182. * TCP connection has been established depends on the implementation
  1183. * in the underlying platform. Applications should not assume that
  1184. * they can change the TOS field after the connection.
  1185. * <p>
  1186. * For Internet Protocol v6 <code>tc</code> is the value that
  1187. * would be placed into the sin6_flowinfo field of the IP header.
  1188. *
  1189. * @param tc an <code>int</code> value for the bitset.
  1190. * @throws SocketException if there is an error setting the
  1191. * traffic class or type-of-service
  1192. * @since 1.4
  1193. * @see #getTrafficClass
  1194. */
  1195. public void setTrafficClass(int tc) throws SocketException {
  1196. if (tc < 0 || tc > 255)
  1197. throw new IllegalArgumentException("tc is not in range 0 -- 255");
  1198. if (isClosed())
  1199. throw new SocketException("Socket is closed");
  1200. getImpl().setOption(SocketOptions.IP_TOS, new Integer(tc));
  1201. }
  1202. /**
  1203. * Gets traffic class or type-of-service in the IP header
  1204. * for packets sent from this Socket
  1205. * <p>
  1206. * As the underlying network implementation may ignore the
  1207. * traffic class or type-of-service set using {@link #setTrafficClass(int)}
  1208. * this method may return a different value than was previously
  1209. * set using the {@link #setTrafficClass(int)} method on this Socket.
  1210. *
  1211. * @return the traffic class or type-of-service already set
  1212. * @throws SocketException if there is an error obtaining the
  1213. * traffic class or type-of-service value.
  1214. * @since 1.4
  1215. * @see #setTrafficClass(int)
  1216. */
  1217. public int getTrafficClass() throws SocketException {
  1218. return ((Integer) (getImpl().getOption(SocketOptions.IP_TOS))).intValue();
  1219. }
  1220. /**
  1221. * Enable/disable the SO_REUSEADDR socket option.
  1222. * <p>
  1223. * When a TCP connection is closed the connection may remain
  1224. * in a timeout state for a period of time after the connection
  1225. * is closed (typically known as the <tt>TIME_WAIT</tt> state
  1226. * or <tt>2MSL</tt> wait state).
  1227. * For applications using a well known socket address or port
  1228. * it may not be possible to bind a socket to the required
  1229. * <tt>SocketAddress</tt> if there is a connection in the
  1230. * timeout state involving the socket address or port.
  1231. * <p>
  1232. * Enabling <tt>SO_REUSEADDR</tt> prior to binding the socket
  1233. * using {@link #bind(SocketAddress)} allows the socket to be
  1234. * bound even though a previous connection is in a timeout
  1235. * state.
  1236. * <p>
  1237. * When a <tt>Socket</tt> is created the initial setting
  1238. * of <tt>SO_REUSEADDR</tt> is disabled.
  1239. * <p>
  1240. * The behaviour when <tt>SO_REUSEADDR</tt> is enabled or
  1241. * disabled after a socket is bound (See {@link #isBound()})
  1242. * is not defined.
  1243. *
  1244. * @param on whether to enable or disable the socket option
  1245. * @exception SocketException if an error occurs enabling or
  1246. * disabling the <tt>SO_RESUEADDR</tt> socket option,
  1247. * or the socket is closed.
  1248. * @since 1.4
  1249. * @see #getReuseAddress()
  1250. * @see #bind(SocketAddress)
  1251. * @see #isClosed()
  1252. * @see #isBound()
  1253. */
  1254. public void setReuseAddress(boolean on) throws SocketException {
  1255. if (isClosed())
  1256. throw new SocketException("Socket is closed");
  1257. getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
  1258. }
  1259. /**
  1260. * Tests if SO_REUSEADDR is enabled.
  1261. *
  1262. * @return a <code>boolean</code> indicating whether or not SO_REUSEADDR is enabled.
  1263. * @exception SocketException if there is an error
  1264. * in the underlying protocol, such as a TCP error.
  1265. * @since 1.4
  1266. * @see #setReuseAddress(boolean)
  1267. */
  1268. public boolean getReuseAddress() throws SocketException {
  1269. if (isClosed())
  1270. throw new SocketException("Socket is closed");
  1271. return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
  1272. }
  1273. /**
  1274. * Closes this socket.
  1275. * <p>
  1276. * Any thread currently blocked in an I/O operation upon this socket
  1277. * will throw a {@link SocketException}.
  1278. * <p>
  1279. * Once a socket has been closed, it is not available for further networking
  1280. * use (i.e. can't be reconnected or rebound). A new socket needs to be
  1281. * created.
  1282. *
  1283. * <p> Closing this socket will also close the socket's
  1284. * {@link java.io.InputStream InputStream} and
  1285. * {@link java.io.OutputStream OutputStream}.
  1286. *
  1287. * <p> If this socket has an associated channel then the channel is closed
  1288. * as well.
  1289. *
  1290. * @exception IOException if an I/O error occurs when closing this socket.
  1291. * @revised 1.4
  1292. * @spec JSR-51
  1293. * @see #isClosed
  1294. */
  1295. public synchronized void close() throws IOException {
  1296. synchronized(closeLock) {
  1297. if (isClosed())
  1298. return;
  1299. if (created)
  1300. impl.close();
  1301. closed = true;
  1302. }
  1303. }
  1304. /**
  1305. * Places the input stream for this socket at "end of stream".
  1306. * Any data sent to the input stream side of the socket is acknowledged
  1307. * and then silently discarded.
  1308. * <p>
  1309. * If you read from a socket input stream after invoking
  1310. * shutdownInput() on the socket, the stream will return EOF.
  1311. *
  1312. * @exception IOException if an I/O error occurs when shutting down this
  1313. * socket.
  1314. *
  1315. * @since 1.3
  1316. * @see java.net.Socket#shutdownOutput()
  1317. * @see java.net.Socket#close()
  1318. * @see java.net.Socket#setSoLinger(boolean, int)
  1319. * @see #isInputShutdown
  1320. */
  1321. public void shutdownInput() throws IOException
  1322. {
  1323. if (isClosed())
  1324. throw new SocketException("Socket is closed");
  1325. if (!isConnected())
  1326. throw new SocketException("Socket is not connected");
  1327. if (isInputShutdown())
  1328. throw new SocketException("Socket input is already shutdown");
  1329. getImpl().shutdownInput();
  1330. shutIn = true;
  1331. }
  1332. /**
  1333. * Disables the output stream for this socket.
  1334. * For a TCP socket, any previously written data will be sent
  1335. * followed by TCP's normal connection termination sequence.
  1336. *
  1337. * If you write to a socket output stream after invoking
  1338. * shutdownOutput() on the socket, the stream will throw
  1339. * an IOException.
  1340. *
  1341. * @exception IOException if an I/O error occurs when shutting down this
  1342. * socket.
  1343. *
  1344. * @since 1.3
  1345. * @see java.net.Socket#shutdownInput()
  1346. * @see java.net.Socket#close()
  1347. * @see java.net.Socket#setSoLinger(boolean, int)
  1348. * @see #isOutputShutdown
  1349. */
  1350. public void shutdownOutput() throws IOException
  1351. {
  1352. if (isClosed())
  1353. throw new SocketException("Socket is closed");
  1354. if (!isConnected())
  1355. throw new SocketException("Socket is not connected");
  1356. if (isOutputShutdown())
  1357. throw new SocketException("Socket output is already shutdown");
  1358. getImpl().shutdownOutput();
  1359. shutOut = true;
  1360. }
  1361. /**
  1362. * Converts this socket to a <code>String</code>.
  1363. *
  1364. * @return a string representation of this socket.
  1365. */
  1366. public String toString() {
  1367. try {
  1368. if (isConnected())
  1369. return "Socket[addr=" + getImpl().getInetAddress() +
  1370. ",port=" + getImpl().getPort() +
  1371. ",localport=" + getImpl().getLocalPort() + "]";
  1372. } catch (SocketException e) {
  1373. }
  1374. return "Socket[unconnected]";
  1375. }
  1376. /**
  1377. * Returns the connection state of the socket.
  1378. *
  1379. * @return true if the socket successfuly connected to a server
  1380. * @since 1.4
  1381. */
  1382. public boolean isConnected() {
  1383. // Before 1.3 Sockets were always connected during creation
  1384. return connected || oldImpl;
  1385. }
  1386. /**
  1387. * Returns the binding state of the socket.
  1388. *
  1389. * @return true if the socket successfuly bound to an address
  1390. * @since 1.4
  1391. * @see #bind
  1392. */
  1393. public boolean isBound() {
  1394. // Before 1.3 Sockets were always bound during creation
  1395. return bound || oldImpl;
  1396. }
  1397. /**
  1398. * Returns the closed state of the socket.
  1399. *
  1400. * @return true if the socket has been closed
  1401. * @since 1.4
  1402. * @see #close
  1403. */
  1404. public boolean isClosed() {
  1405. synchronized(closeLock) {
  1406. return closed;
  1407. }
  1408. }
  1409. /**
  1410. * Returns whether the read-half of the socket connection is closed.
  1411. *
  1412. * @return true if the input of the socket has been shutdown
  1413. * @since 1.4
  1414. * @see #shutdownInput
  1415. */
  1416. public boolean isInputShutdown() {
  1417. return shutIn;
  1418. }
  1419. /**
  1420. * Returns whether the write-half of the socket connection is closed.
  1421. *
  1422. * @return true if the output of the socket has been shutdown
  1423. * @since 1.4
  1424. * @see #shutdownOutput
  1425. */
  1426. public boolean isOutputShutdown() {
  1427. return shutOut;
  1428. }
  1429. /**
  1430. * The factory for all client sockets.
  1431. */
  1432. private static SocketImplFactory factory = null;
  1433. /**
  1434. * Sets the client socket implementation factory for the
  1435. * application. The factory can be specified only once.
  1436. * <p>
  1437. * When an application creates a new client socket, the socket
  1438. * implementation factory's <code>createSocketImpl</code> method is
  1439. * called to create the actual socket implementation.
  1440. * <p>
  1441. * Passing <code>null</code> to the method is a no-op unless the factory
  1442. * was already set.
  1443. * <p>If there is a security manager, this method first calls
  1444. * the security manager's <code>checkSetFactory</code> method
  1445. * to ensure the operation is allowed.
  1446. * This could result in a SecurityException.
  1447. *
  1448. * @param fac the desired factory.
  1449. * @exception IOException if an I/O error occurs when setting the
  1450. * socket factory.
  1451. * @exception SocketException if the factory is already defined.
  1452. * @exception SecurityException if a security manager exists and its
  1453. * <code>checkSetFactory</code> method doesn't allow the operation.
  1454. * @see java.net.SocketImplFactory#createSocketImpl()
  1455. * @see SecurityManager#checkSetFactory
  1456. */
  1457. public static synchronized void setSocketImplFactory(SocketImplFactory fac)
  1458. throws IOException
  1459. {
  1460. if (factory != null) {
  1461. throw new SocketException("factory already defined");
  1462. }
  1463. SecurityManager security = System.getSecurityManager();
  1464. if (security != null) {
  1465. security.checkSetFactory();
  1466. }
  1467. factory = fac;
  1468. }
  1469. /**
  1470. * Sets performance preferences for this socket.
  1471. *
  1472. * <p> Sockets use the TCP/IP protocol by default. Some implementations
  1473. * may offer alternative protocols which have different performance
  1474. * characteristics than TCP/IP. This method allows the application to
  1475. * express its own preferences as to how these tradeoffs should be made
  1476. * when the implementation chooses from the available protocols.
  1477. *
  1478. * <p> Performance preferences are described by three integers
  1479. * whose values indicate the relative importance of short connection time,
  1480. * low latency, and high bandwidth. The absolute values of the integers
  1481. * are irrelevant; in order to choose a protocol the values are simply
  1482. * compared, with larger values indicating stronger preferences. Negative
  1483. * values represent a lower priority than positive values. If the
  1484. * application prefers short connection time over both low latency and high
  1485. * bandwidth, for example, then it could invoke this method with the values
  1486. * <tt>(1, 0, 0)</tt>. If the application prefers high bandwidth above low
  1487. * latency, and low latency above short connection time, then it could
  1488. * invoke this method with the values <tt>(0, 1, 2)</tt>.
  1489. *
  1490. * <p> Invoking this method after this socket has been connected
  1491. * will have no effect.
  1492. *
  1493. * @param connectionTime
  1494. * An <tt>int</tt> expressing the relative importance of a short
  1495. * connection time
  1496. *
  1497. * @param latency
  1498. * An <tt>int</tt> expressing the relative importance of low
  1499. * latency
  1500. *
  1501. * @param bandwidth
  1502. * An <tt>int</tt> expressing the relative importance of high
  1503. * bandwidth
  1504. *
  1505. * @since 1.5
  1506. */
  1507. public void setPerformancePreferences(int connectionTime,
  1508. int latency,
  1509. int bandwidth)
  1510. {
  1511. /* Not implemented yet */
  1512. }
  1513. }