1 use crate::io::prelude::*;
4 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
5 use crate::net::{Shutdown, SocketAddr, ToSocketAddrs};
6 use crate::sys_common::net as net_imp;
7 use crate::sys_common::{AsInner, FromInner, IntoInner};
8 use crate::time::Duration;
10 /// A TCP stream between a local and a remote socket.
12 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
13 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
14 /// by [reading] and [writing] to it.
16 /// The connection will be closed when the value is dropped. The reading and writing
17 /// portions of the connection can also be shut down individually with the [`shutdown`]
20 /// The Transmission Control Protocol is specified in [IETF RFC 793].
22 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
23 /// [`connect`]: #method.connect
24 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
25 /// [reading]: ../../std/io/trait.Read.html
26 /// [`shutdown`]: #method.shutdown
27 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
28 /// [writing]: ../../std/io/trait.Write.html
33 /// use std::io::prelude::*;
34 /// use std::net::TcpStream;
36 /// fn main() -> std::io::Result<()> {
37 /// let mut stream = TcpStream::connect("127.0.0.1:34254")?;
39 /// stream.write(&[1])?;
40 /// stream.read(&mut [0; 128])?;
42 /// } // the stream is closed here
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub struct TcpStream(net_imp::TcpStream);
47 /// A TCP socket server, listening for connections.
49 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
50 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
51 /// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
53 /// The socket will be closed when the value is dropped.
55 /// The Transmission Control Protocol is specified in [IETF RFC 793].
57 /// [`accept`]: #method.accept
58 /// [`bind`]: #method.bind
59 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
60 /// [`Incoming`]: ../../std/net/struct.Incoming.html
61 /// [`TcpListener::incoming`]: #method.incoming
66 /// use std::net::{TcpListener, TcpStream};
68 /// fn handle_client(stream: TcpStream) {
72 /// fn main() -> std::io::Result<()> {
73 /// let listener = TcpListener::bind("127.0.0.1:80")?;
75 /// // accept connections and process them serially
76 /// for stream in listener.incoming() {
77 /// handle_client(stream?);
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub struct TcpListener(net_imp::TcpListener);
85 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
87 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
88 /// See its documentation for more.
90 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
91 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
92 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
93 #[stable(feature = "rust1", since = "1.0.0")]
95 pub struct Incoming<'a> {
96 listener: &'a TcpListener,
100 /// Opens a TCP connection to a remote host.
102 /// `addr` is an address of the remote host. Anything which implements
103 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
104 /// documentation for concrete examples.
106 /// If `addr` yields multiple addresses, `connect` will be attempted with
107 /// each of the addresses until a connection is successful. If none of
108 /// the addresses result in a successful connection, the error returned from
109 /// the last connection attempt (the last address) is returned.
111 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
115 /// Open a TCP connection to `127.0.0.1:8080`:
118 /// use std::net::TcpStream;
120 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
121 /// println!("Connected to the server!");
123 /// println!("Couldn't connect to server...");
127 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
128 /// a TCP connection to `127.0.0.1:8081`:
131 /// use std::net::{SocketAddr, TcpStream};
134 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
135 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
137 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
138 /// println!("Connected to the server!");
140 /// println!("Couldn't connect to server...");
143 #[stable(feature = "rust1", since = "1.0.0")]
144 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
145 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
148 /// Opens a TCP connection to a remote host with a timeout.
150 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
151 /// timeout must be applied to individual addresses.
153 /// It is an error to pass a zero `Duration` to this function.
155 /// Unlike other methods on `TcpStream`, this does not correspond to a
156 /// single system call. It instead calls `connect` in nonblocking mode and
157 /// then uses an OS-specific mechanism to await the completion of the
158 /// connection request.
160 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
161 #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
162 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
163 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
166 /// Returns the socket address of the remote peer of this TCP connection.
171 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
173 /// let stream = TcpStream::connect("127.0.0.1:8080")
174 /// .expect("Couldn't connect to the server...");
175 /// assert_eq!(stream.peer_addr().unwrap(),
176 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
178 #[stable(feature = "rust1", since = "1.0.0")]
179 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
183 /// Returns the socket address of the local half of this TCP connection.
188 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
190 /// let stream = TcpStream::connect("127.0.0.1:8080")
191 /// .expect("Couldn't connect to the server...");
192 /// assert_eq!(stream.local_addr().unwrap().ip(),
193 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub fn local_addr(&self) -> io::Result<SocketAddr> {
200 /// Shuts down the read, write, or both halves of this connection.
202 /// This function will cause all pending and future I/O on the specified
203 /// portions to return immediately with an appropriate value (see the
204 /// documentation of [`Shutdown`]).
206 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
208 /// # Platform-specific behavior
210 /// Calling this function multiple times may result in different behavior,
211 /// depending on the operating system. On Linux, the second call will
212 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
213 /// This may change in the future.
218 /// use std::net::{Shutdown, TcpStream};
220 /// let stream = TcpStream::connect("127.0.0.1:8080")
221 /// .expect("Couldn't connect to the server...");
222 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
229 /// Creates a new independently owned handle to the underlying socket.
231 /// The returned `TcpStream` is a reference to the same stream that this
232 /// object references. Both handles will read and write the same stream of
233 /// data, and options set on one stream will be propagated to the other
239 /// use std::net::TcpStream;
241 /// let stream = TcpStream::connect("127.0.0.1:8080")
242 /// .expect("Couldn't connect to the server...");
243 /// let stream_clone = stream.try_clone().expect("clone failed...");
245 #[stable(feature = "rust1", since = "1.0.0")]
246 pub fn try_clone(&self) -> io::Result<TcpStream> {
247 self.0.duplicate().map(TcpStream)
250 /// Sets the read timeout to the timeout specified.
252 /// If the value specified is [`None`], then [`read`] calls will block
253 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
254 /// passed to this method.
256 /// # Platform-specific behavior
258 /// Platforms may return a different error code whenever a read times out as
259 /// a result of setting this option. For example Unix typically returns an
260 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
262 /// [`None`]: ../../std/option/enum.Option.html#variant.None
263 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
264 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
265 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
266 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
267 /// [`Duration`]: ../../std/time/struct.Duration.html
272 /// use std::net::TcpStream;
274 /// let stream = TcpStream::connect("127.0.0.1:8080")
275 /// .expect("Couldn't connect to the server...");
276 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
279 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
284 /// use std::net::TcpStream;
285 /// use std::time::Duration;
287 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
288 /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
289 /// let err = result.unwrap_err();
290 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
292 #[stable(feature = "socket_timeout", since = "1.4.0")]
293 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
294 self.0.set_read_timeout(dur)
297 /// Sets the write timeout to the timeout specified.
299 /// If the value specified is [`None`], then [`write`] calls will block
300 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
301 /// passed to this method.
303 /// # Platform-specific behavior
305 /// Platforms may return a different error code whenever a write times out
306 /// as a result of setting this option. For example Unix typically returns
307 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
309 /// [`None`]: ../../std/option/enum.Option.html#variant.None
310 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
311 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
312 /// [`Duration`]: ../../std/time/struct.Duration.html
313 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
314 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
319 /// use std::net::TcpStream;
321 /// let stream = TcpStream::connect("127.0.0.1:8080")
322 /// .expect("Couldn't connect to the server...");
323 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
326 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
331 /// use std::net::TcpStream;
332 /// use std::time::Duration;
334 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
335 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
336 /// let err = result.unwrap_err();
337 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
339 #[stable(feature = "socket_timeout", since = "1.4.0")]
340 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
341 self.0.set_write_timeout(dur)
344 /// Returns the read timeout of this socket.
346 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
348 /// # Platform-specific behavior
350 /// Some platforms do not provide access to the current timeout.
352 /// [`None`]: ../../std/option/enum.Option.html#variant.None
353 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
358 /// use std::net::TcpStream;
360 /// let stream = TcpStream::connect("127.0.0.1:8080")
361 /// .expect("Couldn't connect to the server...");
362 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
363 /// assert_eq!(stream.read_timeout().unwrap(), None);
365 #[stable(feature = "socket_timeout", since = "1.4.0")]
366 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
367 self.0.read_timeout()
370 /// Returns the write timeout of this socket.
372 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
374 /// # Platform-specific behavior
376 /// Some platforms do not provide access to the current timeout.
378 /// [`None`]: ../../std/option/enum.Option.html#variant.None
379 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
384 /// use std::net::TcpStream;
386 /// let stream = TcpStream::connect("127.0.0.1:8080")
387 /// .expect("Couldn't connect to the server...");
388 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
389 /// assert_eq!(stream.write_timeout().unwrap(), None);
391 #[stable(feature = "socket_timeout", since = "1.4.0")]
392 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
393 self.0.write_timeout()
396 /// Receives data on the socket from the remote address to which it is
397 /// connected, without removing that data from the queue. On success,
398 /// returns the number of bytes peeked.
400 /// Successive calls return the same data. This is accomplished by passing
401 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
406 /// use std::net::TcpStream;
408 /// let stream = TcpStream::connect("127.0.0.1:8000")
409 /// .expect("couldn't bind to address");
410 /// let mut buf = [0; 10];
411 /// let len = stream.peek(&mut buf).expect("peek failed");
413 #[stable(feature = "peek", since = "1.18.0")]
414 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
418 /// Sets the value of the `TCP_NODELAY` option on this socket.
420 /// If set, this option disables the Nagle algorithm. This means that
421 /// segments are always sent as soon as possible, even if there is only a
422 /// small amount of data. When not set, data is buffered until there is a
423 /// sufficient amount to send out, thereby avoiding the frequent sending of
429 /// use std::net::TcpStream;
431 /// let stream = TcpStream::connect("127.0.0.1:8080")
432 /// .expect("Couldn't connect to the server...");
433 /// stream.set_nodelay(true).expect("set_nodelay call failed");
435 #[stable(feature = "net2_mutators", since = "1.9.0")]
436 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
437 self.0.set_nodelay(nodelay)
440 /// Gets the value of the `TCP_NODELAY` option on this socket.
442 /// For more information about this option, see [`set_nodelay`][link].
444 /// [link]: #method.set_nodelay
449 /// use std::net::TcpStream;
451 /// let stream = TcpStream::connect("127.0.0.1:8080")
452 /// .expect("Couldn't connect to the server...");
453 /// stream.set_nodelay(true).expect("set_nodelay call failed");
454 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
456 #[stable(feature = "net2_mutators", since = "1.9.0")]
457 pub fn nodelay(&self) -> io::Result<bool> {
461 /// Sets the value for the `IP_TTL` option on this socket.
463 /// This value sets the time-to-live field that is used in every packet sent
464 /// from this socket.
469 /// use std::net::TcpStream;
471 /// let stream = TcpStream::connect("127.0.0.1:8080")
472 /// .expect("Couldn't connect to the server...");
473 /// stream.set_ttl(100).expect("set_ttl call failed");
475 #[stable(feature = "net2_mutators", since = "1.9.0")]
476 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
480 /// Gets the value of the `IP_TTL` option for this socket.
482 /// For more information about this option, see [`set_ttl`][link].
484 /// [link]: #method.set_ttl
489 /// use std::net::TcpStream;
491 /// let stream = TcpStream::connect("127.0.0.1:8080")
492 /// .expect("Couldn't connect to the server...");
493 /// stream.set_ttl(100).expect("set_ttl call failed");
494 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
496 #[stable(feature = "net2_mutators", since = "1.9.0")]
497 pub fn ttl(&self) -> io::Result<u32> {
501 /// Gets the value of the `SO_ERROR` option on this socket.
503 /// This will retrieve the stored error in the underlying socket, clearing
504 /// the field in the process. This can be useful for checking errors between
510 /// use std::net::TcpStream;
512 /// let stream = TcpStream::connect("127.0.0.1:8080")
513 /// .expect("Couldn't connect to the server...");
514 /// stream.take_error().expect("No error was expected...");
516 #[stable(feature = "net2_mutators", since = "1.9.0")]
517 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
521 /// Moves this TCP stream into or out of nonblocking mode.
523 /// This will result in `read`, `write`, `recv` and `send` operations
524 /// becoming nonblocking, i.e., immediately returning from their calls.
525 /// If the IO operation is successful, `Ok` is returned and no further
526 /// action is required. If the IO operation could not be completed and needs
527 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
530 /// On Unix platforms, calling this method corresponds to calling `fcntl`
531 /// `FIONBIO`. On Windows calling this method corresponds to calling
532 /// `ioctlsocket` `FIONBIO`.
536 /// Reading bytes from a TCP stream in non-blocking mode:
539 /// use std::io::{self, Read};
540 /// use std::net::TcpStream;
542 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
543 /// .expect("Couldn't connect to the server...");
544 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
546 /// # fn wait_for_fd() { unimplemented!() }
547 /// let mut buf = vec![];
549 /// match stream.read_to_end(&mut buf) {
551 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
552 /// // wait until network socket is ready, typically implemented
553 /// // via platform-specific APIs such as epoll or IOCP
556 /// Err(e) => panic!("encountered IO error: {}", e),
559 /// println!("bytes: {:?}", buf);
562 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
563 #[stable(feature = "net2_mutators", since = "1.9.0")]
564 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
565 self.0.set_nonblocking(nonblocking)
569 #[stable(feature = "rust1", since = "1.0.0")]
570 impl Read for TcpStream {
571 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
575 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
576 self.0.read_vectored(bufs)
580 unsafe fn initializer(&self) -> Initializer {
584 #[stable(feature = "rust1", since = "1.0.0")]
585 impl Write for TcpStream {
586 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
590 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
591 self.0.write_vectored(bufs)
594 fn flush(&mut self) -> io::Result<()> {
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl Read for &TcpStream {
600 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
604 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
605 self.0.read_vectored(bufs)
609 unsafe fn initializer(&self) -> Initializer {
613 #[stable(feature = "rust1", since = "1.0.0")]
614 impl Write for &TcpStream {
615 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
619 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
620 self.0.write_vectored(bufs)
623 fn flush(&mut self) -> io::Result<()> {
628 impl AsInner<net_imp::TcpStream> for TcpStream {
629 fn as_inner(&self) -> &net_imp::TcpStream {
634 impl FromInner<net_imp::TcpStream> for TcpStream {
635 fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
640 impl IntoInner<net_imp::TcpStream> for TcpStream {
641 fn into_inner(self) -> net_imp::TcpStream {
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl fmt::Debug for TcpStream {
648 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
654 /// Creates a new `TcpListener` which will be bound to the specified
657 /// The returned listener is ready for accepting connections.
659 /// Binding with a port number of 0 will request that the OS assigns a port
660 /// to this listener. The port allocated can be queried via the
661 /// [`local_addr`] method.
663 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
664 /// its documentation for concrete examples.
666 /// If `addr` yields multiple addresses, `bind` will be attempted with
667 /// each of the addresses until one succeeds and returns the listener. If
668 /// none of the addresses succeed in creating a listener, the error returned
669 /// from the last attempt (the last address) is returned.
671 /// [`local_addr`]: #method.local_addr
672 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
676 /// Creates a TCP listener bound to `127.0.0.1:80`:
679 /// use std::net::TcpListener;
681 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
684 /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
685 /// TCP listener bound to `127.0.0.1:443`:
688 /// use std::net::{SocketAddr, TcpListener};
691 /// SocketAddr::from(([127, 0, 0, 1], 80)),
692 /// SocketAddr::from(([127, 0, 0, 1], 443)),
694 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
696 #[stable(feature = "rust1", since = "1.0.0")]
697 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
698 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
701 /// Returns the local socket address of this listener.
706 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
708 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
709 /// assert_eq!(listener.local_addr().unwrap(),
710 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
712 #[stable(feature = "rust1", since = "1.0.0")]
713 pub fn local_addr(&self) -> io::Result<SocketAddr> {
717 /// Creates a new independently owned handle to the underlying socket.
719 /// The returned [`TcpListener`] is a reference to the same socket that this
720 /// object references. Both handles can be used to accept incoming
721 /// connections and options set on one listener will affect the other.
723 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
728 /// use std::net::TcpListener;
730 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
731 /// let listener_clone = listener.try_clone().unwrap();
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn try_clone(&self) -> io::Result<TcpListener> {
735 self.0.duplicate().map(TcpListener)
738 /// Accept a new incoming connection from this listener.
740 /// This function will block the calling thread until a new TCP connection
741 /// is established. When established, the corresponding [`TcpStream`] and the
742 /// remote peer's address will be returned.
744 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
749 /// use std::net::TcpListener;
751 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
752 /// match listener.accept() {
753 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
754 /// Err(e) => println!("couldn't get client: {:?}", e),
757 #[stable(feature = "rust1", since = "1.0.0")]
758 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
759 // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
760 // the `a` variable here is technically unused.
761 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
762 self.0.accept().map(|(a, b)| (TcpStream(a), b))
765 /// Returns an iterator over the connections being received on this
768 /// The returned iterator will never return [`None`] and will also not yield
769 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
770 /// calling [`accept`] in a loop.
772 /// [`None`]: ../../std/option/enum.Option.html#variant.None
773 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
774 /// [`accept`]: #method.accept
779 /// use std::net::TcpListener;
781 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
783 /// for stream in listener.incoming() {
786 /// println!("new client!");
788 /// Err(e) => { /* connection failed */ }
792 #[stable(feature = "rust1", since = "1.0.0")]
793 pub fn incoming(&self) -> Incoming<'_> {
794 Incoming { listener: self }
797 /// Sets the value for the `IP_TTL` option on this socket.
799 /// This value sets the time-to-live field that is used in every packet sent
800 /// from this socket.
805 /// use std::net::TcpListener;
807 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
808 /// listener.set_ttl(100).expect("could not set TTL");
810 #[stable(feature = "net2_mutators", since = "1.9.0")]
811 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
815 /// Gets the value of the `IP_TTL` option for this socket.
817 /// For more information about this option, see [`set_ttl`][link].
819 /// [link]: #method.set_ttl
824 /// use std::net::TcpListener;
826 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
827 /// listener.set_ttl(100).expect("could not set TTL");
828 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
830 #[stable(feature = "net2_mutators", since = "1.9.0")]
831 pub fn ttl(&self) -> io::Result<u32> {
835 #[stable(feature = "net2_mutators", since = "1.9.0")]
838 reason = "this option can only be set before the socket is bound"
840 #[allow(missing_docs)]
841 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
842 self.0.set_only_v6(only_v6)
845 #[stable(feature = "net2_mutators", since = "1.9.0")]
848 reason = "this option can only be set before the socket is bound"
850 #[allow(missing_docs)]
851 pub fn only_v6(&self) -> io::Result<bool> {
855 /// Gets the value of the `SO_ERROR` option on this socket.
857 /// This will retrieve the stored error in the underlying socket, clearing
858 /// the field in the process. This can be useful for checking errors between
864 /// use std::net::TcpListener;
866 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
867 /// listener.take_error().expect("No error was expected");
869 #[stable(feature = "net2_mutators", since = "1.9.0")]
870 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
874 /// Moves this TCP stream into or out of nonblocking mode.
876 /// This will result in the `accept` operation becoming nonblocking,
877 /// i.e., immediately returning from their calls. If the IO operation is
878 /// successful, `Ok` is returned and no further action is required. If the
879 /// IO operation could not be completed and needs to be retried, an error
880 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
882 /// On Unix platforms, calling this method corresponds to calling `fcntl`
883 /// `FIONBIO`. On Windows calling this method corresponds to calling
884 /// `ioctlsocket` `FIONBIO`.
888 /// Bind a TCP listener to an address, listen for connections, and read
889 /// bytes in nonblocking mode:
893 /// use std::net::TcpListener;
895 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
896 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
898 /// # fn wait_for_fd() { unimplemented!() }
899 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
900 /// for stream in listener.incoming() {
903 /// // do something with the TcpStream
904 /// handle_connection(s);
906 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
907 /// // wait until network socket is ready, typically implemented
908 /// // via platform-specific APIs such as epoll or IOCP
912 /// Err(e) => panic!("encountered IO error: {}", e),
917 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
918 #[stable(feature = "net2_mutators", since = "1.9.0")]
919 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
920 self.0.set_nonblocking(nonblocking)
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl<'a> Iterator for Incoming<'a> {
926 type Item = io::Result<TcpStream>;
927 fn next(&mut self) -> Option<io::Result<TcpStream>> {
928 Some(self.listener.accept().map(|p| p.0))
932 impl AsInner<net_imp::TcpListener> for TcpListener {
933 fn as_inner(&self) -> &net_imp::TcpListener {
938 impl FromInner<net_imp::TcpListener> for TcpListener {
939 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
944 impl IntoInner<net_imp::TcpListener> for TcpListener {
945 fn into_inner(self) -> net_imp::TcpListener {
950 #[stable(feature = "rust1", since = "1.0.0")]
951 impl fmt::Debug for TcpListener {
952 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
957 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
960 use crate::io::prelude::*;
961 use crate::io::{ErrorKind, IoSlice, IoSliceMut};
962 use crate::net::test::{next_test_ip4, next_test_ip6};
964 use crate::sync::mpsc::channel;
966 use crate::time::{Duration, Instant};
968 fn each_ip(f: &mut dyn FnMut(SocketAddr)) {
977 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
984 match TcpListener::bind("1.1.1.1:9999") {
986 Err(e) => assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
992 match TcpStream::connect("0.0.0.0:1") {
995 e.kind() == ErrorKind::ConnectionRefused
996 || e.kind() == ErrorKind::InvalidInput
997 || e.kind() == ErrorKind::AddrInUse
998 || e.kind() == ErrorKind::AddrNotAvailable,
999 "bad error: {} {:?}",
1007 fn listen_localhost() {
1008 let socket_addr = next_test_ip4();
1009 let listener = t!(TcpListener::bind(&socket_addr));
1011 let _t = thread::spawn(move || {
1012 let mut stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
1013 t!(stream.write(&[144]));
1016 let mut stream = t!(listener.accept()).0;
1018 t!(stream.read(&mut buf));
1019 assert!(buf[0] == 144);
1023 fn connect_loopback() {
1024 each_ip(&mut |addr| {
1025 let acceptor = t!(TcpListener::bind(&addr));
1027 let _t = thread::spawn(move || {
1028 let host = match addr {
1029 SocketAddr::V4(..) => "127.0.0.1",
1030 SocketAddr::V6(..) => "::1",
1032 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
1033 t!(stream.write(&[66]));
1036 let mut stream = t!(acceptor.accept()).0;
1038 t!(stream.read(&mut buf));
1039 assert!(buf[0] == 66);
1045 each_ip(&mut |addr| {
1046 let acceptor = t!(TcpListener::bind(&addr));
1048 let (tx, rx) = channel();
1049 let _t = thread::spawn(move || {
1050 let mut stream = t!(TcpStream::connect(&addr));
1051 t!(stream.write(&[99]));
1052 tx.send(t!(stream.local_addr())).unwrap();
1055 let (mut stream, addr) = t!(acceptor.accept());
1057 t!(stream.read(&mut buf));
1058 assert!(buf[0] == 99);
1059 assert_eq!(addr, t!(rx.recv()));
1065 each_ip(&mut |addr| {
1066 let acceptor = t!(TcpListener::bind(&addr));
1068 let _t = thread::spawn(move || {
1069 let _stream = t!(TcpStream::connect(&addr));
1073 let mut stream = t!(acceptor.accept()).0;
1075 let nread = t!(stream.read(&mut buf));
1076 assert_eq!(nread, 0);
1077 let nread = t!(stream.read(&mut buf));
1078 assert_eq!(nread, 0);
1084 each_ip(&mut |addr| {
1085 let acceptor = t!(TcpListener::bind(&addr));
1087 let (tx, rx) = channel();
1088 let _t = thread::spawn(move || {
1089 drop(t!(TcpStream::connect(&addr)));
1090 tx.send(()).unwrap();
1093 let mut stream = t!(acceptor.accept()).0;
1096 match stream.write(&buf) {
1100 e.kind() == ErrorKind::ConnectionReset
1101 || e.kind() == ErrorKind::BrokenPipe
1102 || e.kind() == ErrorKind::ConnectionAborted,
1103 "unknown error: {}",
1112 fn multiple_connect_serial() {
1113 each_ip(&mut |addr| {
1115 let acceptor = t!(TcpListener::bind(&addr));
1117 let _t = thread::spawn(move || {
1119 let mut stream = t!(TcpStream::connect(&addr));
1120 t!(stream.write(&[99]));
1124 for stream in acceptor.incoming().take(max) {
1125 let mut stream = t!(stream);
1127 t!(stream.read(&mut buf));
1128 assert_eq!(buf[0], 99);
1134 fn multiple_connect_interleaved_greedy_schedule() {
1135 const MAX: usize = 10;
1136 each_ip(&mut |addr| {
1137 let acceptor = t!(TcpListener::bind(&addr));
1139 let _t = thread::spawn(move || {
1140 let acceptor = acceptor;
1141 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
1142 // Start another thread to handle the connection
1143 let _t = thread::spawn(move || {
1144 let mut stream = t!(stream);
1146 t!(stream.read(&mut buf));
1147 assert!(buf[0] == i as u8);
1155 fn connect(i: usize, addr: SocketAddr) {
1160 let t = thread::spawn(move || {
1161 let mut stream = t!(TcpStream::connect(&addr));
1162 // Connect again before writing
1163 connect(i + 1, addr);
1164 t!(stream.write(&[i as u8]));
1166 t.join().ok().expect("thread panicked");
1171 fn multiple_connect_interleaved_lazy_schedule() {
1172 const MAX: usize = 10;
1173 each_ip(&mut |addr| {
1174 let acceptor = t!(TcpListener::bind(&addr));
1176 let _t = thread::spawn(move || {
1177 for stream in acceptor.incoming().take(MAX) {
1178 // Start another thread to handle the connection
1179 let _t = thread::spawn(move || {
1180 let mut stream = t!(stream);
1182 t!(stream.read(&mut buf));
1183 assert!(buf[0] == 99);
1191 fn connect(i: usize, addr: SocketAddr) {
1196 let t = thread::spawn(move || {
1197 let mut stream = t!(TcpStream::connect(&addr));
1198 connect(i + 1, addr);
1199 t!(stream.write(&[99]));
1201 t.join().ok().expect("thread panicked");
1206 fn socket_and_peer_name() {
1207 each_ip(&mut |addr| {
1208 let listener = t!(TcpListener::bind(&addr));
1209 let so_name = t!(listener.local_addr());
1210 assert_eq!(addr, so_name);
1211 let _t = thread::spawn(move || {
1212 t!(listener.accept());
1215 let stream = t!(TcpStream::connect(&addr));
1216 assert_eq!(addr, t!(stream.peer_addr()));
1222 each_ip(&mut |addr| {
1223 let (tx, rx) = channel();
1224 let srv = t!(TcpListener::bind(&addr));
1225 let _t = thread::spawn(move || {
1226 let mut cl = t!(srv.accept()).0;
1227 cl.write(&[10]).unwrap();
1229 t!(cl.read(&mut b));
1230 tx.send(()).unwrap();
1233 let mut c = t!(TcpStream::connect(&addr));
1234 let mut b = [0; 10];
1235 assert_eq!(c.read(&mut b).unwrap(), 1);
1242 fn read_vectored() {
1243 each_ip(&mut |addr| {
1244 let srv = t!(TcpListener::bind(&addr));
1245 let mut s1 = t!(TcpStream::connect(&addr));
1246 let mut s2 = t!(srv.accept()).0;
1248 let len = s1.write(&[10, 11, 12]).unwrap();
1254 let len = t!(s2.read_vectored(&mut [
1255 IoSliceMut::new(&mut a),
1256 IoSliceMut::new(&mut b),
1257 IoSliceMut::new(&mut c)
1260 assert_eq!(b, [10]);
1261 // some implementations don't support readv, so we may only fill the first buffer
1262 assert!(len == 1 || c == [11, 12, 0]);
1267 fn write_vectored() {
1268 each_ip(&mut |addr| {
1269 let srv = t!(TcpListener::bind(&addr));
1270 let mut s1 = t!(TcpStream::connect(&addr));
1271 let mut s2 = t!(srv.accept()).0;
1276 t!(s1.write_vectored(&[IoSlice::new(&a), IoSlice::new(&b), IoSlice::new(&c)]));
1278 let mut buf = [0; 4];
1279 let len = t!(s2.read(&mut buf));
1280 // some implementations don't support writev, so we may only write the first buffer
1282 assert_eq!(buf, [10, 0, 0, 0]);
1285 assert_eq!(buf, [10, 11, 12, 0]);
1292 each_ip(&mut |addr| {
1293 let listener1 = t!(TcpListener::bind(&addr));
1294 match TcpListener::bind(&addr) {
1295 Ok(listener2) => panic!(
1296 "This system (perhaps due to options set by TcpListener::bind) \
1297 permits double binding: {:?} and {:?}",
1298 listener1, listener2
1302 e.kind() == ErrorKind::ConnectionRefused
1303 || e.kind() == ErrorKind::Other
1304 || e.kind() == ErrorKind::AddrInUse,
1305 "unknown error: {} {:?}",
1315 fn tcp_clone_smoke() {
1316 each_ip(&mut |addr| {
1317 let acceptor = t!(TcpListener::bind(&addr));
1319 let _t = thread::spawn(move || {
1320 let mut s = t!(TcpStream::connect(&addr));
1321 let mut buf = [0, 0];
1322 assert_eq!(s.read(&mut buf).unwrap(), 1);
1323 assert_eq!(buf[0], 1);
1327 let mut s1 = t!(acceptor.accept()).0;
1328 let s2 = t!(s1.try_clone());
1330 let (tx1, rx1) = channel();
1331 let (tx2, rx2) = channel();
1332 let _t = thread::spawn(move || {
1334 rx1.recv().unwrap();
1336 tx2.send(()).unwrap();
1338 tx1.send(()).unwrap();
1339 let mut buf = [0, 0];
1340 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1341 rx2.recv().unwrap();
1346 fn tcp_clone_two_read() {
1347 each_ip(&mut |addr| {
1348 let acceptor = t!(TcpListener::bind(&addr));
1349 let (tx1, rx) = channel();
1350 let tx2 = tx1.clone();
1352 let _t = thread::spawn(move || {
1353 let mut s = t!(TcpStream::connect(&addr));
1360 let mut s1 = t!(acceptor.accept()).0;
1361 let s2 = t!(s1.try_clone());
1363 let (done, rx) = channel();
1364 let _t = thread::spawn(move || {
1366 let mut buf = [0, 0];
1367 t!(s2.read(&mut buf));
1368 tx2.send(()).unwrap();
1369 done.send(()).unwrap();
1371 let mut buf = [0, 0];
1372 t!(s1.read(&mut buf));
1373 tx1.send(()).unwrap();
1380 fn tcp_clone_two_write() {
1381 each_ip(&mut |addr| {
1382 let acceptor = t!(TcpListener::bind(&addr));
1384 let _t = thread::spawn(move || {
1385 let mut s = t!(TcpStream::connect(&addr));
1386 let mut buf = [0, 1];
1387 t!(s.read(&mut buf));
1388 t!(s.read(&mut buf));
1391 let mut s1 = t!(acceptor.accept()).0;
1392 let s2 = t!(s1.try_clone());
1394 let (done, rx) = channel();
1395 let _t = thread::spawn(move || {
1398 done.send(()).unwrap();
1407 // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1408 #[cfg_attr(target_env = "sgx", ignore)]
1409 fn shutdown_smoke() {
1410 each_ip(&mut |addr| {
1411 let a = t!(TcpListener::bind(&addr));
1412 let _t = thread::spawn(move || {
1413 let mut c = t!(a.accept()).0;
1415 assert_eq!(c.read(&mut b).unwrap(), 0);
1419 let mut s = t!(TcpStream::connect(&addr));
1420 t!(s.shutdown(Shutdown::Write));
1421 assert!(s.write(&[1]).is_err());
1423 assert_eq!(t!(s.read(&mut b)), 1);
1424 assert_eq!(b[0], 1);
1429 // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1430 #[cfg_attr(target_env = "sgx", ignore)]
1431 fn close_readwrite_smoke() {
1432 each_ip(&mut |addr| {
1433 let a = t!(TcpListener::bind(&addr));
1434 let (tx, rx) = channel::<()>();
1435 let _t = thread::spawn(move || {
1436 let _s = t!(a.accept());
1441 let mut s = t!(TcpStream::connect(&addr));
1442 let mut s2 = t!(s.try_clone());
1444 // closing should prevent reads/writes
1445 t!(s.shutdown(Shutdown::Write));
1446 assert!(s.write(&[0]).is_err());
1447 t!(s.shutdown(Shutdown::Read));
1448 assert_eq!(s.read(&mut b).unwrap(), 0);
1450 // closing should affect previous handles
1451 assert!(s2.write(&[0]).is_err());
1452 assert_eq!(s2.read(&mut b).unwrap(), 0);
1454 // closing should affect new handles
1455 let mut s3 = t!(s.try_clone());
1456 assert!(s3.write(&[0]).is_err());
1457 assert_eq!(s3.read(&mut b).unwrap(), 0);
1459 // make sure these don't die
1460 let _ = s2.shutdown(Shutdown::Read);
1461 let _ = s2.shutdown(Shutdown::Write);
1462 let _ = s3.shutdown(Shutdown::Read);
1463 let _ = s3.shutdown(Shutdown::Write);
1469 #[cfg(unix)] // test doesn't work on Windows, see #31657
1470 fn close_read_wakes_up() {
1471 each_ip(&mut |addr| {
1472 let a = t!(TcpListener::bind(&addr));
1473 let (tx1, rx) = channel::<()>();
1474 let _t = thread::spawn(move || {
1475 let _s = t!(a.accept());
1479 let s = t!(TcpStream::connect(&addr));
1480 let s2 = t!(s.try_clone());
1481 let (tx, rx) = channel();
1482 let _t = thread::spawn(move || {
1484 assert_eq!(t!(s2.read(&mut [0])), 0);
1485 tx.send(()).unwrap();
1487 // this should wake up the child thread
1488 t!(s.shutdown(Shutdown::Read));
1490 // this test will never finish if the child doesn't wake up
1497 fn clone_while_reading() {
1498 each_ip(&mut |addr| {
1499 let accept = t!(TcpListener::bind(&addr));
1501 // Enqueue a thread to write to a socket
1502 let (tx, rx) = channel();
1503 let (txdone, rxdone) = channel();
1504 let txdone2 = txdone.clone();
1505 let _t = thread::spawn(move || {
1506 let mut tcp = t!(TcpStream::connect(&addr));
1508 t!(tcp.write(&[0]));
1509 txdone2.send(()).unwrap();
1512 // Spawn off a reading clone
1513 let tcp = t!(accept.accept()).0;
1514 let tcp2 = t!(tcp.try_clone());
1515 let txdone3 = txdone.clone();
1516 let _t = thread::spawn(move || {
1517 let mut tcp2 = tcp2;
1518 t!(tcp2.read(&mut [0]));
1519 txdone3.send(()).unwrap();
1522 // Try to ensure that the reading clone is indeed reading
1524 thread::yield_now();
1527 // clone the handle again while it's reading, then let it finish the
1529 let _ = t!(tcp.try_clone());
1530 tx.send(()).unwrap();
1531 rxdone.recv().unwrap();
1532 rxdone.recv().unwrap();
1537 fn clone_accept_smoke() {
1538 each_ip(&mut |addr| {
1539 let a = t!(TcpListener::bind(&addr));
1540 let a2 = t!(a.try_clone());
1542 let _t = thread::spawn(move || {
1543 let _ = TcpStream::connect(&addr);
1545 let _t = thread::spawn(move || {
1546 let _ = TcpStream::connect(&addr);
1555 fn clone_accept_concurrent() {
1556 each_ip(&mut |addr| {
1557 let a = t!(TcpListener::bind(&addr));
1558 let a2 = t!(a.try_clone());
1560 let (tx, rx) = channel();
1561 let tx2 = tx.clone();
1563 let _t = thread::spawn(move || {
1564 tx.send(t!(a.accept())).unwrap();
1566 let _t = thread::spawn(move || {
1567 tx2.send(t!(a2.accept())).unwrap();
1570 let _t = thread::spawn(move || {
1571 let _ = TcpStream::connect(&addr);
1573 let _t = thread::spawn(move || {
1574 let _ = TcpStream::connect(&addr);
1584 #[cfg(not(target_env = "sgx"))]
1585 fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1588 #[cfg(target_env = "sgx")]
1589 fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1593 #[cfg(target_env = "sgx")]
1594 use crate::os::fortanix_sgx::io::AsRawFd;
1596 use crate::os::unix::io::AsRawFd;
1597 #[cfg(not(windows))]
1598 fn render_inner(addr: &dyn AsRawFd) -> impl fmt::Debug {
1602 fn render_inner(addr: &dyn crate::os::windows::io::AsRawSocket) -> impl fmt::Debug {
1603 addr.as_raw_socket()
1606 let inner_name = if cfg!(windows) { "socket" } else { "fd" };
1607 let socket_addr = next_test_ip4();
1609 let listener = t!(TcpListener::bind(&socket_addr));
1610 let compare = format!(
1611 "TcpListener {{ addr: {:?}, {}: {:?} }}",
1612 render_socket_addr(&socket_addr),
1614 render_inner(&listener)
1616 assert_eq!(format!("{:?}", listener), compare);
1618 let stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
1619 let compare = format!(
1620 "TcpStream {{ addr: {:?}, peer: {:?}, {}: {:?} }}",
1621 render_socket_addr(&stream.local_addr().unwrap()),
1622 render_socket_addr(&stream.peer_addr().unwrap()),
1624 render_inner(&stream)
1626 assert_eq!(format!("{:?}", stream), compare);
1629 // FIXME: re-enabled openbsd tests once their socket timeout code
1630 // no longer has rounding errors.
1631 // VxWorks ignores SO_SNDTIMEO.
1632 #[cfg_attr(any(target_os = "netbsd", target_os = "openbsd", target_os = "vxworks"), ignore)]
1633 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1636 let addr = next_test_ip4();
1637 let listener = t!(TcpListener::bind(&addr));
1639 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1640 let dur = Duration::new(15410, 0);
1642 assert_eq!(None, t!(stream.read_timeout()));
1644 t!(stream.set_read_timeout(Some(dur)));
1645 assert_eq!(Some(dur), t!(stream.read_timeout()));
1647 assert_eq!(None, t!(stream.write_timeout()));
1649 t!(stream.set_write_timeout(Some(dur)));
1650 assert_eq!(Some(dur), t!(stream.write_timeout()));
1652 t!(stream.set_read_timeout(None));
1653 assert_eq!(None, t!(stream.read_timeout()));
1655 t!(stream.set_write_timeout(None));
1656 assert_eq!(None, t!(stream.write_timeout()));
1661 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1662 fn test_read_timeout() {
1663 let addr = next_test_ip4();
1664 let listener = t!(TcpListener::bind(&addr));
1666 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1667 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1669 let mut buf = [0; 10];
1670 let start = Instant::now();
1671 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1673 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1674 "unexpected_error: {:?}",
1677 assert!(start.elapsed() > Duration::from_millis(400));
1682 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1683 fn test_read_with_timeout() {
1684 let addr = next_test_ip4();
1685 let listener = t!(TcpListener::bind(&addr));
1687 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1688 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1690 let mut other_end = t!(listener.accept()).0;
1691 t!(other_end.write_all(b"hello world"));
1693 let mut buf = [0; 11];
1694 t!(stream.read(&mut buf));
1695 assert_eq!(b"hello world", &buf[..]);
1697 let start = Instant::now();
1698 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1700 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1701 "unexpected_error: {:?}",
1704 assert!(start.elapsed() > Duration::from_millis(400));
1708 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1709 // when passed zero Durations
1711 fn test_timeout_zero_duration() {
1712 let addr = next_test_ip4();
1714 let listener = t!(TcpListener::bind(&addr));
1715 let stream = t!(TcpStream::connect(&addr));
1717 let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1718 let err = result.unwrap_err();
1719 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1721 let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1722 let err = result.unwrap_err();
1723 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1729 #[cfg_attr(target_env = "sgx", ignore)]
1731 let addr = next_test_ip4();
1732 let _listener = t!(TcpListener::bind(&addr));
1734 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1736 assert_eq!(false, t!(stream.nodelay()));
1737 t!(stream.set_nodelay(true));
1738 assert_eq!(true, t!(stream.nodelay()));
1739 t!(stream.set_nodelay(false));
1740 assert_eq!(false, t!(stream.nodelay()));
1744 #[cfg_attr(target_env = "sgx", ignore)]
1748 let addr = next_test_ip4();
1749 let listener = t!(TcpListener::bind(&addr));
1751 t!(listener.set_ttl(ttl));
1752 assert_eq!(ttl, t!(listener.ttl()));
1754 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1756 t!(stream.set_ttl(ttl));
1757 assert_eq!(ttl, t!(stream.ttl()));
1761 #[cfg_attr(target_env = "sgx", ignore)]
1762 fn set_nonblocking() {
1763 let addr = next_test_ip4();
1764 let listener = t!(TcpListener::bind(&addr));
1766 t!(listener.set_nonblocking(true));
1767 t!(listener.set_nonblocking(false));
1769 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1771 t!(stream.set_nonblocking(false));
1772 t!(stream.set_nonblocking(true));
1775 match stream.read(&mut buf) {
1776 Ok(_) => panic!("expected error"),
1777 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1778 Err(e) => panic!("unexpected error {}", e),
1783 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1785 each_ip(&mut |addr| {
1786 let (txdone, rxdone) = channel();
1788 let srv = t!(TcpListener::bind(&addr));
1789 let _t = thread::spawn(move || {
1790 let mut cl = t!(srv.accept()).0;
1791 cl.write(&[1, 3, 3, 7]).unwrap();
1795 let mut c = t!(TcpStream::connect(&addr));
1796 let mut b = [0; 10];
1798 let len = c.peek(&mut b).unwrap();
1801 let len = c.read(&mut b).unwrap();
1804 t!(c.set_nonblocking(true));
1805 match c.peek(&mut b) {
1806 Ok(_) => panic!("expected error"),
1807 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1808 Err(e) => panic!("unexpected error {}", e),
1810 t!(txdone.send(()));
1815 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1816 fn connect_timeout_valid() {
1817 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1818 let addr = listener.local_addr().unwrap();
1819 TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();