1 #![deny(unsafe_op_in_unsafe_fn)]
2 use crate::io::prelude::*;
5 use crate::io::{self, Initializer, IoSlice, IoSliceMut};
6 use crate::net::{Shutdown, SocketAddr, ToSocketAddrs};
7 use crate::sys_common::net as net_imp;
8 use crate::sys_common::{AsInner, FromInner, IntoInner};
9 use crate::time::Duration;
11 /// A TCP stream between a local and a remote socket.
13 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
14 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
15 /// by [reading] and [writing] to it.
17 /// The connection will be closed when the value is dropped. The reading and writing
18 /// portions of the connection can also be shut down individually with the [`shutdown`]
21 /// The Transmission Control Protocol is specified in [IETF RFC 793].
23 /// [`accept`]: TcpListener::accept
24 /// [`connect`]: TcpStream::connect
25 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
27 /// [`shutdown`]: TcpStream::shutdown
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`]: TcpListener::accept
58 /// [`bind`]: TcpListener::bind
59 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
64 /// use std::net::{TcpListener, TcpStream};
66 /// fn handle_client(stream: TcpStream) {
70 /// fn main() -> std::io::Result<()> {
71 /// let listener = TcpListener::bind("127.0.0.1:80")?;
73 /// // accept connections and process them serially
74 /// for stream in listener.incoming() {
75 /// handle_client(stream?);
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub struct TcpListener(net_imp::TcpListener);
83 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
85 /// This `struct` is created by the [`TcpListener::incoming`] method.
86 /// See its documentation for more.
88 /// [`accept`]: TcpListener::accept
89 #[stable(feature = "rust1", since = "1.0.0")]
91 pub struct Incoming<'a> {
92 listener: &'a TcpListener,
96 /// Opens a TCP connection to a remote host.
98 /// `addr` is an address of the remote host. Anything which implements
99 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
100 /// documentation for concrete examples.
102 /// If `addr` yields multiple addresses, `connect` will be attempted with
103 /// each of the addresses until a connection is successful. If none of
104 /// the addresses result in a successful connection, the error returned from
105 /// the last connection attempt (the last address) is returned.
109 /// Open a TCP connection to `127.0.0.1:8080`:
112 /// use std::net::TcpStream;
114 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
115 /// println!("Connected to the server!");
117 /// println!("Couldn't connect to server...");
121 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
122 /// a TCP connection to `127.0.0.1:8081`:
125 /// use std::net::{SocketAddr, TcpStream};
128 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
129 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
131 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
132 /// println!("Connected to the server!");
134 /// println!("Couldn't connect to server...");
137 #[stable(feature = "rust1", since = "1.0.0")]
138 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
139 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
142 /// Opens a TCP connection to a remote host with a timeout.
144 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
145 /// timeout must be applied to individual addresses.
147 /// It is an error to pass a zero `Duration` to this function.
149 /// Unlike other methods on `TcpStream`, this does not correspond to a
150 /// single system call. It instead calls `connect` in nonblocking mode and
151 /// then uses an OS-specific mechanism to await the completion of the
152 /// connection request.
153 #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
154 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
155 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
158 /// Returns the socket address of the remote peer of this TCP connection.
163 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
165 /// let stream = TcpStream::connect("127.0.0.1:8080")
166 /// .expect("Couldn't connect to the server...");
167 /// assert_eq!(stream.peer_addr().unwrap(),
168 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
175 /// Returns the socket address of the local half of this TCP connection.
180 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
182 /// let stream = TcpStream::connect("127.0.0.1:8080")
183 /// .expect("Couldn't connect to the server...");
184 /// assert_eq!(stream.local_addr().unwrap().ip(),
185 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn local_addr(&self) -> io::Result<SocketAddr> {
192 /// Shuts down the read, write, or both halves of this connection.
194 /// This function will cause all pending and future I/O on the specified
195 /// portions to return immediately with an appropriate value (see the
196 /// documentation of [`Shutdown`]).
198 /// # Platform-specific behavior
200 /// Calling this function multiple times may result in different behavior,
201 /// depending on the operating system. On Linux, the second call will
202 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
203 /// This may change in the future.
208 /// use std::net::{Shutdown, TcpStream};
210 /// let stream = TcpStream::connect("127.0.0.1:8080")
211 /// .expect("Couldn't connect to the server...");
212 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
214 #[stable(feature = "rust1", since = "1.0.0")]
215 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
219 /// Creates a new independently owned handle to the underlying socket.
221 /// The returned `TcpStream` is a reference to the same stream that this
222 /// object references. Both handles will read and write the same stream of
223 /// data, and options set on one stream will be propagated to the other
229 /// use std::net::TcpStream;
231 /// let stream = TcpStream::connect("127.0.0.1:8080")
232 /// .expect("Couldn't connect to the server...");
233 /// let stream_clone = stream.try_clone().expect("clone failed...");
235 #[stable(feature = "rust1", since = "1.0.0")]
236 pub fn try_clone(&self) -> io::Result<TcpStream> {
237 self.0.duplicate().map(TcpStream)
240 /// Sets the read timeout to the timeout specified.
242 /// If the value specified is [`None`], then [`read`] calls will block
243 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
244 /// passed to this method.
246 /// # Platform-specific behavior
248 /// Platforms may return a different error code whenever a read times out as
249 /// a result of setting this option. For example Unix typically returns an
250 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
252 /// [`read`]: Read::read
253 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
254 /// [`TimedOut`]: io::ErrorKind::TimedOut
259 /// use std::net::TcpStream;
261 /// let stream = TcpStream::connect("127.0.0.1:8080")
262 /// .expect("Couldn't connect to the server...");
263 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
266 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
271 /// use std::net::TcpStream;
272 /// use std::time::Duration;
274 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
275 /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
276 /// let err = result.unwrap_err();
277 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
279 #[stable(feature = "socket_timeout", since = "1.4.0")]
280 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
281 self.0.set_read_timeout(dur)
284 /// Sets the write timeout to the timeout specified.
286 /// If the value specified is [`None`], then [`write`] calls will block
287 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
288 /// passed to this method.
290 /// # Platform-specific behavior
292 /// Platforms may return a different error code whenever a write times out
293 /// as a result of setting this option. For example Unix typically returns
294 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
296 /// [`write`]: Write::write
297 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
298 /// [`TimedOut`]: io::ErrorKind::TimedOut
303 /// use std::net::TcpStream;
305 /// let stream = TcpStream::connect("127.0.0.1:8080")
306 /// .expect("Couldn't connect to the server...");
307 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
310 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
315 /// use std::net::TcpStream;
316 /// use std::time::Duration;
318 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
319 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
320 /// let err = result.unwrap_err();
321 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
323 #[stable(feature = "socket_timeout", since = "1.4.0")]
324 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
325 self.0.set_write_timeout(dur)
328 /// Returns the read timeout of this socket.
330 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
332 /// # Platform-specific behavior
334 /// Some platforms do not provide access to the current timeout.
336 /// [`read`]: Read::read
341 /// use std::net::TcpStream;
343 /// let stream = TcpStream::connect("127.0.0.1:8080")
344 /// .expect("Couldn't connect to the server...");
345 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
346 /// assert_eq!(stream.read_timeout().unwrap(), None);
348 #[stable(feature = "socket_timeout", since = "1.4.0")]
349 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
350 self.0.read_timeout()
353 /// Returns the write timeout of this socket.
355 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
357 /// # Platform-specific behavior
359 /// Some platforms do not provide access to the current timeout.
361 /// [`write`]: Write::write
366 /// use std::net::TcpStream;
368 /// let stream = TcpStream::connect("127.0.0.1:8080")
369 /// .expect("Couldn't connect to the server...");
370 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
371 /// assert_eq!(stream.write_timeout().unwrap(), None);
373 #[stable(feature = "socket_timeout", since = "1.4.0")]
374 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
375 self.0.write_timeout()
378 /// Receives data on the socket from the remote address to which it is
379 /// connected, without removing that data from the queue. On success,
380 /// returns the number of bytes peeked.
382 /// Successive calls return the same data. This is accomplished by passing
383 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
388 /// use std::net::TcpStream;
390 /// let stream = TcpStream::connect("127.0.0.1:8000")
391 /// .expect("couldn't bind to address");
392 /// let mut buf = [0; 10];
393 /// let len = stream.peek(&mut buf).expect("peek failed");
395 #[stable(feature = "peek", since = "1.18.0")]
396 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
400 /// Sets the value of the `TCP_NODELAY` option on this socket.
402 /// If set, this option disables the Nagle algorithm. This means that
403 /// segments are always sent as soon as possible, even if there is only a
404 /// small amount of data. When not set, data is buffered until there is a
405 /// sufficient amount to send out, thereby avoiding the frequent sending of
411 /// use std::net::TcpStream;
413 /// let stream = TcpStream::connect("127.0.0.1:8080")
414 /// .expect("Couldn't connect to the server...");
415 /// stream.set_nodelay(true).expect("set_nodelay call failed");
417 #[stable(feature = "net2_mutators", since = "1.9.0")]
418 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
419 self.0.set_nodelay(nodelay)
422 /// Gets the value of the `TCP_NODELAY` option on this socket.
424 /// For more information about this option, see [`TcpStream::set_nodelay`].
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");
434 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
436 #[stable(feature = "net2_mutators", since = "1.9.0")]
437 pub fn nodelay(&self) -> io::Result<bool> {
441 /// Sets the value for the `IP_TTL` option on this socket.
443 /// This value sets the time-to-live field that is used in every packet sent
444 /// from this socket.
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_ttl(100).expect("set_ttl call failed");
455 #[stable(feature = "net2_mutators", since = "1.9.0")]
456 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
460 /// Gets the value of the `IP_TTL` option for this socket.
462 /// For more information about this option, see [`TcpStream::set_ttl`].
467 /// use std::net::TcpStream;
469 /// let stream = TcpStream::connect("127.0.0.1:8080")
470 /// .expect("Couldn't connect to the server...");
471 /// stream.set_ttl(100).expect("set_ttl call failed");
472 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
474 #[stable(feature = "net2_mutators", since = "1.9.0")]
475 pub fn ttl(&self) -> io::Result<u32> {
479 /// Gets the value of the `SO_ERROR` option on this socket.
481 /// This will retrieve the stored error in the underlying socket, clearing
482 /// the field in the process. This can be useful for checking errors between
488 /// use std::net::TcpStream;
490 /// let stream = TcpStream::connect("127.0.0.1:8080")
491 /// .expect("Couldn't connect to the server...");
492 /// stream.take_error().expect("No error was expected...");
494 #[stable(feature = "net2_mutators", since = "1.9.0")]
495 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
499 /// Moves this TCP stream into or out of nonblocking mode.
501 /// This will result in `read`, `write`, `recv` and `send` operations
502 /// becoming nonblocking, i.e., immediately returning from their calls.
503 /// If the IO operation is successful, `Ok` is returned and no further
504 /// action is required. If the IO operation could not be completed and needs
505 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
508 /// On Unix platforms, calling this method corresponds to calling `fcntl`
509 /// `FIONBIO`. On Windows calling this method corresponds to calling
510 /// `ioctlsocket` `FIONBIO`.
514 /// Reading bytes from a TCP stream in non-blocking mode:
517 /// use std::io::{self, Read};
518 /// use std::net::TcpStream;
520 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
521 /// .expect("Couldn't connect to the server...");
522 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
524 /// # fn wait_for_fd() { unimplemented!() }
525 /// let mut buf = vec![];
527 /// match stream.read_to_end(&mut buf) {
529 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
530 /// // wait until network socket is ready, typically implemented
531 /// // via platform-specific APIs such as epoll or IOCP
534 /// Err(e) => panic!("encountered IO error: {}", e),
537 /// println!("bytes: {:?}", buf);
539 #[stable(feature = "net2_mutators", since = "1.9.0")]
540 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
541 self.0.set_nonblocking(nonblocking)
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl Read for TcpStream {
547 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
551 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
552 self.0.read_vectored(bufs)
556 fn is_read_vectored(&self) -> bool {
557 self.0.is_read_vectored()
561 unsafe fn initializer(&self) -> Initializer {
562 // SAFETY: Read is guaranteed to work on uninitialized memory
563 unsafe { Initializer::nop() }
566 #[stable(feature = "rust1", since = "1.0.0")]
567 impl Write for TcpStream {
568 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
572 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
573 self.0.write_vectored(bufs)
577 fn is_write_vectored(&self) -> bool {
578 self.0.is_write_vectored()
581 fn flush(&mut self) -> io::Result<()> {
585 #[stable(feature = "rust1", since = "1.0.0")]
586 impl Read for &TcpStream {
587 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
591 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
592 self.0.read_vectored(bufs)
596 fn is_read_vectored(&self) -> bool {
597 self.0.is_read_vectored()
601 unsafe fn initializer(&self) -> Initializer {
602 // SAFETY: Read is guaranteed to work on uninitialized memory
603 unsafe { Initializer::nop() }
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl Write for &TcpStream {
608 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
612 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
613 self.0.write_vectored(bufs)
617 fn is_write_vectored(&self) -> bool {
618 self.0.is_write_vectored()
621 fn flush(&mut self) -> io::Result<()> {
626 impl AsInner<net_imp::TcpStream> for TcpStream {
627 fn as_inner(&self) -> &net_imp::TcpStream {
632 impl FromInner<net_imp::TcpStream> for TcpStream {
633 fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
638 impl IntoInner<net_imp::TcpStream> for TcpStream {
639 fn into_inner(self) -> net_imp::TcpStream {
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl fmt::Debug for TcpStream {
646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652 /// Creates a new `TcpListener` which will be bound to the specified
655 /// The returned listener is ready for accepting connections.
657 /// Binding with a port number of 0 will request that the OS assigns a port
658 /// to this listener. The port allocated can be queried via the
659 /// [`TcpListener::local_addr`] method.
661 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
662 /// its documentation for concrete examples.
664 /// If `addr` yields multiple addresses, `bind` will be attempted with
665 /// each of the addresses until one succeeds and returns the listener. If
666 /// none of the addresses succeed in creating a listener, the error returned
667 /// from the last attempt (the last address) is returned.
671 /// Creates a TCP listener bound to `127.0.0.1:80`:
674 /// use std::net::TcpListener;
676 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
679 /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
680 /// TCP listener bound to `127.0.0.1:443`:
683 /// use std::net::{SocketAddr, TcpListener};
686 /// SocketAddr::from(([127, 0, 0, 1], 80)),
687 /// SocketAddr::from(([127, 0, 0, 1], 443)),
689 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
691 #[stable(feature = "rust1", since = "1.0.0")]
692 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
693 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
696 /// Returns the local socket address of this listener.
701 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
703 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
704 /// assert_eq!(listener.local_addr().unwrap(),
705 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub fn local_addr(&self) -> io::Result<SocketAddr> {
712 /// Creates a new independently owned handle to the underlying socket.
714 /// The returned [`TcpListener`] is a reference to the same socket that this
715 /// object references. Both handles can be used to accept incoming
716 /// connections and options set on one listener will affect the other.
721 /// use std::net::TcpListener;
723 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
724 /// let listener_clone = listener.try_clone().unwrap();
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn try_clone(&self) -> io::Result<TcpListener> {
728 self.0.duplicate().map(TcpListener)
731 /// Accept a new incoming connection from this listener.
733 /// This function will block the calling thread until a new TCP connection
734 /// is established. When established, the corresponding [`TcpStream`] and the
735 /// remote peer's address will be returned.
740 /// use std::net::TcpListener;
742 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
743 /// match listener.accept() {
744 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
745 /// Err(e) => println!("couldn't get client: {:?}", e),
748 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
750 // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
751 // the `a` variable here is technically unused.
752 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
753 self.0.accept().map(|(a, b)| (TcpStream(a), b))
756 /// Returns an iterator over the connections being received on this
759 /// The returned iterator will never return [`None`] and will also not yield
760 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
761 /// calling [`TcpListener::accept`] in a loop.
766 /// use std::net::TcpListener;
768 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
770 /// for stream in listener.incoming() {
773 /// println!("new client!");
775 /// Err(e) => { /* connection failed */ }
779 #[stable(feature = "rust1", since = "1.0.0")]
780 pub fn incoming(&self) -> Incoming<'_> {
781 Incoming { listener: self }
784 /// Sets the value for the `IP_TTL` option on this socket.
786 /// This value sets the time-to-live field that is used in every packet sent
787 /// from this socket.
792 /// use std::net::TcpListener;
794 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
795 /// listener.set_ttl(100).expect("could not set TTL");
797 #[stable(feature = "net2_mutators", since = "1.9.0")]
798 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
802 /// Gets the value of the `IP_TTL` option for this socket.
804 /// For more information about this option, see [`TcpListener::set_ttl`].
809 /// use std::net::TcpListener;
811 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
812 /// listener.set_ttl(100).expect("could not set TTL");
813 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
815 #[stable(feature = "net2_mutators", since = "1.9.0")]
816 pub fn ttl(&self) -> io::Result<u32> {
820 #[stable(feature = "net2_mutators", since = "1.9.0")]
823 reason = "this option can only be set before the socket is bound"
825 #[allow(missing_docs)]
826 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
827 self.0.set_only_v6(only_v6)
830 #[stable(feature = "net2_mutators", since = "1.9.0")]
833 reason = "this option can only be set before the socket is bound"
835 #[allow(missing_docs)]
836 pub fn only_v6(&self) -> io::Result<bool> {
840 /// Gets the value of the `SO_ERROR` option on this socket.
842 /// This will retrieve the stored error in the underlying socket, clearing
843 /// the field in the process. This can be useful for checking errors between
849 /// use std::net::TcpListener;
851 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
852 /// listener.take_error().expect("No error was expected");
854 #[stable(feature = "net2_mutators", since = "1.9.0")]
855 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
859 /// Moves this TCP stream into or out of nonblocking mode.
861 /// This will result in the `accept` operation becoming nonblocking,
862 /// i.e., immediately returning from their calls. If the IO operation is
863 /// successful, `Ok` is returned and no further action is required. If the
864 /// IO operation could not be completed and needs to be retried, an error
865 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
867 /// On Unix platforms, calling this method corresponds to calling `fcntl`
868 /// `FIONBIO`. On Windows calling this method corresponds to calling
869 /// `ioctlsocket` `FIONBIO`.
873 /// Bind a TCP listener to an address, listen for connections, and read
874 /// bytes in nonblocking mode:
878 /// use std::net::TcpListener;
880 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
881 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
883 /// # fn wait_for_fd() { unimplemented!() }
884 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
885 /// for stream in listener.incoming() {
888 /// // do something with the TcpStream
889 /// handle_connection(s);
891 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
892 /// // wait until network socket is ready, typically implemented
893 /// // via platform-specific APIs such as epoll or IOCP
897 /// Err(e) => panic!("encountered IO error: {}", e),
901 #[stable(feature = "net2_mutators", since = "1.9.0")]
902 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
903 self.0.set_nonblocking(nonblocking)
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl<'a> Iterator for Incoming<'a> {
909 type Item = io::Result<TcpStream>;
910 fn next(&mut self) -> Option<io::Result<TcpStream>> {
911 Some(self.listener.accept().map(|p| p.0))
915 impl AsInner<net_imp::TcpListener> for TcpListener {
916 fn as_inner(&self) -> &net_imp::TcpListener {
921 impl FromInner<net_imp::TcpListener> for TcpListener {
922 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
927 impl IntoInner<net_imp::TcpListener> for TcpListener {
928 fn into_inner(self) -> net_imp::TcpListener {
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl fmt::Debug for TcpListener {
935 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
940 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
943 use crate::io::prelude::*;
944 use crate::io::{ErrorKind, IoSlice, IoSliceMut};
945 use crate::net::test::{next_test_ip4, next_test_ip6};
947 use crate::sync::mpsc::channel;
949 use crate::time::{Duration, Instant};
951 fn each_ip(f: &mut dyn FnMut(SocketAddr)) {
960 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
967 match TcpListener::bind("1.1.1.1:9999") {
969 Err(e) => assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
975 match TcpStream::connect("0.0.0.0:1") {
978 e.kind() == ErrorKind::ConnectionRefused
979 || e.kind() == ErrorKind::InvalidInput
980 || e.kind() == ErrorKind::AddrInUse
981 || e.kind() == ErrorKind::AddrNotAvailable,
982 "bad error: {} {:?}",
990 fn listen_localhost() {
991 let socket_addr = next_test_ip4();
992 let listener = t!(TcpListener::bind(&socket_addr));
994 let _t = thread::spawn(move || {
995 let mut stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
996 t!(stream.write(&[144]));
999 let mut stream = t!(listener.accept()).0;
1001 t!(stream.read(&mut buf));
1002 assert!(buf[0] == 144);
1006 fn connect_loopback() {
1007 each_ip(&mut |addr| {
1008 let acceptor = t!(TcpListener::bind(&addr));
1010 let _t = thread::spawn(move || {
1011 let host = match addr {
1012 SocketAddr::V4(..) => "127.0.0.1",
1013 SocketAddr::V6(..) => "::1",
1015 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
1016 t!(stream.write(&[66]));
1019 let mut stream = t!(acceptor.accept()).0;
1021 t!(stream.read(&mut buf));
1022 assert!(buf[0] == 66);
1028 each_ip(&mut |addr| {
1029 let acceptor = t!(TcpListener::bind(&addr));
1031 let (tx, rx) = channel();
1032 let _t = thread::spawn(move || {
1033 let mut stream = t!(TcpStream::connect(&addr));
1034 t!(stream.write(&[99]));
1035 tx.send(t!(stream.local_addr())).unwrap();
1038 let (mut stream, addr) = t!(acceptor.accept());
1040 t!(stream.read(&mut buf));
1041 assert!(buf[0] == 99);
1042 assert_eq!(addr, t!(rx.recv()));
1048 each_ip(&mut |addr| {
1049 let acceptor = t!(TcpListener::bind(&addr));
1051 let _t = thread::spawn(move || {
1052 let _stream = t!(TcpStream::connect(&addr));
1056 let mut stream = t!(acceptor.accept()).0;
1058 let nread = t!(stream.read(&mut buf));
1059 assert_eq!(nread, 0);
1060 let nread = t!(stream.read(&mut buf));
1061 assert_eq!(nread, 0);
1067 each_ip(&mut |addr| {
1068 let acceptor = t!(TcpListener::bind(&addr));
1070 let (tx, rx) = channel();
1071 let _t = thread::spawn(move || {
1072 drop(t!(TcpStream::connect(&addr)));
1073 tx.send(()).unwrap();
1076 let mut stream = t!(acceptor.accept()).0;
1079 match stream.write(&buf) {
1083 e.kind() == ErrorKind::ConnectionReset
1084 || e.kind() == ErrorKind::BrokenPipe
1085 || e.kind() == ErrorKind::ConnectionAborted,
1086 "unknown error: {}",
1095 fn multiple_connect_serial() {
1096 each_ip(&mut |addr| {
1098 let acceptor = t!(TcpListener::bind(&addr));
1100 let _t = thread::spawn(move || {
1102 let mut stream = t!(TcpStream::connect(&addr));
1103 t!(stream.write(&[99]));
1107 for stream in acceptor.incoming().take(max) {
1108 let mut stream = t!(stream);
1110 t!(stream.read(&mut buf));
1111 assert_eq!(buf[0], 99);
1117 fn multiple_connect_interleaved_greedy_schedule() {
1118 const MAX: usize = 10;
1119 each_ip(&mut |addr| {
1120 let acceptor = t!(TcpListener::bind(&addr));
1122 let _t = thread::spawn(move || {
1123 let acceptor = acceptor;
1124 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
1125 // Start another thread to handle the connection
1126 let _t = thread::spawn(move || {
1127 let mut stream = t!(stream);
1129 t!(stream.read(&mut buf));
1130 assert!(buf[0] == i as u8);
1138 fn connect(i: usize, addr: SocketAddr) {
1143 let t = thread::spawn(move || {
1144 let mut stream = t!(TcpStream::connect(&addr));
1145 // Connect again before writing
1146 connect(i + 1, addr);
1147 t!(stream.write(&[i as u8]));
1149 t.join().ok().expect("thread panicked");
1154 fn multiple_connect_interleaved_lazy_schedule() {
1155 const MAX: usize = 10;
1156 each_ip(&mut |addr| {
1157 let acceptor = t!(TcpListener::bind(&addr));
1159 let _t = thread::spawn(move || {
1160 for stream in acceptor.incoming().take(MAX) {
1161 // Start another thread to handle the connection
1162 let _t = thread::spawn(move || {
1163 let mut stream = t!(stream);
1165 t!(stream.read(&mut buf));
1166 assert!(buf[0] == 99);
1174 fn connect(i: usize, addr: SocketAddr) {
1179 let t = thread::spawn(move || {
1180 let mut stream = t!(TcpStream::connect(&addr));
1181 connect(i + 1, addr);
1182 t!(stream.write(&[99]));
1184 t.join().ok().expect("thread panicked");
1189 fn socket_and_peer_name() {
1190 each_ip(&mut |addr| {
1191 let listener = t!(TcpListener::bind(&addr));
1192 let so_name = t!(listener.local_addr());
1193 assert_eq!(addr, so_name);
1194 let _t = thread::spawn(move || {
1195 t!(listener.accept());
1198 let stream = t!(TcpStream::connect(&addr));
1199 assert_eq!(addr, t!(stream.peer_addr()));
1205 each_ip(&mut |addr| {
1206 let (tx, rx) = channel();
1207 let srv = t!(TcpListener::bind(&addr));
1208 let _t = thread::spawn(move || {
1209 let mut cl = t!(srv.accept()).0;
1210 cl.write(&[10]).unwrap();
1212 t!(cl.read(&mut b));
1213 tx.send(()).unwrap();
1216 let mut c = t!(TcpStream::connect(&addr));
1217 let mut b = [0; 10];
1218 assert_eq!(c.read(&mut b).unwrap(), 1);
1225 fn read_vectored() {
1226 each_ip(&mut |addr| {
1227 let srv = t!(TcpListener::bind(&addr));
1228 let mut s1 = t!(TcpStream::connect(&addr));
1229 let mut s2 = t!(srv.accept()).0;
1231 let len = s1.write(&[10, 11, 12]).unwrap();
1237 let len = t!(s2.read_vectored(&mut [
1238 IoSliceMut::new(&mut a),
1239 IoSliceMut::new(&mut b),
1240 IoSliceMut::new(&mut c)
1243 assert_eq!(b, [10]);
1244 // some implementations don't support readv, so we may only fill the first buffer
1245 assert!(len == 1 || c == [11, 12, 0]);
1250 fn write_vectored() {
1251 each_ip(&mut |addr| {
1252 let srv = t!(TcpListener::bind(&addr));
1253 let mut s1 = t!(TcpStream::connect(&addr));
1254 let mut s2 = t!(srv.accept()).0;
1259 t!(s1.write_vectored(&[IoSlice::new(&a), IoSlice::new(&b), IoSlice::new(&c)]));
1261 let mut buf = [0; 4];
1262 let len = t!(s2.read(&mut buf));
1263 // some implementations don't support writev, so we may only write the first buffer
1265 assert_eq!(buf, [10, 0, 0, 0]);
1268 assert_eq!(buf, [10, 11, 12, 0]);
1275 each_ip(&mut |addr| {
1276 let listener1 = t!(TcpListener::bind(&addr));
1277 match TcpListener::bind(&addr) {
1278 Ok(listener2) => panic!(
1279 "This system (perhaps due to options set by TcpListener::bind) \
1280 permits double binding: {:?} and {:?}",
1281 listener1, listener2
1285 e.kind() == ErrorKind::ConnectionRefused
1286 || e.kind() == ErrorKind::Other
1287 || e.kind() == ErrorKind::AddrInUse,
1288 "unknown error: {} {:?}",
1298 fn tcp_clone_smoke() {
1299 each_ip(&mut |addr| {
1300 let acceptor = t!(TcpListener::bind(&addr));
1302 let _t = thread::spawn(move || {
1303 let mut s = t!(TcpStream::connect(&addr));
1304 let mut buf = [0, 0];
1305 assert_eq!(s.read(&mut buf).unwrap(), 1);
1306 assert_eq!(buf[0], 1);
1310 let mut s1 = t!(acceptor.accept()).0;
1311 let s2 = t!(s1.try_clone());
1313 let (tx1, rx1) = channel();
1314 let (tx2, rx2) = channel();
1315 let _t = thread::spawn(move || {
1317 rx1.recv().unwrap();
1319 tx2.send(()).unwrap();
1321 tx1.send(()).unwrap();
1322 let mut buf = [0, 0];
1323 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1324 rx2.recv().unwrap();
1329 fn tcp_clone_two_read() {
1330 each_ip(&mut |addr| {
1331 let acceptor = t!(TcpListener::bind(&addr));
1332 let (tx1, rx) = channel();
1333 let tx2 = tx1.clone();
1335 let _t = thread::spawn(move || {
1336 let mut s = t!(TcpStream::connect(&addr));
1343 let mut s1 = t!(acceptor.accept()).0;
1344 let s2 = t!(s1.try_clone());
1346 let (done, rx) = channel();
1347 let _t = thread::spawn(move || {
1349 let mut buf = [0, 0];
1350 t!(s2.read(&mut buf));
1351 tx2.send(()).unwrap();
1352 done.send(()).unwrap();
1354 let mut buf = [0, 0];
1355 t!(s1.read(&mut buf));
1356 tx1.send(()).unwrap();
1363 fn tcp_clone_two_write() {
1364 each_ip(&mut |addr| {
1365 let acceptor = t!(TcpListener::bind(&addr));
1367 let _t = thread::spawn(move || {
1368 let mut s = t!(TcpStream::connect(&addr));
1369 let mut buf = [0, 1];
1370 t!(s.read(&mut buf));
1371 t!(s.read(&mut buf));
1374 let mut s1 = t!(acceptor.accept()).0;
1375 let s2 = t!(s1.try_clone());
1377 let (done, rx) = channel();
1378 let _t = thread::spawn(move || {
1381 done.send(()).unwrap();
1390 // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1391 #[cfg_attr(target_env = "sgx", ignore)]
1392 fn shutdown_smoke() {
1393 each_ip(&mut |addr| {
1394 let a = t!(TcpListener::bind(&addr));
1395 let _t = thread::spawn(move || {
1396 let mut c = t!(a.accept()).0;
1398 assert_eq!(c.read(&mut b).unwrap(), 0);
1402 let mut s = t!(TcpStream::connect(&addr));
1403 t!(s.shutdown(Shutdown::Write));
1404 assert!(s.write(&[1]).is_err());
1406 assert_eq!(t!(s.read(&mut b)), 1);
1407 assert_eq!(b[0], 1);
1412 // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1413 #[cfg_attr(target_env = "sgx", ignore)]
1414 fn close_readwrite_smoke() {
1415 each_ip(&mut |addr| {
1416 let a = t!(TcpListener::bind(&addr));
1417 let (tx, rx) = channel::<()>();
1418 let _t = thread::spawn(move || {
1419 let _s = t!(a.accept());
1424 let mut s = t!(TcpStream::connect(&addr));
1425 let mut s2 = t!(s.try_clone());
1427 // closing should prevent reads/writes
1428 t!(s.shutdown(Shutdown::Write));
1429 assert!(s.write(&[0]).is_err());
1430 t!(s.shutdown(Shutdown::Read));
1431 assert_eq!(s.read(&mut b).unwrap(), 0);
1433 // closing should affect previous handles
1434 assert!(s2.write(&[0]).is_err());
1435 assert_eq!(s2.read(&mut b).unwrap(), 0);
1437 // closing should affect new handles
1438 let mut s3 = t!(s.try_clone());
1439 assert!(s3.write(&[0]).is_err());
1440 assert_eq!(s3.read(&mut b).unwrap(), 0);
1442 // make sure these don't die
1443 let _ = s2.shutdown(Shutdown::Read);
1444 let _ = s2.shutdown(Shutdown::Write);
1445 let _ = s3.shutdown(Shutdown::Read);
1446 let _ = s3.shutdown(Shutdown::Write);
1452 #[cfg(unix)] // test doesn't work on Windows, see #31657
1453 fn close_read_wakes_up() {
1454 each_ip(&mut |addr| {
1455 let a = t!(TcpListener::bind(&addr));
1456 let (tx1, rx) = channel::<()>();
1457 let _t = thread::spawn(move || {
1458 let _s = t!(a.accept());
1462 let s = t!(TcpStream::connect(&addr));
1463 let s2 = t!(s.try_clone());
1464 let (tx, rx) = channel();
1465 let _t = thread::spawn(move || {
1467 assert_eq!(t!(s2.read(&mut [0])), 0);
1468 tx.send(()).unwrap();
1470 // this should wake up the child thread
1471 t!(s.shutdown(Shutdown::Read));
1473 // this test will never finish if the child doesn't wake up
1480 fn clone_while_reading() {
1481 each_ip(&mut |addr| {
1482 let accept = t!(TcpListener::bind(&addr));
1484 // Enqueue a thread to write to a socket
1485 let (tx, rx) = channel();
1486 let (txdone, rxdone) = channel();
1487 let txdone2 = txdone.clone();
1488 let _t = thread::spawn(move || {
1489 let mut tcp = t!(TcpStream::connect(&addr));
1491 t!(tcp.write(&[0]));
1492 txdone2.send(()).unwrap();
1495 // Spawn off a reading clone
1496 let tcp = t!(accept.accept()).0;
1497 let tcp2 = t!(tcp.try_clone());
1498 let txdone3 = txdone.clone();
1499 let _t = thread::spawn(move || {
1500 let mut tcp2 = tcp2;
1501 t!(tcp2.read(&mut [0]));
1502 txdone3.send(()).unwrap();
1505 // Try to ensure that the reading clone is indeed reading
1507 thread::yield_now();
1510 // clone the handle again while it's reading, then let it finish the
1512 let _ = t!(tcp.try_clone());
1513 tx.send(()).unwrap();
1514 rxdone.recv().unwrap();
1515 rxdone.recv().unwrap();
1520 fn clone_accept_smoke() {
1521 each_ip(&mut |addr| {
1522 let a = t!(TcpListener::bind(&addr));
1523 let a2 = t!(a.try_clone());
1525 let _t = thread::spawn(move || {
1526 let _ = TcpStream::connect(&addr);
1528 let _t = thread::spawn(move || {
1529 let _ = TcpStream::connect(&addr);
1538 fn clone_accept_concurrent() {
1539 each_ip(&mut |addr| {
1540 let a = t!(TcpListener::bind(&addr));
1541 let a2 = t!(a.try_clone());
1543 let (tx, rx) = channel();
1544 let tx2 = tx.clone();
1546 let _t = thread::spawn(move || {
1547 tx.send(t!(a.accept())).unwrap();
1549 let _t = thread::spawn(move || {
1550 tx2.send(t!(a2.accept())).unwrap();
1553 let _t = thread::spawn(move || {
1554 let _ = TcpStream::connect(&addr);
1556 let _t = thread::spawn(move || {
1557 let _ = TcpStream::connect(&addr);
1567 #[cfg(not(target_env = "sgx"))]
1568 fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1571 #[cfg(target_env = "sgx")]
1572 fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1576 #[cfg(target_env = "sgx")]
1577 use crate::os::fortanix_sgx::io::AsRawFd;
1579 use crate::os::unix::io::AsRawFd;
1580 #[cfg(not(windows))]
1581 fn render_inner(addr: &dyn AsRawFd) -> impl fmt::Debug {
1585 fn render_inner(addr: &dyn crate::os::windows::io::AsRawSocket) -> impl fmt::Debug {
1586 addr.as_raw_socket()
1589 let inner_name = if cfg!(windows) { "socket" } else { "fd" };
1590 let socket_addr = next_test_ip4();
1592 let listener = t!(TcpListener::bind(&socket_addr));
1593 let compare = format!(
1594 "TcpListener {{ addr: {:?}, {}: {:?} }}",
1595 render_socket_addr(&socket_addr),
1597 render_inner(&listener)
1599 assert_eq!(format!("{:?}", listener), compare);
1601 let stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
1602 let compare = format!(
1603 "TcpStream {{ addr: {:?}, peer: {:?}, {}: {:?} }}",
1604 render_socket_addr(&stream.local_addr().unwrap()),
1605 render_socket_addr(&stream.peer_addr().unwrap()),
1607 render_inner(&stream)
1609 assert_eq!(format!("{:?}", stream), compare);
1612 // FIXME: re-enabled openbsd tests once their socket timeout code
1613 // no longer has rounding errors.
1614 // VxWorks ignores SO_SNDTIMEO.
1615 #[cfg_attr(any(target_os = "netbsd", target_os = "openbsd", target_os = "vxworks"), ignore)]
1616 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1619 let addr = next_test_ip4();
1620 let listener = t!(TcpListener::bind(&addr));
1622 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1623 let dur = Duration::new(15410, 0);
1625 assert_eq!(None, t!(stream.read_timeout()));
1627 t!(stream.set_read_timeout(Some(dur)));
1628 assert_eq!(Some(dur), t!(stream.read_timeout()));
1630 assert_eq!(None, t!(stream.write_timeout()));
1632 t!(stream.set_write_timeout(Some(dur)));
1633 assert_eq!(Some(dur), t!(stream.write_timeout()));
1635 t!(stream.set_read_timeout(None));
1636 assert_eq!(None, t!(stream.read_timeout()));
1638 t!(stream.set_write_timeout(None));
1639 assert_eq!(None, t!(stream.write_timeout()));
1644 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1645 fn test_read_timeout() {
1646 let addr = next_test_ip4();
1647 let listener = t!(TcpListener::bind(&addr));
1649 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1650 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1652 let mut buf = [0; 10];
1653 let start = Instant::now();
1654 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1656 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1657 "unexpected_error: {:?}",
1660 assert!(start.elapsed() > Duration::from_millis(400));
1665 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1666 fn test_read_with_timeout() {
1667 let addr = next_test_ip4();
1668 let listener = t!(TcpListener::bind(&addr));
1670 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1671 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1673 let mut other_end = t!(listener.accept()).0;
1674 t!(other_end.write_all(b"hello world"));
1676 let mut buf = [0; 11];
1677 t!(stream.read(&mut buf));
1678 assert_eq!(b"hello world", &buf[..]);
1680 let start = Instant::now();
1681 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1683 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1684 "unexpected_error: {:?}",
1687 assert!(start.elapsed() > Duration::from_millis(400));
1691 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1692 // when passed zero Durations
1694 fn test_timeout_zero_duration() {
1695 let addr = next_test_ip4();
1697 let listener = t!(TcpListener::bind(&addr));
1698 let stream = t!(TcpStream::connect(&addr));
1700 let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1701 let err = result.unwrap_err();
1702 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1704 let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1705 let err = result.unwrap_err();
1706 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1712 #[cfg_attr(target_env = "sgx", ignore)]
1714 let addr = next_test_ip4();
1715 let _listener = t!(TcpListener::bind(&addr));
1717 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1719 assert_eq!(false, t!(stream.nodelay()));
1720 t!(stream.set_nodelay(true));
1721 assert_eq!(true, t!(stream.nodelay()));
1722 t!(stream.set_nodelay(false));
1723 assert_eq!(false, t!(stream.nodelay()));
1727 #[cfg_attr(target_env = "sgx", ignore)]
1731 let addr = next_test_ip4();
1732 let listener = t!(TcpListener::bind(&addr));
1734 t!(listener.set_ttl(ttl));
1735 assert_eq!(ttl, t!(listener.ttl()));
1737 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1739 t!(stream.set_ttl(ttl));
1740 assert_eq!(ttl, t!(stream.ttl()));
1744 #[cfg_attr(target_env = "sgx", ignore)]
1745 fn set_nonblocking() {
1746 let addr = next_test_ip4();
1747 let listener = t!(TcpListener::bind(&addr));
1749 t!(listener.set_nonblocking(true));
1750 t!(listener.set_nonblocking(false));
1752 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1754 t!(stream.set_nonblocking(false));
1755 t!(stream.set_nonblocking(true));
1758 match stream.read(&mut buf) {
1759 Ok(_) => panic!("expected error"),
1760 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1761 Err(e) => panic!("unexpected error {}", e),
1766 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1768 each_ip(&mut |addr| {
1769 let (txdone, rxdone) = channel();
1771 let srv = t!(TcpListener::bind(&addr));
1772 let _t = thread::spawn(move || {
1773 let mut cl = t!(srv.accept()).0;
1774 cl.write(&[1, 3, 3, 7]).unwrap();
1778 let mut c = t!(TcpStream::connect(&addr));
1779 let mut b = [0; 10];
1781 let len = c.peek(&mut b).unwrap();
1784 let len = c.read(&mut b).unwrap();
1787 t!(c.set_nonblocking(true));
1788 match c.peek(&mut b) {
1789 Ok(_) => panic!("expected error"),
1790 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1791 Err(e) => panic!("unexpected error {}", e),
1793 t!(txdone.send(()));
1798 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1799 fn connect_timeout_valid() {
1800 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1801 let addr = listener.local_addr().unwrap();
1802 TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();