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
67 /// use std::net::{TcpListener, TcpStream};
69 /// fn handle_client(stream: TcpStream) {
73 /// fn main() -> io::Result<()> {
74 /// let listener = TcpListener::bind("127.0.0.1:80")?;
76 /// // accept connections and process them serially
77 /// for stream in listener.incoming() {
78 /// handle_client(stream?);
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct TcpListener(net_imp::TcpListener);
86 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
88 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
89 /// See its documentation for more.
91 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
92 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
93 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
94 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct Incoming<'a> {
97 listener: &'a TcpListener,
101 /// Opens a TCP connection to a remote host.
103 /// `addr` is an address of the remote host. Anything which implements
104 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
105 /// documentation for concrete examples.
107 /// If `addr` yields multiple addresses, `connect` will be attempted with
108 /// each of the addresses until a connection is successful. If none of
109 /// the addresses result in a successful connection, the error returned from
110 /// the last connection attempt (the last address) is returned.
112 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
116 /// Open a TCP connection to `127.0.0.1:8080`:
119 /// use std::net::TcpStream;
121 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
122 /// println!("Connected to the server!");
124 /// println!("Couldn't connect to server...");
128 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
129 /// a TCP connection to `127.0.0.1:8081`:
132 /// use std::net::{SocketAddr, TcpStream};
135 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
136 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
138 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
139 /// println!("Connected to the server!");
141 /// println!("Couldn't connect to server...");
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
146 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
149 /// Opens a TCP connection to a remote host with a timeout.
151 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
152 /// timeout must be applied to individual addresses.
154 /// It is an error to pass a zero `Duration` to this function.
156 /// Unlike other methods on `TcpStream`, this does not correspond to a
157 /// single system call. It instead calls `connect` in nonblocking mode and
158 /// then uses an OS-specific mechanism to await the completion of the
159 /// connection request.
161 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
162 #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
163 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
164 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
167 /// Returns the socket address of the remote peer of this TCP connection.
172 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
174 /// let stream = TcpStream::connect("127.0.0.1:8080")
175 /// .expect("Couldn't connect to the server...");
176 /// assert_eq!(stream.peer_addr().unwrap(),
177 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
184 /// Returns the socket address of the local half of this TCP connection.
189 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
191 /// let stream = TcpStream::connect("127.0.0.1:8080")
192 /// .expect("Couldn't connect to the server...");
193 /// assert_eq!(stream.local_addr().unwrap().ip(),
194 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub fn local_addr(&self) -> io::Result<SocketAddr> {
201 /// Shuts down the read, write, or both halves of this connection.
203 /// This function will cause all pending and future I/O on the specified
204 /// portions to return immediately with an appropriate value (see the
205 /// documentation of [`Shutdown`]).
207 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
209 /// # Platform-specific behavior
211 /// Calling this function multiple times may result in different behavior,
212 /// depending on the operating system. On Linux, the second call will
213 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
214 /// This may change in the future.
219 /// use std::net::{Shutdown, TcpStream};
221 /// let stream = TcpStream::connect("127.0.0.1:8080")
222 /// .expect("Couldn't connect to the server...");
223 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
225 #[stable(feature = "rust1", since = "1.0.0")]
226 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
230 /// Creates a new independently owned handle to the underlying socket.
232 /// The returned `TcpStream` is a reference to the same stream that this
233 /// object references. Both handles will read and write the same stream of
234 /// data, and options set on one stream will be propagated to the other
240 /// use std::net::TcpStream;
242 /// let stream = TcpStream::connect("127.0.0.1:8080")
243 /// .expect("Couldn't connect to the server...");
244 /// let stream_clone = stream.try_clone().expect("clone failed...");
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub fn try_clone(&self) -> io::Result<TcpStream> {
248 self.0.duplicate().map(TcpStream)
251 /// Sets the read timeout to the timeout specified.
253 /// If the value specified is [`None`], then [`read`] calls will block
254 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
255 /// passed to this method.
257 /// # Platform-specific behavior
259 /// Platforms may return a different error code whenever a read times out as
260 /// a result of setting this option. For example Unix typically returns an
261 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
263 /// [`None`]: ../../std/option/enum.Option.html#variant.None
264 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
265 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
266 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
267 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
268 /// [`Duration`]: ../../std/time/struct.Duration.html
273 /// use std::net::TcpStream;
275 /// let stream = TcpStream::connect("127.0.0.1:8080")
276 /// .expect("Couldn't connect to the server...");
277 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
280 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
285 /// use std::net::TcpStream;
286 /// use std::time::Duration;
288 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
289 /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
290 /// let err = result.unwrap_err();
291 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
293 #[stable(feature = "socket_timeout", since = "1.4.0")]
294 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
295 self.0.set_read_timeout(dur)
298 /// Sets the write timeout to the timeout specified.
300 /// If the value specified is [`None`], then [`write`] calls will block
301 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
302 /// passed to this method.
304 /// # Platform-specific behavior
306 /// Platforms may return a different error code whenever a write times out
307 /// as a result of setting this option. For example Unix typically returns
308 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
310 /// [`None`]: ../../std/option/enum.Option.html#variant.None
311 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
312 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
313 /// [`Duration`]: ../../std/time/struct.Duration.html
314 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
315 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
320 /// use std::net::TcpStream;
322 /// let stream = TcpStream::connect("127.0.0.1:8080")
323 /// .expect("Couldn't connect to the server...");
324 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
327 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
332 /// use std::net::TcpStream;
333 /// use std::time::Duration;
335 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
336 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
337 /// let err = result.unwrap_err();
338 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
340 #[stable(feature = "socket_timeout", since = "1.4.0")]
341 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
342 self.0.set_write_timeout(dur)
345 /// Returns the read timeout of this socket.
347 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
349 /// # Platform-specific behavior
351 /// Some platforms do not provide access to the current timeout.
353 /// [`None`]: ../../std/option/enum.Option.html#variant.None
354 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
359 /// use std::net::TcpStream;
361 /// let stream = TcpStream::connect("127.0.0.1:8080")
362 /// .expect("Couldn't connect to the server...");
363 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
364 /// assert_eq!(stream.read_timeout().unwrap(), None);
366 #[stable(feature = "socket_timeout", since = "1.4.0")]
367 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
368 self.0.read_timeout()
371 /// Returns the write timeout of this socket.
373 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
375 /// # Platform-specific behavior
377 /// Some platforms do not provide access to the current timeout.
379 /// [`None`]: ../../std/option/enum.Option.html#variant.None
380 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
385 /// use std::net::TcpStream;
387 /// let stream = TcpStream::connect("127.0.0.1:8080")
388 /// .expect("Couldn't connect to the server...");
389 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
390 /// assert_eq!(stream.write_timeout().unwrap(), None);
392 #[stable(feature = "socket_timeout", since = "1.4.0")]
393 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
394 self.0.write_timeout()
397 /// Receives data on the socket from the remote address to which it is
398 /// connected, without removing that data from the queue. On success,
399 /// returns the number of bytes peeked.
401 /// Successive calls return the same data. This is accomplished by passing
402 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
407 /// use std::net::TcpStream;
409 /// let stream = TcpStream::connect("127.0.0.1:8000")
410 /// .expect("couldn't bind to address");
411 /// let mut buf = [0; 10];
412 /// let len = stream.peek(&mut buf).expect("peek failed");
414 #[stable(feature = "peek", since = "1.18.0")]
415 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
419 /// Sets the value of the `TCP_NODELAY` option on this socket.
421 /// If set, this option disables the Nagle algorithm. This means that
422 /// segments are always sent as soon as possible, even if there is only a
423 /// small amount of data. When not set, data is buffered until there is a
424 /// sufficient amount to send out, thereby avoiding the frequent sending of
430 /// use std::net::TcpStream;
432 /// let stream = TcpStream::connect("127.0.0.1:8080")
433 /// .expect("Couldn't connect to the server...");
434 /// stream.set_nodelay(true).expect("set_nodelay call failed");
436 #[stable(feature = "net2_mutators", since = "1.9.0")]
437 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
438 self.0.set_nodelay(nodelay)
441 /// Gets the value of the `TCP_NODELAY` option on this socket.
443 /// For more information about this option, see [`set_nodelay`][link].
445 /// [link]: #method.set_nodelay
450 /// use std::net::TcpStream;
452 /// let stream = TcpStream::connect("127.0.0.1:8080")
453 /// .expect("Couldn't connect to the server...");
454 /// stream.set_nodelay(true).expect("set_nodelay call failed");
455 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
457 #[stable(feature = "net2_mutators", since = "1.9.0")]
458 pub fn nodelay(&self) -> io::Result<bool> {
462 /// Sets the value for the `IP_TTL` option on this socket.
464 /// This value sets the time-to-live field that is used in every packet sent
465 /// from this socket.
470 /// use std::net::TcpStream;
472 /// let stream = TcpStream::connect("127.0.0.1:8080")
473 /// .expect("Couldn't connect to the server...");
474 /// stream.set_ttl(100).expect("set_ttl call failed");
476 #[stable(feature = "net2_mutators", since = "1.9.0")]
477 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
481 /// Gets the value of the `IP_TTL` option for this socket.
483 /// For more information about this option, see [`set_ttl`][link].
485 /// [link]: #method.set_ttl
490 /// use std::net::TcpStream;
492 /// let stream = TcpStream::connect("127.0.0.1:8080")
493 /// .expect("Couldn't connect to the server...");
494 /// stream.set_ttl(100).expect("set_ttl call failed");
495 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
497 #[stable(feature = "net2_mutators", since = "1.9.0")]
498 pub fn ttl(&self) -> io::Result<u32> {
502 /// Gets the value of the `SO_ERROR` option on this socket.
504 /// This will retrieve the stored error in the underlying socket, clearing
505 /// the field in the process. This can be useful for checking errors between
511 /// use std::net::TcpStream;
513 /// let stream = TcpStream::connect("127.0.0.1:8080")
514 /// .expect("Couldn't connect to the server...");
515 /// stream.take_error().expect("No error was expected...");
517 #[stable(feature = "net2_mutators", since = "1.9.0")]
518 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
522 /// Moves this TCP stream into or out of nonblocking mode.
524 /// This will result in `read`, `write`, `recv` and `send` operations
525 /// becoming nonblocking, i.e., immediately returning from their calls.
526 /// If the IO operation is successful, `Ok` is returned and no further
527 /// action is required. If the IO operation could not be completed and needs
528 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
531 /// On Unix platforms, calling this method corresponds to calling `fcntl`
532 /// `FIONBIO`. On Windows calling this method corresponds to calling
533 /// `ioctlsocket` `FIONBIO`.
537 /// Reading bytes from a TCP stream in non-blocking mode:
540 /// use std::io::{self, Read};
541 /// use std::net::TcpStream;
543 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
544 /// .expect("Couldn't connect to the server...");
545 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
547 /// # fn wait_for_fd() { unimplemented!() }
548 /// let mut buf = vec![];
550 /// match stream.read_to_end(&mut buf) {
552 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
553 /// // wait until network socket is ready, typically implemented
554 /// // via platform-specific APIs such as epoll or IOCP
557 /// Err(e) => panic!("encountered IO error: {}", e),
560 /// println!("bytes: {:?}", buf);
563 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
564 #[stable(feature = "net2_mutators", since = "1.9.0")]
565 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
566 self.0.set_nonblocking(nonblocking)
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl Read for TcpStream {
572 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
576 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
577 self.0.read_vectored(bufs)
581 unsafe fn initializer(&self) -> Initializer {
585 #[stable(feature = "rust1", since = "1.0.0")]
586 impl Write for TcpStream {
587 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
591 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
592 self.0.write_vectored(bufs)
595 fn flush(&mut self) -> io::Result<()> {
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl Read for &TcpStream {
601 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
605 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
606 self.0.read_vectored(bufs)
610 unsafe fn initializer(&self) -> Initializer {
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl Write for &TcpStream {
616 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
620 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
621 self.0.write_vectored(bufs)
624 fn flush(&mut self) -> io::Result<()> {
629 impl AsInner<net_imp::TcpStream> for TcpStream {
630 fn as_inner(&self) -> &net_imp::TcpStream {
635 impl FromInner<net_imp::TcpStream> for TcpStream {
636 fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
641 impl IntoInner<net_imp::TcpStream> for TcpStream {
642 fn into_inner(self) -> net_imp::TcpStream {
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl fmt::Debug for TcpStream {
649 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 /// Creates a new `TcpListener` which will be bound to the specified
658 /// The returned listener is ready for accepting connections.
660 /// Binding with a port number of 0 will request that the OS assigns a port
661 /// to this listener. The port allocated can be queried via the
662 /// [`local_addr`] method.
664 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
665 /// its documentation for concrete examples.
667 /// If `addr` yields multiple addresses, `bind` will be attempted with
668 /// each of the addresses until one succeeds and returns the listener. If
669 /// none of the addresses succeed in creating a listener, the error returned
670 /// from the last attempt (the last address) is returned.
672 /// [`local_addr`]: #method.local_addr
673 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
677 /// Creates a TCP listener bound to `127.0.0.1:80`:
680 /// use std::net::TcpListener;
682 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
685 /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
686 /// TCP listener bound to `127.0.0.1:443`:
689 /// use std::net::{SocketAddr, TcpListener};
692 /// SocketAddr::from(([127, 0, 0, 1], 80)),
693 /// SocketAddr::from(([127, 0, 0, 1], 443)),
695 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
697 #[stable(feature = "rust1", since = "1.0.0")]
698 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
699 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
702 /// Returns the local socket address of this listener.
707 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
709 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
710 /// assert_eq!(listener.local_addr().unwrap(),
711 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
713 #[stable(feature = "rust1", since = "1.0.0")]
714 pub fn local_addr(&self) -> io::Result<SocketAddr> {
718 /// Creates a new independently owned handle to the underlying socket.
720 /// The returned [`TcpListener`] is a reference to the same socket that this
721 /// object references. Both handles can be used to accept incoming
722 /// connections and options set on one listener will affect the other.
724 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
729 /// use std::net::TcpListener;
731 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
732 /// let listener_clone = listener.try_clone().unwrap();
734 #[stable(feature = "rust1", since = "1.0.0")]
735 pub fn try_clone(&self) -> io::Result<TcpListener> {
736 self.0.duplicate().map(TcpListener)
739 /// Accept a new incoming connection from this listener.
741 /// This function will block the calling thread until a new TCP connection
742 /// is established. When established, the corresponding [`TcpStream`] and the
743 /// remote peer's address will be returned.
745 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
750 /// use std::net::TcpListener;
752 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
753 /// match listener.accept() {
754 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
755 /// Err(e) => println!("couldn't get client: {:?}", e),
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
760 // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
761 // the `a` variable here is technically unused.
762 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
763 self.0.accept().map(|(a, b)| (TcpStream(a), b))
766 /// Returns an iterator over the connections being received on this
769 /// The returned iterator will never return [`None`] and will also not yield
770 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
771 /// calling [`accept`] in a loop.
773 /// [`None`]: ../../std/option/enum.Option.html#variant.None
774 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
775 /// [`accept`]: #method.accept
780 /// use std::net::TcpListener;
782 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
784 /// for stream in listener.incoming() {
787 /// println!("new client!");
789 /// Err(e) => { /* connection failed */ }
793 #[stable(feature = "rust1", since = "1.0.0")]
794 pub fn incoming(&self) -> Incoming<'_> {
795 Incoming { listener: self }
798 /// Sets the value for the `IP_TTL` option on this socket.
800 /// This value sets the time-to-live field that is used in every packet sent
801 /// from this socket.
806 /// use std::net::TcpListener;
808 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
809 /// listener.set_ttl(100).expect("could not set TTL");
811 #[stable(feature = "net2_mutators", since = "1.9.0")]
812 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
816 /// Gets the value of the `IP_TTL` option for this socket.
818 /// For more information about this option, see [`set_ttl`][link].
820 /// [link]: #method.set_ttl
825 /// use std::net::TcpListener;
827 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
828 /// listener.set_ttl(100).expect("could not set TTL");
829 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
831 #[stable(feature = "net2_mutators", since = "1.9.0")]
832 pub fn ttl(&self) -> io::Result<u32> {
836 #[stable(feature = "net2_mutators", since = "1.9.0")]
839 reason = "this option can only be set before the socket is bound"
841 #[allow(missing_docs)]
842 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
843 self.0.set_only_v6(only_v6)
846 #[stable(feature = "net2_mutators", since = "1.9.0")]
849 reason = "this option can only be set before the socket is bound"
851 #[allow(missing_docs)]
852 pub fn only_v6(&self) -> io::Result<bool> {
856 /// Gets the value of the `SO_ERROR` option on this socket.
858 /// This will retrieve the stored error in the underlying socket, clearing
859 /// the field in the process. This can be useful for checking errors between
865 /// use std::net::TcpListener;
867 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
868 /// listener.take_error().expect("No error was expected");
870 #[stable(feature = "net2_mutators", since = "1.9.0")]
871 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
875 /// Moves this TCP stream into or out of nonblocking mode.
877 /// This will result in the `accept` operation becoming nonblocking,
878 /// i.e., immediately returning from their calls. If the IO operation is
879 /// successful, `Ok` is returned and no further action is required. If the
880 /// IO operation could not be completed and needs to be retried, an error
881 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
883 /// On Unix platforms, calling this method corresponds to calling `fcntl`
884 /// `FIONBIO`. On Windows calling this method corresponds to calling
885 /// `ioctlsocket` `FIONBIO`.
889 /// Bind a TCP listener to an address, listen for connections, and read
890 /// bytes in nonblocking mode:
894 /// use std::net::TcpListener;
896 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
897 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
899 /// # fn wait_for_fd() { unimplemented!() }
900 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
901 /// for stream in listener.incoming() {
904 /// // do something with the TcpStream
905 /// handle_connection(s);
907 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
908 /// // wait until network socket is ready, typically implemented
909 /// // via platform-specific APIs such as epoll or IOCP
913 /// Err(e) => panic!("encountered IO error: {}", e),
918 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
919 #[stable(feature = "net2_mutators", since = "1.9.0")]
920 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
921 self.0.set_nonblocking(nonblocking)
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<'a> Iterator for Incoming<'a> {
927 type Item = io::Result<TcpStream>;
928 fn next(&mut self) -> Option<io::Result<TcpStream>> {
929 Some(self.listener.accept().map(|p| p.0))
933 impl AsInner<net_imp::TcpListener> for TcpListener {
934 fn as_inner(&self) -> &net_imp::TcpListener {
939 impl FromInner<net_imp::TcpListener> for TcpListener {
940 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
945 impl IntoInner<net_imp::TcpListener> for TcpListener {
946 fn into_inner(self) -> net_imp::TcpListener {
951 #[stable(feature = "rust1", since = "1.0.0")]
952 impl fmt::Debug for TcpListener {
953 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
958 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
961 use crate::io::prelude::*;
962 use crate::io::{ErrorKind, IoSlice, IoSliceMut};
963 use crate::net::test::{next_test_ip4, next_test_ip6};
965 use crate::sync::mpsc::channel;
967 use crate::time::{Duration, Instant};
969 fn each_ip(f: &mut dyn FnMut(SocketAddr)) {
978 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
985 match TcpListener::bind("1.1.1.1:9999") {
987 Err(e) => assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
993 match TcpStream::connect("0.0.0.0:1") {
996 e.kind() == ErrorKind::ConnectionRefused
997 || e.kind() == ErrorKind::InvalidInput
998 || e.kind() == ErrorKind::AddrInUse
999 || e.kind() == ErrorKind::AddrNotAvailable,
1000 "bad error: {} {:?}",
1008 fn listen_localhost() {
1009 let socket_addr = next_test_ip4();
1010 let listener = t!(TcpListener::bind(&socket_addr));
1012 let _t = thread::spawn(move || {
1013 let mut stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
1014 t!(stream.write(&[144]));
1017 let mut stream = t!(listener.accept()).0;
1019 t!(stream.read(&mut buf));
1020 assert!(buf[0] == 144);
1024 fn connect_loopback() {
1025 each_ip(&mut |addr| {
1026 let acceptor = t!(TcpListener::bind(&addr));
1028 let _t = thread::spawn(move || {
1029 let host = match addr {
1030 SocketAddr::V4(..) => "127.0.0.1",
1031 SocketAddr::V6(..) => "::1",
1033 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
1034 t!(stream.write(&[66]));
1037 let mut stream = t!(acceptor.accept()).0;
1039 t!(stream.read(&mut buf));
1040 assert!(buf[0] == 66);
1046 each_ip(&mut |addr| {
1047 let acceptor = t!(TcpListener::bind(&addr));
1049 let (tx, rx) = channel();
1050 let _t = thread::spawn(move || {
1051 let mut stream = t!(TcpStream::connect(&addr));
1052 t!(stream.write(&[99]));
1053 tx.send(t!(stream.local_addr())).unwrap();
1056 let (mut stream, addr) = t!(acceptor.accept());
1058 t!(stream.read(&mut buf));
1059 assert!(buf[0] == 99);
1060 assert_eq!(addr, t!(rx.recv()));
1066 each_ip(&mut |addr| {
1067 let acceptor = t!(TcpListener::bind(&addr));
1069 let _t = thread::spawn(move || {
1070 let _stream = t!(TcpStream::connect(&addr));
1074 let mut stream = t!(acceptor.accept()).0;
1076 let nread = t!(stream.read(&mut buf));
1077 assert_eq!(nread, 0);
1078 let nread = t!(stream.read(&mut buf));
1079 assert_eq!(nread, 0);
1085 each_ip(&mut |addr| {
1086 let acceptor = t!(TcpListener::bind(&addr));
1088 let (tx, rx) = channel();
1089 let _t = thread::spawn(move || {
1090 drop(t!(TcpStream::connect(&addr)));
1091 tx.send(()).unwrap();
1094 let mut stream = t!(acceptor.accept()).0;
1097 match stream.write(&buf) {
1101 e.kind() == ErrorKind::ConnectionReset
1102 || e.kind() == ErrorKind::BrokenPipe
1103 || e.kind() == ErrorKind::ConnectionAborted,
1104 "unknown error: {}",
1113 fn multiple_connect_serial() {
1114 each_ip(&mut |addr| {
1116 let acceptor = t!(TcpListener::bind(&addr));
1118 let _t = thread::spawn(move || {
1120 let mut stream = t!(TcpStream::connect(&addr));
1121 t!(stream.write(&[99]));
1125 for stream in acceptor.incoming().take(max) {
1126 let mut stream = t!(stream);
1128 t!(stream.read(&mut buf));
1129 assert_eq!(buf[0], 99);
1135 fn multiple_connect_interleaved_greedy_schedule() {
1136 const MAX: usize = 10;
1137 each_ip(&mut |addr| {
1138 let acceptor = t!(TcpListener::bind(&addr));
1140 let _t = thread::spawn(move || {
1141 let acceptor = acceptor;
1142 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
1143 // Start another thread to handle the connection
1144 let _t = thread::spawn(move || {
1145 let mut stream = t!(stream);
1147 t!(stream.read(&mut buf));
1148 assert!(buf[0] == i as u8);
1156 fn connect(i: usize, addr: SocketAddr) {
1161 let t = thread::spawn(move || {
1162 let mut stream = t!(TcpStream::connect(&addr));
1163 // Connect again before writing
1164 connect(i + 1, addr);
1165 t!(stream.write(&[i as u8]));
1167 t.join().ok().expect("thread panicked");
1172 fn multiple_connect_interleaved_lazy_schedule() {
1173 const MAX: usize = 10;
1174 each_ip(&mut |addr| {
1175 let acceptor = t!(TcpListener::bind(&addr));
1177 let _t = thread::spawn(move || {
1178 for stream in acceptor.incoming().take(MAX) {
1179 // Start another thread to handle the connection
1180 let _t = thread::spawn(move || {
1181 let mut stream = t!(stream);
1183 t!(stream.read(&mut buf));
1184 assert!(buf[0] == 99);
1192 fn connect(i: usize, addr: SocketAddr) {
1197 let t = thread::spawn(move || {
1198 let mut stream = t!(TcpStream::connect(&addr));
1199 connect(i + 1, addr);
1200 t!(stream.write(&[99]));
1202 t.join().ok().expect("thread panicked");
1207 fn socket_and_peer_name() {
1208 each_ip(&mut |addr| {
1209 let listener = t!(TcpListener::bind(&addr));
1210 let so_name = t!(listener.local_addr());
1211 assert_eq!(addr, so_name);
1212 let _t = thread::spawn(move || {
1213 t!(listener.accept());
1216 let stream = t!(TcpStream::connect(&addr));
1217 assert_eq!(addr, t!(stream.peer_addr()));
1223 each_ip(&mut |addr| {
1224 let (tx, rx) = channel();
1225 let srv = t!(TcpListener::bind(&addr));
1226 let _t = thread::spawn(move || {
1227 let mut cl = t!(srv.accept()).0;
1228 cl.write(&[10]).unwrap();
1230 t!(cl.read(&mut b));
1231 tx.send(()).unwrap();
1234 let mut c = t!(TcpStream::connect(&addr));
1235 let mut b = [0; 10];
1236 assert_eq!(c.read(&mut b).unwrap(), 1);
1243 fn read_vectored() {
1244 each_ip(&mut |addr| {
1245 let srv = t!(TcpListener::bind(&addr));
1246 let mut s1 = t!(TcpStream::connect(&addr));
1247 let mut s2 = t!(srv.accept()).0;
1249 let len = s1.write(&[10, 11, 12]).unwrap();
1255 let len = t!(s2.read_vectored(&mut [
1256 IoSliceMut::new(&mut a),
1257 IoSliceMut::new(&mut b),
1258 IoSliceMut::new(&mut c)
1261 assert_eq!(b, [10]);
1262 // some implementations don't support readv, so we may only fill the first buffer
1263 assert!(len == 1 || c == [11, 12, 0]);
1268 fn write_vectored() {
1269 each_ip(&mut |addr| {
1270 let srv = t!(TcpListener::bind(&addr));
1271 let mut s1 = t!(TcpStream::connect(&addr));
1272 let mut s2 = t!(srv.accept()).0;
1277 t!(s1.write_vectored(&[IoSlice::new(&a), IoSlice::new(&b), IoSlice::new(&c)]));
1279 let mut buf = [0; 4];
1280 let len = t!(s2.read(&mut buf));
1281 // some implementations don't support writev, so we may only write the first buffer
1283 assert_eq!(buf, [10, 0, 0, 0]);
1286 assert_eq!(buf, [10, 11, 12, 0]);
1293 each_ip(&mut |addr| {
1294 let listener1 = t!(TcpListener::bind(&addr));
1295 match TcpListener::bind(&addr) {
1296 Ok(listener2) => panic!(
1297 "This system (perhaps due to options set by TcpListener::bind) \
1298 permits double binding: {:?} and {:?}",
1299 listener1, listener2
1303 e.kind() == ErrorKind::ConnectionRefused
1304 || e.kind() == ErrorKind::Other
1305 || e.kind() == ErrorKind::AddrInUse,
1306 "unknown error: {} {:?}",
1316 fn tcp_clone_smoke() {
1317 each_ip(&mut |addr| {
1318 let acceptor = t!(TcpListener::bind(&addr));
1320 let _t = thread::spawn(move || {
1321 let mut s = t!(TcpStream::connect(&addr));
1322 let mut buf = [0, 0];
1323 assert_eq!(s.read(&mut buf).unwrap(), 1);
1324 assert_eq!(buf[0], 1);
1328 let mut s1 = t!(acceptor.accept()).0;
1329 let s2 = t!(s1.try_clone());
1331 let (tx1, rx1) = channel();
1332 let (tx2, rx2) = channel();
1333 let _t = thread::spawn(move || {
1335 rx1.recv().unwrap();
1337 tx2.send(()).unwrap();
1339 tx1.send(()).unwrap();
1340 let mut buf = [0, 0];
1341 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1342 rx2.recv().unwrap();
1347 fn tcp_clone_two_read() {
1348 each_ip(&mut |addr| {
1349 let acceptor = t!(TcpListener::bind(&addr));
1350 let (tx1, rx) = channel();
1351 let tx2 = tx1.clone();
1353 let _t = thread::spawn(move || {
1354 let mut s = t!(TcpStream::connect(&addr));
1361 let mut s1 = t!(acceptor.accept()).0;
1362 let s2 = t!(s1.try_clone());
1364 let (done, rx) = channel();
1365 let _t = thread::spawn(move || {
1367 let mut buf = [0, 0];
1368 t!(s2.read(&mut buf));
1369 tx2.send(()).unwrap();
1370 done.send(()).unwrap();
1372 let mut buf = [0, 0];
1373 t!(s1.read(&mut buf));
1374 tx1.send(()).unwrap();
1381 fn tcp_clone_two_write() {
1382 each_ip(&mut |addr| {
1383 let acceptor = t!(TcpListener::bind(&addr));
1385 let _t = thread::spawn(move || {
1386 let mut s = t!(TcpStream::connect(&addr));
1387 let mut buf = [0, 1];
1388 t!(s.read(&mut buf));
1389 t!(s.read(&mut buf));
1392 let mut s1 = t!(acceptor.accept()).0;
1393 let s2 = t!(s1.try_clone());
1395 let (done, rx) = channel();
1396 let _t = thread::spawn(move || {
1399 done.send(()).unwrap();
1408 // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1409 #[cfg_attr(target_env = "sgx", ignore)]
1410 fn shutdown_smoke() {
1411 each_ip(&mut |addr| {
1412 let a = t!(TcpListener::bind(&addr));
1413 let _t = thread::spawn(move || {
1414 let mut c = t!(a.accept()).0;
1416 assert_eq!(c.read(&mut b).unwrap(), 0);
1420 let mut s = t!(TcpStream::connect(&addr));
1421 t!(s.shutdown(Shutdown::Write));
1422 assert!(s.write(&[1]).is_err());
1424 assert_eq!(t!(s.read(&mut b)), 1);
1425 assert_eq!(b[0], 1);
1430 // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1431 #[cfg_attr(target_env = "sgx", ignore)]
1432 fn close_readwrite_smoke() {
1433 each_ip(&mut |addr| {
1434 let a = t!(TcpListener::bind(&addr));
1435 let (tx, rx) = channel::<()>();
1436 let _t = thread::spawn(move || {
1437 let _s = t!(a.accept());
1442 let mut s = t!(TcpStream::connect(&addr));
1443 let mut s2 = t!(s.try_clone());
1445 // closing should prevent reads/writes
1446 t!(s.shutdown(Shutdown::Write));
1447 assert!(s.write(&[0]).is_err());
1448 t!(s.shutdown(Shutdown::Read));
1449 assert_eq!(s.read(&mut b).unwrap(), 0);
1451 // closing should affect previous handles
1452 assert!(s2.write(&[0]).is_err());
1453 assert_eq!(s2.read(&mut b).unwrap(), 0);
1455 // closing should affect new handles
1456 let mut s3 = t!(s.try_clone());
1457 assert!(s3.write(&[0]).is_err());
1458 assert_eq!(s3.read(&mut b).unwrap(), 0);
1460 // make sure these don't die
1461 let _ = s2.shutdown(Shutdown::Read);
1462 let _ = s2.shutdown(Shutdown::Write);
1463 let _ = s3.shutdown(Shutdown::Read);
1464 let _ = s3.shutdown(Shutdown::Write);
1470 #[cfg(unix)] // test doesn't work on Windows, see #31657
1471 fn close_read_wakes_up() {
1472 each_ip(&mut |addr| {
1473 let a = t!(TcpListener::bind(&addr));
1474 let (tx1, rx) = channel::<()>();
1475 let _t = thread::spawn(move || {
1476 let _s = t!(a.accept());
1480 let s = t!(TcpStream::connect(&addr));
1481 let s2 = t!(s.try_clone());
1482 let (tx, rx) = channel();
1483 let _t = thread::spawn(move || {
1485 assert_eq!(t!(s2.read(&mut [0])), 0);
1486 tx.send(()).unwrap();
1488 // this should wake up the child thread
1489 t!(s.shutdown(Shutdown::Read));
1491 // this test will never finish if the child doesn't wake up
1498 fn clone_while_reading() {
1499 each_ip(&mut |addr| {
1500 let accept = t!(TcpListener::bind(&addr));
1502 // Enqueue a thread to write to a socket
1503 let (tx, rx) = channel();
1504 let (txdone, rxdone) = channel();
1505 let txdone2 = txdone.clone();
1506 let _t = thread::spawn(move || {
1507 let mut tcp = t!(TcpStream::connect(&addr));
1509 t!(tcp.write(&[0]));
1510 txdone2.send(()).unwrap();
1513 // Spawn off a reading clone
1514 let tcp = t!(accept.accept()).0;
1515 let tcp2 = t!(tcp.try_clone());
1516 let txdone3 = txdone.clone();
1517 let _t = thread::spawn(move || {
1518 let mut tcp2 = tcp2;
1519 t!(tcp2.read(&mut [0]));
1520 txdone3.send(()).unwrap();
1523 // Try to ensure that the reading clone is indeed reading
1525 thread::yield_now();
1528 // clone the handle again while it's reading, then let it finish the
1530 let _ = t!(tcp.try_clone());
1531 tx.send(()).unwrap();
1532 rxdone.recv().unwrap();
1533 rxdone.recv().unwrap();
1538 fn clone_accept_smoke() {
1539 each_ip(&mut |addr| {
1540 let a = t!(TcpListener::bind(&addr));
1541 let a2 = t!(a.try_clone());
1543 let _t = thread::spawn(move || {
1544 let _ = TcpStream::connect(&addr);
1546 let _t = thread::spawn(move || {
1547 let _ = TcpStream::connect(&addr);
1556 fn clone_accept_concurrent() {
1557 each_ip(&mut |addr| {
1558 let a = t!(TcpListener::bind(&addr));
1559 let a2 = t!(a.try_clone());
1561 let (tx, rx) = channel();
1562 let tx2 = tx.clone();
1564 let _t = thread::spawn(move || {
1565 tx.send(t!(a.accept())).unwrap();
1567 let _t = thread::spawn(move || {
1568 tx2.send(t!(a2.accept())).unwrap();
1571 let _t = thread::spawn(move || {
1572 let _ = TcpStream::connect(&addr);
1574 let _t = thread::spawn(move || {
1575 let _ = TcpStream::connect(&addr);
1585 #[cfg(not(target_env = "sgx"))]
1586 fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1589 #[cfg(target_env = "sgx")]
1590 fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1594 #[cfg(target_env = "sgx")]
1595 use crate::os::fortanix_sgx::io::AsRawFd;
1597 use crate::os::unix::io::AsRawFd;
1598 #[cfg(not(windows))]
1599 fn render_inner(addr: &dyn AsRawFd) -> impl fmt::Debug {
1603 fn render_inner(addr: &dyn crate::os::windows::io::AsRawSocket) -> impl fmt::Debug {
1604 addr.as_raw_socket()
1607 let inner_name = if cfg!(windows) { "socket" } else { "fd" };
1608 let socket_addr = next_test_ip4();
1610 let listener = t!(TcpListener::bind(&socket_addr));
1611 let compare = format!(
1612 "TcpListener {{ addr: {:?}, {}: {:?} }}",
1613 render_socket_addr(&socket_addr),
1615 render_inner(&listener)
1617 assert_eq!(format!("{:?}", listener), compare);
1619 let stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
1620 let compare = format!(
1621 "TcpStream {{ addr: {:?}, peer: {:?}, {}: {:?} }}",
1622 render_socket_addr(&stream.local_addr().unwrap()),
1623 render_socket_addr(&stream.peer_addr().unwrap()),
1625 render_inner(&stream)
1627 assert_eq!(format!("{:?}", stream), compare);
1630 // FIXME: re-enabled openbsd tests once their socket timeout code
1631 // no longer has rounding errors.
1632 // VxWorks ignores SO_SNDTIMEO.
1633 #[cfg_attr(any(target_os = "netbsd", target_os = "openbsd", target_os = "vxworks"), ignore)]
1634 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1637 let addr = next_test_ip4();
1638 let listener = t!(TcpListener::bind(&addr));
1640 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1641 let dur = Duration::new(15410, 0);
1643 assert_eq!(None, t!(stream.read_timeout()));
1645 t!(stream.set_read_timeout(Some(dur)));
1646 assert_eq!(Some(dur), t!(stream.read_timeout()));
1648 assert_eq!(None, t!(stream.write_timeout()));
1650 t!(stream.set_write_timeout(Some(dur)));
1651 assert_eq!(Some(dur), t!(stream.write_timeout()));
1653 t!(stream.set_read_timeout(None));
1654 assert_eq!(None, t!(stream.read_timeout()));
1656 t!(stream.set_write_timeout(None));
1657 assert_eq!(None, t!(stream.write_timeout()));
1662 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1663 fn test_read_timeout() {
1664 let addr = next_test_ip4();
1665 let listener = t!(TcpListener::bind(&addr));
1667 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1668 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1670 let mut buf = [0; 10];
1671 let start = Instant::now();
1672 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1674 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1675 "unexpected_error: {:?}",
1678 assert!(start.elapsed() > Duration::from_millis(400));
1683 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1684 fn test_read_with_timeout() {
1685 let addr = next_test_ip4();
1686 let listener = t!(TcpListener::bind(&addr));
1688 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1689 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1691 let mut other_end = t!(listener.accept()).0;
1692 t!(other_end.write_all(b"hello world"));
1694 let mut buf = [0; 11];
1695 t!(stream.read(&mut buf));
1696 assert_eq!(b"hello world", &buf[..]);
1698 let start = Instant::now();
1699 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1701 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1702 "unexpected_error: {:?}",
1705 assert!(start.elapsed() > Duration::from_millis(400));
1709 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1710 // when passed zero Durations
1712 fn test_timeout_zero_duration() {
1713 let addr = next_test_ip4();
1715 let listener = t!(TcpListener::bind(&addr));
1716 let stream = t!(TcpStream::connect(&addr));
1718 let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1719 let err = result.unwrap_err();
1720 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1722 let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1723 let err = result.unwrap_err();
1724 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1730 #[cfg_attr(target_env = "sgx", ignore)]
1732 let addr = next_test_ip4();
1733 let _listener = t!(TcpListener::bind(&addr));
1735 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1737 assert_eq!(false, t!(stream.nodelay()));
1738 t!(stream.set_nodelay(true));
1739 assert_eq!(true, t!(stream.nodelay()));
1740 t!(stream.set_nodelay(false));
1741 assert_eq!(false, t!(stream.nodelay()));
1745 #[cfg_attr(target_env = "sgx", ignore)]
1749 let addr = next_test_ip4();
1750 let listener = t!(TcpListener::bind(&addr));
1752 t!(listener.set_ttl(ttl));
1753 assert_eq!(ttl, t!(listener.ttl()));
1755 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1757 t!(stream.set_ttl(ttl));
1758 assert_eq!(ttl, t!(stream.ttl()));
1762 #[cfg_attr(target_env = "sgx", ignore)]
1763 fn set_nonblocking() {
1764 let addr = next_test_ip4();
1765 let listener = t!(TcpListener::bind(&addr));
1767 t!(listener.set_nonblocking(true));
1768 t!(listener.set_nonblocking(false));
1770 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1772 t!(stream.set_nonblocking(false));
1773 t!(stream.set_nonblocking(true));
1776 match stream.read(&mut buf) {
1777 Ok(_) => panic!("expected error"),
1778 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1779 Err(e) => panic!("unexpected error {}", e),
1784 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1786 each_ip(&mut |addr| {
1787 let (txdone, rxdone) = channel();
1789 let srv = t!(TcpListener::bind(&addr));
1790 let _t = thread::spawn(move || {
1791 let mut cl = t!(srv.accept()).0;
1792 cl.write(&[1, 3, 3, 7]).unwrap();
1796 let mut c = t!(TcpStream::connect(&addr));
1797 let mut b = [0; 10];
1799 let len = c.peek(&mut b).unwrap();
1802 let len = c.read(&mut b).unwrap();
1805 t!(c.set_nonblocking(true));
1806 match c.peek(&mut b) {
1807 Ok(_) => panic!("expected error"),
1808 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1809 Err(e) => panic!("unexpected error {}", e),
1811 t!(txdone.send(()));
1816 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1817 fn connect_timeout_valid() {
1818 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1819 let addr = listener.local_addr().unwrap();
1820 TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();