1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 use io::{self, Initializer};
15 use net::{ToSocketAddrs, SocketAddr, Shutdown};
16 use sys_common::net as net_imp;
17 use sys_common::{AsInner, FromInner, IntoInner};
20 /// A TCP stream between a local and a remote socket.
22 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
23 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
24 /// by [reading] and [writing] to it.
26 /// The connection will be closed when the value is dropped. The reading and writing
27 /// portions of the connection can also be shut down individually with the [`shutdown`]
30 /// The Transmission Control Protocol is specified in [IETF RFC 793].
32 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
33 /// [`connect`]: #method.connect
34 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
35 /// [reading]: ../../std/io/trait.Read.html
36 /// [`shutdown`]: #method.shutdown
37 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
38 /// [writing]: ../../std/io/trait.Write.html
43 /// use std::io::prelude::*;
44 /// use std::net::TcpStream;
47 /// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
49 /// // ignore the Result
50 /// let _ = stream.write(&[1]);
51 /// let _ = stream.read(&mut [0; 128]); // ignore here too
52 /// } // the stream is closed here
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub struct TcpStream(net_imp::TcpStream);
57 /// A TCP socket server, listening for connections.
59 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
60 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
61 /// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
63 /// The socket will be closed when the value is dropped.
65 /// The Transmission Control Protocol is specified in [IETF RFC 793].
67 /// [`accept`]: #method.accept
68 /// [`bind`]: #method.bind
69 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
70 /// [`Incoming`]: ../../std/net/struct.Incoming.html
71 /// [`TcpListener::incoming`]: #method.incoming
77 /// use std::net::{TcpListener, TcpStream};
79 /// fn handle_client(stream: TcpStream) {
83 /// # fn process() -> io::Result<()> {
84 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
86 /// // accept connections and process them serially
87 /// for stream in listener.incoming() {
88 /// handle_client(stream?);
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub struct TcpListener(net_imp::TcpListener);
96 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
98 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
99 /// See its documentation for more.
101 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
102 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
103 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
104 #[stable(feature = "rust1", since = "1.0.0")]
106 pub struct Incoming<'a> { listener: &'a TcpListener }
109 /// Opens a TCP connection to a remote host.
111 /// `addr` is an address of the remote host. Anything which implements
112 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
113 /// documentation for concrete examples.
115 /// If `addr` yields multiple addresses, `connect` will be attempted with
116 /// each of the addresses until a connection is successful. If none of
117 /// the addresses result in a successful connection, the error returned from
118 /// the last connection attempt (the last address) is returned.
120 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
124 /// Open a TCP connection to `127.0.0.1:8080`:
127 /// use std::net::TcpStream;
129 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
130 /// println!("Connected to the server!");
132 /// println!("Couldn't connect to server...");
136 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
137 /// a TCP connection to `127.0.0.1:8081`:
140 /// use std::net::{SocketAddr, TcpStream};
143 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
144 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
146 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
147 /// println!("Connected to the server!");
149 /// println!("Couldn't connect to server...");
152 #[stable(feature = "rust1", since = "1.0.0")]
153 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
154 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
157 /// Opens a TCP connection to a remote host with a timeout.
159 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
160 /// timeout must be applied to individual addresses.
162 /// It is an error to pass a zero `Duration` to this function.
164 /// Unlike other methods on `TcpStream`, this does not correspond to a
165 /// single system call. It instead calls `connect` in nonblocking mode and
166 /// then uses an OS-specific mechanism to await the completion of the
167 /// connection request.
169 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
170 #[stable(feature = "tcpstream_connect_timeout", since = "1.22.0")]
171 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
172 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
175 /// Returns the socket address of the remote peer of this TCP connection.
180 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
182 /// let stream = TcpStream::connect("127.0.0.1:8080")
183 /// .expect("Couldn't connect to the server...");
184 /// assert_eq!(stream.peer_addr().unwrap(),
185 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
192 /// Returns the socket address of the local half of this TCP connection.
197 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
199 /// let stream = TcpStream::connect("127.0.0.1:8080")
200 /// .expect("Couldn't connect to the server...");
201 /// assert_eq!(stream.local_addr().unwrap(),
202 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn local_addr(&self) -> io::Result<SocketAddr> {
209 /// Shuts down the read, write, or both halves of this connection.
211 /// This function will cause all pending and future I/O on the specified
212 /// portions to return immediately with an appropriate value (see the
213 /// documentation of [`Shutdown`]).
215 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
217 /// # Platform-specific behavior
219 /// Calling this function multiple times may result in different behavior,
220 /// depending on the operating system. On Linux, the second call will
221 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
222 /// This may change in the future.
227 /// use std::net::{Shutdown, TcpStream};
229 /// let stream = TcpStream::connect("127.0.0.1:8080")
230 /// .expect("Couldn't connect to the server...");
231 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
233 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
238 /// Creates a new independently owned handle to the underlying socket.
240 /// The returned `TcpStream` is a reference to the same stream that this
241 /// object references. Both handles will read and write the same stream of
242 /// data, and options set on one stream will be propagated to the other
248 /// use std::net::TcpStream;
250 /// let stream = TcpStream::connect("127.0.0.1:8080")
251 /// .expect("Couldn't connect to the server...");
252 /// let stream_clone = stream.try_clone().expect("clone failed...");
254 #[stable(feature = "rust1", since = "1.0.0")]
255 pub fn try_clone(&self) -> io::Result<TcpStream> {
256 self.0.duplicate().map(TcpStream)
259 /// Sets the read timeout to the timeout specified.
261 /// If the value specified is [`None`], then [`read`] calls will block
262 /// indefinitely. It is an error to pass the zero `Duration` to this
267 /// Platforms may return a different error code whenever a read times out as
268 /// a result of setting this option. For example Unix typically returns an
269 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
271 /// [`None`]: ../../std/option/enum.Option.html#variant.None
272 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
273 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
274 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
279 /// use std::net::TcpStream;
281 /// let stream = TcpStream::connect("127.0.0.1:8080")
282 /// .expect("Couldn't connect to the server...");
283 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
285 #[stable(feature = "socket_timeout", since = "1.4.0")]
286 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
287 self.0.set_read_timeout(dur)
290 /// Sets the write timeout to the timeout specified.
292 /// If the value specified is [`None`], then [`write`] calls will block
293 /// indefinitely. It is an error to pass the zero [`Duration`] to this
298 /// Platforms may return a different error code whenever a write times out
299 /// as a result of setting this option. For example Unix typically returns
300 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
302 /// [`None`]: ../../std/option/enum.Option.html#variant.None
303 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
304 /// [`Duration`]: ../../std/time/struct.Duration.html
305 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
306 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
311 /// use std::net::TcpStream;
313 /// let stream = TcpStream::connect("127.0.0.1:8080")
314 /// .expect("Couldn't connect to the server...");
315 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
317 #[stable(feature = "socket_timeout", since = "1.4.0")]
318 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
319 self.0.set_write_timeout(dur)
322 /// Returns the read timeout of this socket.
324 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
328 /// Some platforms do not provide access to the current timeout.
330 /// [`None`]: ../../std/option/enum.Option.html#variant.None
331 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
336 /// use std::net::TcpStream;
338 /// let stream = TcpStream::connect("127.0.0.1:8080")
339 /// .expect("Couldn't connect to the server...");
340 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
341 /// assert_eq!(stream.read_timeout().unwrap(), None);
343 #[stable(feature = "socket_timeout", since = "1.4.0")]
344 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
345 self.0.read_timeout()
348 /// Returns the write timeout of this socket.
350 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
354 /// Some platforms do not provide access to the current timeout.
356 /// [`None`]: ../../std/option/enum.Option.html#variant.None
357 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
362 /// use std::net::TcpStream;
364 /// let stream = TcpStream::connect("127.0.0.1:8080")
365 /// .expect("Couldn't connect to the server...");
366 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
367 /// assert_eq!(stream.write_timeout().unwrap(), None);
369 #[stable(feature = "socket_timeout", since = "1.4.0")]
370 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
371 self.0.write_timeout()
374 /// Receives data on the socket from the remote address to which it is
375 /// connected, without removing that data from the queue. On success,
376 /// returns the number of bytes peeked.
378 /// Successive calls return the same data. This is accomplished by passing
379 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
384 /// use std::net::TcpStream;
386 /// let stream = TcpStream::connect("127.0.0.1:8000")
387 /// .expect("couldn't bind to address");
388 /// let mut buf = [0; 10];
389 /// let len = stream.peek(&mut buf).expect("peek failed");
391 #[stable(feature = "peek", since = "1.18.0")]
392 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
396 /// Sets the value of the `TCP_NODELAY` option on this socket.
398 /// If set, this option disables the Nagle algorithm. This means that
399 /// segments are always sent as soon as possible, even if there is only a
400 /// small amount of data. When not set, data is buffered until there is a
401 /// sufficient amount to send out, thereby avoiding the frequent sending of
407 /// use std::net::TcpStream;
409 /// let stream = TcpStream::connect("127.0.0.1:8080")
410 /// .expect("Couldn't connect to the server...");
411 /// stream.set_nodelay(true).expect("set_nodelay call failed");
413 #[stable(feature = "net2_mutators", since = "1.9.0")]
414 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
415 self.0.set_nodelay(nodelay)
418 /// Gets the value of the `TCP_NODELAY` option on this socket.
420 /// For more information about this option, see [`set_nodelay`][link].
422 /// [link]: #method.set_nodelay
427 /// use std::net::TcpStream;
429 /// let stream = TcpStream::connect("127.0.0.1:8080")
430 /// .expect("Couldn't connect to the server...");
431 /// stream.set_nodelay(true).expect("set_nodelay call failed");
432 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
434 #[stable(feature = "net2_mutators", since = "1.9.0")]
435 pub fn nodelay(&self) -> io::Result<bool> {
439 /// Sets the value for the `IP_TTL` option on this socket.
441 /// This value sets the time-to-live field that is used in every packet sent
442 /// from this socket.
447 /// use std::net::TcpStream;
449 /// let stream = TcpStream::connect("127.0.0.1:8080")
450 /// .expect("Couldn't connect to the server...");
451 /// stream.set_ttl(100).expect("set_ttl call failed");
453 #[stable(feature = "net2_mutators", since = "1.9.0")]
454 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
458 /// Gets the value of the `IP_TTL` option for this socket.
460 /// For more information about this option, see [`set_ttl`][link].
462 /// [link]: #method.set_ttl
467 /// use std::net::TcpStream;
469 /// let stream = TcpStream::connect("127.0.0.1:8080")
470 /// .expect("Couldn't connect to the server...");
471 /// stream.set_ttl(100).expect("set_ttl call failed");
472 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
474 #[stable(feature = "net2_mutators", since = "1.9.0")]
475 pub fn ttl(&self) -> io::Result<u32> {
479 /// Get the value of the `SO_ERROR` option on this socket.
481 /// This will retrieve the stored error in the underlying socket, clearing
482 /// the field in the process. This can be useful for checking errors between
488 /// use std::net::TcpStream;
490 /// let stream = TcpStream::connect("127.0.0.1:8080")
491 /// .expect("Couldn't connect to the server...");
492 /// stream.take_error().expect("No error was expected...");
494 #[stable(feature = "net2_mutators", since = "1.9.0")]
495 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
499 /// Moves this TCP stream into or out of nonblocking mode.
501 /// On Unix this corresponds to calling fcntl, and on Windows this
502 /// corresponds to calling ioctlsocket.
507 /// use std::net::TcpStream;
509 /// let stream = TcpStream::connect("127.0.0.1:8080")
510 /// .expect("Couldn't connect to the server...");
511 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
513 #[stable(feature = "net2_mutators", since = "1.9.0")]
514 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
515 self.0.set_nonblocking(nonblocking)
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl Read for TcpStream {
521 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
524 unsafe fn initializer(&self) -> Initializer {
528 #[stable(feature = "rust1", since = "1.0.0")]
529 impl Write for TcpStream {
530 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
531 fn flush(&mut self) -> io::Result<()> { Ok(()) }
533 #[stable(feature = "rust1", since = "1.0.0")]
534 impl<'a> Read for &'a TcpStream {
535 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
538 unsafe fn initializer(&self) -> Initializer {
542 #[stable(feature = "rust1", since = "1.0.0")]
543 impl<'a> Write for &'a TcpStream {
544 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
545 fn flush(&mut self) -> io::Result<()> { Ok(()) }
548 impl AsInner<net_imp::TcpStream> for TcpStream {
549 fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
552 impl FromInner<net_imp::TcpStream> for TcpStream {
553 fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
556 impl IntoInner<net_imp::TcpStream> for TcpStream {
557 fn into_inner(self) -> net_imp::TcpStream { self.0 }
560 #[stable(feature = "rust1", since = "1.0.0")]
561 impl fmt::Debug for TcpStream {
562 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
568 /// Creates a new `TcpListener` which will be bound to the specified
571 /// The returned listener is ready for accepting connections.
573 /// Binding with a port number of 0 will request that the OS assigns a port
574 /// to this listener. The port allocated can be queried via the
575 /// [`local_addr`] method.
577 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
578 /// its documentation for concrete examples.
580 /// If `addr` yields multiple addresses, `bind` will be attempted with
581 /// each of the addresses until one succeeds and returns the listener. If
582 /// none of the addresses succeed in creating a listener, the error returned
583 /// from the last attempt (the last address) is returned.
585 /// [`local_addr`]: #method.local_addr
586 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
590 /// Create a TCP listener bound to `127.0.0.1:80`:
593 /// use std::net::TcpListener;
595 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
598 /// Create a TCP listener bound to `127.0.0.1:80`. If that fails, create a
599 /// TCP listener bound to `127.0.0.1:443`:
602 /// use std::net::{SocketAddr, TcpListener};
605 /// SocketAddr::from(([127, 0, 0, 1], 80)),
606 /// SocketAddr::from(([127, 0, 0, 1], 443)),
608 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
610 #[stable(feature = "rust1", since = "1.0.0")]
611 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
612 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
615 /// Returns the local socket address of this listener.
620 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
622 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
623 /// assert_eq!(listener.local_addr().unwrap(),
624 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn local_addr(&self) -> io::Result<SocketAddr> {
631 /// Creates a new independently owned handle to the underlying socket.
633 /// The returned [`TcpListener`] is a reference to the same socket that this
634 /// object references. Both handles can be used to accept incoming
635 /// connections and options set on one listener will affect the other.
637 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
642 /// use std::net::TcpListener;
644 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
645 /// let listener_clone = listener.try_clone().unwrap();
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn try_clone(&self) -> io::Result<TcpListener> {
649 self.0.duplicate().map(TcpListener)
652 /// Accept a new incoming connection from this listener.
654 /// This function will block the calling thread until a new TCP connection
655 /// is established. When established, the corresponding [`TcpStream`] and the
656 /// remote peer's address will be returned.
658 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
663 /// use std::net::TcpListener;
665 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
666 /// match listener.accept() {
667 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
668 /// Err(e) => println!("couldn't get client: {:?}", e),
671 #[stable(feature = "rust1", since = "1.0.0")]
672 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
673 self.0.accept().map(|(a, b)| (TcpStream(a), b))
676 /// Returns an iterator over the connections being received on this
679 /// The returned iterator will never return [`None`] and will also not yield
680 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
681 /// calling [`accept`] in a loop.
683 /// [`None`]: ../../std/option/enum.Option.html#variant.None
684 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
685 /// [`accept`]: #method.accept
690 /// use std::net::TcpListener;
692 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
694 /// for stream in listener.incoming() {
697 /// println!("new client!");
699 /// Err(e) => { /* connection failed */ }
703 #[stable(feature = "rust1", since = "1.0.0")]
704 pub fn incoming(&self) -> Incoming {
705 Incoming { listener: self }
708 /// Sets the value for the `IP_TTL` option on this socket.
710 /// This value sets the time-to-live field that is used in every packet sent
711 /// from this socket.
716 /// use std::net::TcpListener;
718 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
719 /// listener.set_ttl(100).expect("could not set TTL");
721 #[stable(feature = "net2_mutators", since = "1.9.0")]
722 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
726 /// Gets the value of the `IP_TTL` option for this socket.
728 /// For more information about this option, see [`set_ttl`][link].
730 /// [link]: #method.set_ttl
735 /// use std::net::TcpListener;
737 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
738 /// listener.set_ttl(100).expect("could not set TTL");
739 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
741 #[stable(feature = "net2_mutators", since = "1.9.0")]
742 pub fn ttl(&self) -> io::Result<u32> {
746 #[stable(feature = "net2_mutators", since = "1.9.0")]
747 #[rustc_deprecated(since = "1.16.0",
748 reason = "this option can only be set before the socket is bound")]
749 #[allow(missing_docs)]
750 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
751 self.0.set_only_v6(only_v6)
754 #[stable(feature = "net2_mutators", since = "1.9.0")]
755 #[rustc_deprecated(since = "1.16.0",
756 reason = "this option can only be set before the socket is bound")]
757 #[allow(missing_docs)]
758 pub fn only_v6(&self) -> io::Result<bool> {
762 /// Get the value of the `SO_ERROR` option on this socket.
764 /// This will retrieve the stored error in the underlying socket, clearing
765 /// the field in the process. This can be useful for checking errors between
771 /// use std::net::TcpListener;
773 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
774 /// listener.take_error().expect("No error was expected");
776 #[stable(feature = "net2_mutators", since = "1.9.0")]
777 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
781 /// Moves this TCP stream into or out of nonblocking mode.
783 /// On Unix this corresponds to calling fcntl, and on Windows this
784 /// corresponds to calling ioctlsocket.
789 /// use std::net::TcpListener;
791 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
792 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
794 #[stable(feature = "net2_mutators", since = "1.9.0")]
795 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
796 self.0.set_nonblocking(nonblocking)
800 #[stable(feature = "rust1", since = "1.0.0")]
801 impl<'a> Iterator for Incoming<'a> {
802 type Item = io::Result<TcpStream>;
803 fn next(&mut self) -> Option<io::Result<TcpStream>> {
804 Some(self.listener.accept().map(|p| p.0))
808 impl AsInner<net_imp::TcpListener> for TcpListener {
809 fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
812 impl FromInner<net_imp::TcpListener> for TcpListener {
813 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
818 impl IntoInner<net_imp::TcpListener> for TcpListener {
819 fn into_inner(self) -> net_imp::TcpListener { self.0 }
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl fmt::Debug for TcpListener {
824 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
829 #[cfg(all(test, not(target_os = "emscripten")))]
834 use net::test::{next_test_ip4, next_test_ip6};
835 use sync::mpsc::channel;
836 use sys_common::AsInner;
837 use time::{Instant, Duration};
840 fn each_ip(f: &mut FnMut(SocketAddr)) {
849 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
856 match TcpListener::bind("1.1.1.1:9999") {
859 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
865 match TcpStream::connect("0.0.0.0:1") {
867 Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
868 e.kind() == ErrorKind::InvalidInput ||
869 e.kind() == ErrorKind::AddrInUse ||
870 e.kind() == ErrorKind::AddrNotAvailable,
871 "bad error: {} {:?}", e, e.kind()),
876 fn listen_localhost() {
877 let socket_addr = next_test_ip4();
878 let listener = t!(TcpListener::bind(&socket_addr));
880 let _t = thread::spawn(move || {
881 let mut stream = t!(TcpStream::connect(&("localhost",
882 socket_addr.port())));
883 t!(stream.write(&[144]));
886 let mut stream = t!(listener.accept()).0;
888 t!(stream.read(&mut buf));
889 assert!(buf[0] == 144);
893 fn connect_loopback() {
894 each_ip(&mut |addr| {
895 let acceptor = t!(TcpListener::bind(&addr));
897 let _t = thread::spawn(move|| {
898 let host = match addr {
899 SocketAddr::V4(..) => "127.0.0.1",
900 SocketAddr::V6(..) => "::1",
902 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
903 t!(stream.write(&[66]));
906 let mut stream = t!(acceptor.accept()).0;
908 t!(stream.read(&mut buf));
909 assert!(buf[0] == 66);
915 each_ip(&mut |addr| {
916 let acceptor = t!(TcpListener::bind(&addr));
918 let (tx, rx) = channel();
919 let _t = thread::spawn(move|| {
920 let mut stream = t!(TcpStream::connect(&addr));
921 t!(stream.write(&[99]));
922 tx.send(t!(stream.local_addr())).unwrap();
925 let (mut stream, addr) = t!(acceptor.accept());
927 t!(stream.read(&mut buf));
928 assert!(buf[0] == 99);
929 assert_eq!(addr, t!(rx.recv()));
935 each_ip(&mut |addr| {
936 let acceptor = t!(TcpListener::bind(&addr));
938 let _t = thread::spawn(move|| {
939 let _stream = t!(TcpStream::connect(&addr));
943 let mut stream = t!(acceptor.accept()).0;
945 let nread = t!(stream.read(&mut buf));
946 assert_eq!(nread, 0);
947 let nread = t!(stream.read(&mut buf));
948 assert_eq!(nread, 0);
954 each_ip(&mut |addr| {
955 let acceptor = t!(TcpListener::bind(&addr));
957 let (tx, rx) = channel();
958 let _t = thread::spawn(move|| {
959 drop(t!(TcpStream::connect(&addr)));
960 tx.send(()).unwrap();
963 let mut stream = t!(acceptor.accept()).0;
966 match stream.write(&buf) {
969 assert!(e.kind() == ErrorKind::ConnectionReset ||
970 e.kind() == ErrorKind::BrokenPipe ||
971 e.kind() == ErrorKind::ConnectionAborted,
972 "unknown error: {}", e);
979 fn multiple_connect_serial() {
980 each_ip(&mut |addr| {
982 let acceptor = t!(TcpListener::bind(&addr));
984 let _t = thread::spawn(move|| {
986 let mut stream = t!(TcpStream::connect(&addr));
987 t!(stream.write(&[99]));
991 for stream in acceptor.incoming().take(max) {
992 let mut stream = t!(stream);
994 t!(stream.read(&mut buf));
995 assert_eq!(buf[0], 99);
1001 fn multiple_connect_interleaved_greedy_schedule() {
1002 const MAX: usize = 10;
1003 each_ip(&mut |addr| {
1004 let acceptor = t!(TcpListener::bind(&addr));
1006 let _t = thread::spawn(move|| {
1007 let acceptor = acceptor;
1008 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
1009 // Start another thread to handle the connection
1010 let _t = thread::spawn(move|| {
1011 let mut stream = t!(stream);
1013 t!(stream.read(&mut buf));
1014 assert!(buf[0] == i as u8);
1022 fn connect(i: usize, addr: SocketAddr) {
1023 if i == MAX { return }
1025 let t = thread::spawn(move|| {
1026 let mut stream = t!(TcpStream::connect(&addr));
1027 // Connect again before writing
1028 connect(i + 1, addr);
1029 t!(stream.write(&[i as u8]));
1031 t.join().ok().unwrap();
1036 fn multiple_connect_interleaved_lazy_schedule() {
1037 const MAX: usize = 10;
1038 each_ip(&mut |addr| {
1039 let acceptor = t!(TcpListener::bind(&addr));
1041 let _t = thread::spawn(move|| {
1042 for stream in acceptor.incoming().take(MAX) {
1043 // Start another thread to handle the connection
1044 let _t = thread::spawn(move|| {
1045 let mut stream = t!(stream);
1047 t!(stream.read(&mut buf));
1048 assert!(buf[0] == 99);
1056 fn connect(i: usize, addr: SocketAddr) {
1057 if i == MAX { return }
1059 let t = thread::spawn(move|| {
1060 let mut stream = t!(TcpStream::connect(&addr));
1061 connect(i + 1, addr);
1062 t!(stream.write(&[99]));
1064 t.join().ok().unwrap();
1069 fn socket_and_peer_name() {
1070 each_ip(&mut |addr| {
1071 let listener = t!(TcpListener::bind(&addr));
1072 let so_name = t!(listener.local_addr());
1073 assert_eq!(addr, so_name);
1074 let _t = thread::spawn(move|| {
1075 t!(listener.accept());
1078 let stream = t!(TcpStream::connect(&addr));
1079 assert_eq!(addr, t!(stream.peer_addr()));
1085 each_ip(&mut |addr| {
1086 let (tx, rx) = channel();
1087 let srv = t!(TcpListener::bind(&addr));
1088 let _t = thread::spawn(move|| {
1089 let mut cl = t!(srv.accept()).0;
1090 cl.write(&[10]).unwrap();
1092 t!(cl.read(&mut b));
1093 tx.send(()).unwrap();
1096 let mut c = t!(TcpStream::connect(&addr));
1097 let mut b = [0; 10];
1098 assert_eq!(c.read(&mut b).unwrap(), 1);
1106 each_ip(&mut |addr| {
1107 let _listener = t!(TcpListener::bind(&addr));
1108 match TcpListener::bind(&addr) {
1111 assert!(e.kind() == ErrorKind::ConnectionRefused ||
1112 e.kind() == ErrorKind::Other ||
1113 e.kind() == ErrorKind::AddrInUse,
1114 "unknown error: {} {:?}", e, e.kind());
1122 each_ip(&mut |addr| {
1123 let acceptor = t!(TcpListener::bind(&addr));
1125 let _t = thread::spawn(move|| {
1126 t!(TcpStream::connect(&addr));
1129 t!(acceptor.accept());
1131 t!(TcpListener::bind(&addr));
1136 fn tcp_clone_smoke() {
1137 each_ip(&mut |addr| {
1138 let acceptor = t!(TcpListener::bind(&addr));
1140 let _t = thread::spawn(move|| {
1141 let mut s = t!(TcpStream::connect(&addr));
1142 let mut buf = [0, 0];
1143 assert_eq!(s.read(&mut buf).unwrap(), 1);
1144 assert_eq!(buf[0], 1);
1148 let mut s1 = t!(acceptor.accept()).0;
1149 let s2 = t!(s1.try_clone());
1151 let (tx1, rx1) = channel();
1152 let (tx2, rx2) = channel();
1153 let _t = thread::spawn(move|| {
1155 rx1.recv().unwrap();
1157 tx2.send(()).unwrap();
1159 tx1.send(()).unwrap();
1160 let mut buf = [0, 0];
1161 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1162 rx2.recv().unwrap();
1167 fn tcp_clone_two_read() {
1168 each_ip(&mut |addr| {
1169 let acceptor = t!(TcpListener::bind(&addr));
1170 let (tx1, rx) = channel();
1171 let tx2 = tx1.clone();
1173 let _t = thread::spawn(move|| {
1174 let mut s = t!(TcpStream::connect(&addr));
1181 let mut s1 = t!(acceptor.accept()).0;
1182 let s2 = t!(s1.try_clone());
1184 let (done, rx) = channel();
1185 let _t = thread::spawn(move|| {
1187 let mut buf = [0, 0];
1188 t!(s2.read(&mut buf));
1189 tx2.send(()).unwrap();
1190 done.send(()).unwrap();
1192 let mut buf = [0, 0];
1193 t!(s1.read(&mut buf));
1194 tx1.send(()).unwrap();
1201 fn tcp_clone_two_write() {
1202 each_ip(&mut |addr| {
1203 let acceptor = t!(TcpListener::bind(&addr));
1205 let _t = thread::spawn(move|| {
1206 let mut s = t!(TcpStream::connect(&addr));
1207 let mut buf = [0, 1];
1208 t!(s.read(&mut buf));
1209 t!(s.read(&mut buf));
1212 let mut s1 = t!(acceptor.accept()).0;
1213 let s2 = t!(s1.try_clone());
1215 let (done, rx) = channel();
1216 let _t = thread::spawn(move|| {
1219 done.send(()).unwrap();
1228 fn shutdown_smoke() {
1229 each_ip(&mut |addr| {
1230 let a = t!(TcpListener::bind(&addr));
1231 let _t = thread::spawn(move|| {
1232 let mut c = t!(a.accept()).0;
1234 assert_eq!(c.read(&mut b).unwrap(), 0);
1238 let mut s = t!(TcpStream::connect(&addr));
1239 t!(s.shutdown(Shutdown::Write));
1240 assert!(s.write(&[1]).is_err());
1242 assert_eq!(t!(s.read(&mut b)), 1);
1243 assert_eq!(b[0], 1);
1248 fn close_readwrite_smoke() {
1249 each_ip(&mut |addr| {
1250 let a = t!(TcpListener::bind(&addr));
1251 let (tx, rx) = channel::<()>();
1252 let _t = thread::spawn(move|| {
1253 let _s = t!(a.accept());
1258 let mut s = t!(TcpStream::connect(&addr));
1259 let mut s2 = t!(s.try_clone());
1261 // closing should prevent reads/writes
1262 t!(s.shutdown(Shutdown::Write));
1263 assert!(s.write(&[0]).is_err());
1264 t!(s.shutdown(Shutdown::Read));
1265 assert_eq!(s.read(&mut b).unwrap(), 0);
1267 // closing should affect previous handles
1268 assert!(s2.write(&[0]).is_err());
1269 assert_eq!(s2.read(&mut b).unwrap(), 0);
1271 // closing should affect new handles
1272 let mut s3 = t!(s.try_clone());
1273 assert!(s3.write(&[0]).is_err());
1274 assert_eq!(s3.read(&mut b).unwrap(), 0);
1276 // make sure these don't die
1277 let _ = s2.shutdown(Shutdown::Read);
1278 let _ = s2.shutdown(Shutdown::Write);
1279 let _ = s3.shutdown(Shutdown::Read);
1280 let _ = s3.shutdown(Shutdown::Write);
1286 #[cfg(unix)] // test doesn't work on Windows, see #31657
1287 fn close_read_wakes_up() {
1288 each_ip(&mut |addr| {
1289 let a = t!(TcpListener::bind(&addr));
1290 let (tx1, rx) = channel::<()>();
1291 let _t = thread::spawn(move|| {
1292 let _s = t!(a.accept());
1296 let s = t!(TcpStream::connect(&addr));
1297 let s2 = t!(s.try_clone());
1298 let (tx, rx) = channel();
1299 let _t = thread::spawn(move|| {
1301 assert_eq!(t!(s2.read(&mut [0])), 0);
1302 tx.send(()).unwrap();
1304 // this should wake up the child thread
1305 t!(s.shutdown(Shutdown::Read));
1307 // this test will never finish if the child doesn't wake up
1314 fn clone_while_reading() {
1315 each_ip(&mut |addr| {
1316 let accept = t!(TcpListener::bind(&addr));
1318 // Enqueue a thread to write to a socket
1319 let (tx, rx) = channel();
1320 let (txdone, rxdone) = channel();
1321 let txdone2 = txdone.clone();
1322 let _t = thread::spawn(move|| {
1323 let mut tcp = t!(TcpStream::connect(&addr));
1325 t!(tcp.write(&[0]));
1326 txdone2.send(()).unwrap();
1329 // Spawn off a reading clone
1330 let tcp = t!(accept.accept()).0;
1331 let tcp2 = t!(tcp.try_clone());
1332 let txdone3 = txdone.clone();
1333 let _t = thread::spawn(move|| {
1334 let mut tcp2 = tcp2;
1335 t!(tcp2.read(&mut [0]));
1336 txdone3.send(()).unwrap();
1339 // Try to ensure that the reading clone is indeed reading
1341 thread::yield_now();
1344 // clone the handle again while it's reading, then let it finish the
1346 let _ = t!(tcp.try_clone());
1347 tx.send(()).unwrap();
1348 rxdone.recv().unwrap();
1349 rxdone.recv().unwrap();
1354 fn clone_accept_smoke() {
1355 each_ip(&mut |addr| {
1356 let a = t!(TcpListener::bind(&addr));
1357 let a2 = t!(a.try_clone());
1359 let _t = thread::spawn(move|| {
1360 let _ = TcpStream::connect(&addr);
1362 let _t = thread::spawn(move|| {
1363 let _ = TcpStream::connect(&addr);
1372 fn clone_accept_concurrent() {
1373 each_ip(&mut |addr| {
1374 let a = t!(TcpListener::bind(&addr));
1375 let a2 = t!(a.try_clone());
1377 let (tx, rx) = channel();
1378 let tx2 = tx.clone();
1380 let _t = thread::spawn(move|| {
1381 tx.send(t!(a.accept())).unwrap();
1383 let _t = thread::spawn(move|| {
1384 tx2.send(t!(a2.accept())).unwrap();
1387 let _t = thread::spawn(move|| {
1388 let _ = TcpStream::connect(&addr);
1390 let _t = thread::spawn(move|| {
1391 let _ = TcpStream::connect(&addr);
1401 let name = if cfg!(windows) {"socket"} else {"fd"};
1402 let socket_addr = next_test_ip4();
1404 let listener = t!(TcpListener::bind(&socket_addr));
1405 let listener_inner = listener.0.socket().as_inner();
1406 let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
1407 socket_addr, name, listener_inner);
1408 assert_eq!(format!("{:?}", listener), compare);
1410 let stream = t!(TcpStream::connect(&("localhost",
1411 socket_addr.port())));
1412 let stream_inner = stream.0.socket().as_inner();
1413 let compare = format!("TcpStream {{ addr: {:?}, \
1414 peer: {:?}, {}: {:?} }}",
1415 stream.local_addr().unwrap(),
1416 stream.peer_addr().unwrap(),
1419 assert_eq!(format!("{:?}", stream), compare);
1422 // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
1423 // no longer has rounding errors.
1424 #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1427 let addr = next_test_ip4();
1428 let listener = t!(TcpListener::bind(&addr));
1430 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1431 let dur = Duration::new(15410, 0);
1433 assert_eq!(None, t!(stream.read_timeout()));
1435 t!(stream.set_read_timeout(Some(dur)));
1436 assert_eq!(Some(dur), t!(stream.read_timeout()));
1438 assert_eq!(None, t!(stream.write_timeout()));
1440 t!(stream.set_write_timeout(Some(dur)));
1441 assert_eq!(Some(dur), t!(stream.write_timeout()));
1443 t!(stream.set_read_timeout(None));
1444 assert_eq!(None, t!(stream.read_timeout()));
1446 t!(stream.set_write_timeout(None));
1447 assert_eq!(None, t!(stream.write_timeout()));
1452 fn test_read_timeout() {
1453 let addr = next_test_ip4();
1454 let listener = t!(TcpListener::bind(&addr));
1456 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1457 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1459 let mut buf = [0; 10];
1460 let start = Instant::now();
1461 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1462 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1463 assert!(start.elapsed() > Duration::from_millis(400));
1468 fn test_read_with_timeout() {
1469 let addr = next_test_ip4();
1470 let listener = t!(TcpListener::bind(&addr));
1472 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1473 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1475 let mut other_end = t!(listener.accept()).0;
1476 t!(other_end.write_all(b"hello world"));
1478 let mut buf = [0; 11];
1479 t!(stream.read(&mut buf));
1480 assert_eq!(b"hello world", &buf[..]);
1482 let start = Instant::now();
1483 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1484 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1485 assert!(start.elapsed() > Duration::from_millis(400));
1491 let addr = next_test_ip4();
1492 let _listener = t!(TcpListener::bind(&addr));
1494 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1496 assert_eq!(false, t!(stream.nodelay()));
1497 t!(stream.set_nodelay(true));
1498 assert_eq!(true, t!(stream.nodelay()));
1499 t!(stream.set_nodelay(false));
1500 assert_eq!(false, t!(stream.nodelay()));
1507 let addr = next_test_ip4();
1508 let listener = t!(TcpListener::bind(&addr));
1510 t!(listener.set_ttl(ttl));
1511 assert_eq!(ttl, t!(listener.ttl()));
1513 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1515 t!(stream.set_ttl(ttl));
1516 assert_eq!(ttl, t!(stream.ttl()));
1520 fn set_nonblocking() {
1521 let addr = next_test_ip4();
1522 let listener = t!(TcpListener::bind(&addr));
1524 t!(listener.set_nonblocking(true));
1525 t!(listener.set_nonblocking(false));
1527 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1529 t!(stream.set_nonblocking(false));
1530 t!(stream.set_nonblocking(true));
1533 match stream.read(&mut buf) {
1534 Ok(_) => panic!("expected error"),
1535 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1536 Err(e) => panic!("unexpected error {}", e),
1542 each_ip(&mut |addr| {
1543 let (txdone, rxdone) = channel();
1545 let srv = t!(TcpListener::bind(&addr));
1546 let _t = thread::spawn(move|| {
1547 let mut cl = t!(srv.accept()).0;
1548 cl.write(&[1,3,3,7]).unwrap();
1552 let mut c = t!(TcpStream::connect(&addr));
1553 let mut b = [0; 10];
1555 let len = c.peek(&mut b).unwrap();
1558 let len = c.read(&mut b).unwrap();
1561 t!(c.set_nonblocking(true));
1562 match c.peek(&mut b) {
1563 Ok(_) => panic!("expected error"),
1564 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1565 Err(e) => panic!("unexpected error {}", e),
1567 t!(txdone.send(()));
1572 fn connect_timeout_unroutable() {
1573 // this IP is unroutable, so connections should always time out.
1574 let addr = "10.255.255.1:80".parse().unwrap();
1575 let e = TcpStream::connect_timeout(&addr, Duration::from_millis(250)).unwrap_err();
1576 assert_eq!(e.kind(), io::ErrorKind::TimedOut);
1580 fn connect_timeout_valid() {
1581 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1582 let addr = listener.local_addr().unwrap();
1583 TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();