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