1 use crate::io::prelude::*;
4 use crate::io::{self, Initializer, IoVec, IoVecMut};
5 use crate::net::{ToSocketAddrs, SocketAddr, Shutdown};
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> { listener: &'a TcpListener }
99 /// Opens a TCP connection to a remote host.
101 /// `addr` is an address of the remote host. Anything which implements
102 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
103 /// documentation for concrete examples.
105 /// If `addr` yields multiple addresses, `connect` will be attempted with
106 /// each of the addresses until a connection is successful. If none of
107 /// the addresses result in a successful connection, the error returned from
108 /// the last connection attempt (the last address) is returned.
110 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
114 /// Open a TCP connection to `127.0.0.1:8080`:
117 /// use std::net::TcpStream;
119 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
120 /// println!("Connected to the server!");
122 /// println!("Couldn't connect to server...");
126 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
127 /// a TCP connection to `127.0.0.1:8081`:
130 /// use std::net::{SocketAddr, TcpStream};
133 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
134 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
136 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
137 /// println!("Connected to the server!");
139 /// println!("Couldn't connect to server...");
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
144 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
147 /// Opens a TCP connection to a remote host with a timeout.
149 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
150 /// timeout must be applied to individual addresses.
152 /// It is an error to pass a zero `Duration` to this function.
154 /// Unlike other methods on `TcpStream`, this does not correspond to a
155 /// single system call. It instead calls `connect` in nonblocking mode and
156 /// then uses an OS-specific mechanism to await the completion of the
157 /// connection request.
159 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
160 #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
161 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
162 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
165 /// Returns the socket address of the remote peer of this TCP connection.
170 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
172 /// let stream = TcpStream::connect("127.0.0.1:8080")
173 /// .expect("Couldn't connect to the server...");
174 /// assert_eq!(stream.peer_addr().unwrap(),
175 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
177 #[stable(feature = "rust1", since = "1.0.0")]
178 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
182 /// Returns the socket address of the local half of this TCP connection.
187 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
189 /// let stream = TcpStream::connect("127.0.0.1:8080")
190 /// .expect("Couldn't connect to the server...");
191 /// assert_eq!(stream.local_addr().unwrap().ip(),
192 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
194 #[stable(feature = "rust1", since = "1.0.0")]
195 pub fn local_addr(&self) -> io::Result<SocketAddr> {
199 /// Shuts down the read, write, or both halves of this connection.
201 /// This function will cause all pending and future I/O on the specified
202 /// portions to return immediately with an appropriate value (see the
203 /// documentation of [`Shutdown`]).
205 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
207 /// # Platform-specific behavior
209 /// Calling this function multiple times may result in different behavior,
210 /// depending on the operating system. On Linux, the second call will
211 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
212 /// This may change in the future.
217 /// use std::net::{Shutdown, TcpStream};
219 /// let stream = TcpStream::connect("127.0.0.1:8080")
220 /// .expect("Couldn't connect to the server...");
221 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
223 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
228 /// Creates a new independently owned handle to the underlying socket.
230 /// The returned `TcpStream` is a reference to the same stream that this
231 /// object references. Both handles will read and write the same stream of
232 /// data, and options set on one stream will be propagated to the other
238 /// use std::net::TcpStream;
240 /// let stream = TcpStream::connect("127.0.0.1:8080")
241 /// .expect("Couldn't connect to the server...");
242 /// let stream_clone = stream.try_clone().expect("clone failed...");
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub fn try_clone(&self) -> io::Result<TcpStream> {
246 self.0.duplicate().map(TcpStream)
249 /// Sets the read timeout to the timeout specified.
251 /// If the value specified is [`None`], then [`read`] calls will block
252 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
253 /// passed to this method.
255 /// # Platform-specific behavior
257 /// Platforms may return a different error code whenever a read times out as
258 /// a result of setting this option. For example Unix typically returns an
259 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
261 /// [`None`]: ../../std/option/enum.Option.html#variant.None
262 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
263 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
264 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
265 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
266 /// [`Duration`]: ../../std/time/struct.Duration.html
271 /// use std::net::TcpStream;
273 /// let stream = TcpStream::connect("127.0.0.1:8080")
274 /// .expect("Couldn't connect to the server...");
275 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
278 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
283 /// use std::net::TcpStream;
284 /// use std::time::Duration;
286 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
287 /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
288 /// let err = result.unwrap_err();
289 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
291 #[stable(feature = "socket_timeout", since = "1.4.0")]
292 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
293 self.0.set_read_timeout(dur)
296 /// Sets the write timeout to the timeout specified.
298 /// If the value specified is [`None`], then [`write`] calls will block
299 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
300 /// passed to this method.
302 /// # Platform-specific behavior
304 /// Platforms may return a different error code whenever a write times out
305 /// as a result of setting this option. For example Unix typically returns
306 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
308 /// [`None`]: ../../std/option/enum.Option.html#variant.None
309 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
310 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
311 /// [`Duration`]: ../../std/time/struct.Duration.html
312 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
313 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
318 /// use std::net::TcpStream;
320 /// let stream = TcpStream::connect("127.0.0.1:8080")
321 /// .expect("Couldn't connect to the server...");
322 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
325 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
330 /// use std::net::TcpStream;
331 /// use std::time::Duration;
333 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
334 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
335 /// let err = result.unwrap_err();
336 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
338 #[stable(feature = "socket_timeout", since = "1.4.0")]
339 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
340 self.0.set_write_timeout(dur)
343 /// Returns the read timeout of this socket.
345 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
347 /// # Platform-specific behavior
349 /// Some platforms do not provide access to the current timeout.
351 /// [`None`]: ../../std/option/enum.Option.html#variant.None
352 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
357 /// use std::net::TcpStream;
359 /// let stream = TcpStream::connect("127.0.0.1:8080")
360 /// .expect("Couldn't connect to the server...");
361 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
362 /// assert_eq!(stream.read_timeout().unwrap(), None);
364 #[stable(feature = "socket_timeout", since = "1.4.0")]
365 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
366 self.0.read_timeout()
369 /// Returns the write timeout of this socket.
371 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
373 /// # Platform-specific behavior
375 /// Some platforms do not provide access to the current timeout.
377 /// [`None`]: ../../std/option/enum.Option.html#variant.None
378 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
383 /// use std::net::TcpStream;
385 /// let stream = TcpStream::connect("127.0.0.1:8080")
386 /// .expect("Couldn't connect to the server...");
387 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
388 /// assert_eq!(stream.write_timeout().unwrap(), None);
390 #[stable(feature = "socket_timeout", since = "1.4.0")]
391 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
392 self.0.write_timeout()
395 /// Receives data on the socket from the remote address to which it is
396 /// connected, without removing that data from the queue. On success,
397 /// returns the number of bytes peeked.
399 /// Successive calls return the same data. This is accomplished by passing
400 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
405 /// use std::net::TcpStream;
407 /// let stream = TcpStream::connect("127.0.0.1:8000")
408 /// .expect("couldn't bind to address");
409 /// let mut buf = [0; 10];
410 /// let len = stream.peek(&mut buf).expect("peek failed");
412 #[stable(feature = "peek", since = "1.18.0")]
413 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
417 /// Sets the value of the `TCP_NODELAY` option on this socket.
419 /// If set, this option disables the Nagle algorithm. This means that
420 /// segments are always sent as soon as possible, even if there is only a
421 /// small amount of data. When not set, data is buffered until there is a
422 /// sufficient amount to send out, thereby avoiding the frequent sending of
428 /// use std::net::TcpStream;
430 /// let stream = TcpStream::connect("127.0.0.1:8080")
431 /// .expect("Couldn't connect to the server...");
432 /// stream.set_nodelay(true).expect("set_nodelay call failed");
434 #[stable(feature = "net2_mutators", since = "1.9.0")]
435 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
436 self.0.set_nodelay(nodelay)
439 /// Gets the value of the `TCP_NODELAY` option on this socket.
441 /// For more information about this option, see [`set_nodelay`][link].
443 /// [link]: #method.set_nodelay
448 /// use std::net::TcpStream;
450 /// let stream = TcpStream::connect("127.0.0.1:8080")
451 /// .expect("Couldn't connect to the server...");
452 /// stream.set_nodelay(true).expect("set_nodelay call failed");
453 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
455 #[stable(feature = "net2_mutators", since = "1.9.0")]
456 pub fn nodelay(&self) -> io::Result<bool> {
460 /// Sets the value for the `IP_TTL` option on this socket.
462 /// This value sets the time-to-live field that is used in every packet sent
463 /// from this socket.
468 /// use std::net::TcpStream;
470 /// let stream = TcpStream::connect("127.0.0.1:8080")
471 /// .expect("Couldn't connect to the server...");
472 /// stream.set_ttl(100).expect("set_ttl call failed");
474 #[stable(feature = "net2_mutators", since = "1.9.0")]
475 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
479 /// Gets the value of the `IP_TTL` option for this socket.
481 /// For more information about this option, see [`set_ttl`][link].
483 /// [link]: #method.set_ttl
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.set_ttl(100).expect("set_ttl call failed");
493 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
495 #[stable(feature = "net2_mutators", since = "1.9.0")]
496 pub fn ttl(&self) -> io::Result<u32> {
500 /// Gets the value of the `SO_ERROR` option on this socket.
502 /// This will retrieve the stored error in the underlying socket, clearing
503 /// the field in the process. This can be useful for checking errors between
509 /// use std::net::TcpStream;
511 /// let stream = TcpStream::connect("127.0.0.1:8080")
512 /// .expect("Couldn't connect to the server...");
513 /// stream.take_error().expect("No error was expected...");
515 #[stable(feature = "net2_mutators", since = "1.9.0")]
516 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
520 /// Moves this TCP stream into or out of nonblocking mode.
522 /// This will result in `read`, `write`, `recv` and `send` operations
523 /// becoming nonblocking, i.e., immediately returning from their calls.
524 /// If the IO operation is successful, `Ok` is returned and no further
525 /// action is required. If the IO operation could not be completed and needs
526 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
529 /// On Unix platforms, calling this method corresponds to calling `fcntl`
530 /// `FIONBIO`. On Windows calling this method corresponds to calling
531 /// `ioctlsocket` `FIONBIO`.
535 /// Reading bytes from a TCP stream in non-blocking mode:
538 /// use std::io::{self, Read};
539 /// use std::net::TcpStream;
541 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
542 /// .expect("Couldn't connect to the server...");
543 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
545 /// # fn wait_for_fd() { unimplemented!() }
546 /// let mut buf = vec![];
548 /// match stream.read_to_end(&mut buf) {
550 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
551 /// // wait until network socket is ready, typically implemented
552 /// // via platform-specific APIs such as epoll or IOCP
555 /// Err(e) => panic!("encountered IO error: {}", e),
558 /// println!("bytes: {:?}", buf);
561 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
562 #[stable(feature = "net2_mutators", since = "1.9.0")]
563 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
564 self.0.set_nonblocking(nonblocking)
568 #[stable(feature = "rust1", since = "1.0.0")]
569 impl Read for TcpStream {
570 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
572 fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> io::Result<usize> {
573 self.0.read_vectored(bufs)
577 unsafe fn initializer(&self) -> Initializer {
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl Write for TcpStream {
583 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
585 fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> io::Result<usize> {
586 self.0.write_vectored(bufs)
589 fn flush(&mut self) -> io::Result<()> { Ok(()) }
591 #[stable(feature = "rust1", since = "1.0.0")]
592 impl Read for &TcpStream {
593 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
595 fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> io::Result<usize> {
596 self.0.read_vectored(bufs)
600 unsafe fn initializer(&self) -> Initializer {
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl Write for &TcpStream {
606 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
608 fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> io::Result<usize> {
609 self.0.write_vectored(bufs)
612 fn flush(&mut self) -> io::Result<()> { Ok(()) }
615 impl AsInner<net_imp::TcpStream> for TcpStream {
616 fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
619 impl FromInner<net_imp::TcpStream> for TcpStream {
620 fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
623 impl IntoInner<net_imp::TcpStream> for TcpStream {
624 fn into_inner(self) -> net_imp::TcpStream { self.0 }
627 #[stable(feature = "rust1", since = "1.0.0")]
628 impl fmt::Debug for TcpStream {
629 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
635 /// Creates a new `TcpListener` which will be bound to the specified
638 /// The returned listener is ready for accepting connections.
640 /// Binding with a port number of 0 will request that the OS assigns a port
641 /// to this listener. The port allocated can be queried via the
642 /// [`local_addr`] method.
644 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
645 /// its documentation for concrete examples.
647 /// If `addr` yields multiple addresses, `bind` will be attempted with
648 /// each of the addresses until one succeeds and returns the listener. If
649 /// none of the addresses succeed in creating a listener, the error returned
650 /// from the last attempt (the last address) is returned.
652 /// [`local_addr`]: #method.local_addr
653 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
657 /// Creates a TCP listener bound to `127.0.0.1:80`:
660 /// use std::net::TcpListener;
662 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
665 /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
666 /// TCP listener bound to `127.0.0.1:443`:
669 /// use std::net::{SocketAddr, TcpListener};
672 /// SocketAddr::from(([127, 0, 0, 1], 80)),
673 /// SocketAddr::from(([127, 0, 0, 1], 443)),
675 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
677 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
679 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
682 /// Returns the local socket address of this listener.
687 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
689 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
690 /// assert_eq!(listener.local_addr().unwrap(),
691 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
693 #[stable(feature = "rust1", since = "1.0.0")]
694 pub fn local_addr(&self) -> io::Result<SocketAddr> {
698 /// Creates a new independently owned handle to the underlying socket.
700 /// The returned [`TcpListener`] is a reference to the same socket that this
701 /// object references. Both handles can be used to accept incoming
702 /// connections and options set on one listener will affect the other.
704 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
709 /// use std::net::TcpListener;
711 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
712 /// let listener_clone = listener.try_clone().unwrap();
714 #[stable(feature = "rust1", since = "1.0.0")]
715 pub fn try_clone(&self) -> io::Result<TcpListener> {
716 self.0.duplicate().map(TcpListener)
719 /// Accept a new incoming connection from this listener.
721 /// This function will block the calling thread until a new TCP connection
722 /// is established. When established, the corresponding [`TcpStream`] and the
723 /// remote peer's address will be returned.
725 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
730 /// use std::net::TcpListener;
732 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
733 /// match listener.accept() {
734 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
735 /// Err(e) => println!("couldn't get client: {:?}", e),
738 #[stable(feature = "rust1", since = "1.0.0")]
739 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
740 // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
741 // the `a` variable here is technically unused.
742 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
743 self.0.accept().map(|(a, b)| (TcpStream(a), b))
746 /// Returns an iterator over the connections being received on this
749 /// The returned iterator will never return [`None`] and will also not yield
750 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
751 /// calling [`accept`] in a loop.
753 /// [`None`]: ../../std/option/enum.Option.html#variant.None
754 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
755 /// [`accept`]: #method.accept
760 /// use std::net::TcpListener;
762 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
764 /// for stream in listener.incoming() {
767 /// println!("new client!");
769 /// Err(e) => { /* connection failed */ }
773 #[stable(feature = "rust1", since = "1.0.0")]
774 pub fn incoming(&self) -> Incoming {
775 Incoming { listener: self }
778 /// Sets the value for the `IP_TTL` option on this socket.
780 /// This value sets the time-to-live field that is used in every packet sent
781 /// from this socket.
786 /// use std::net::TcpListener;
788 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
789 /// listener.set_ttl(100).expect("could not set TTL");
791 #[stable(feature = "net2_mutators", since = "1.9.0")]
792 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
796 /// Gets the value of the `IP_TTL` option for this socket.
798 /// For more information about this option, see [`set_ttl`][link].
800 /// [link]: #method.set_ttl
805 /// use std::net::TcpListener;
807 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
808 /// listener.set_ttl(100).expect("could not set TTL");
809 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
811 #[stable(feature = "net2_mutators", since = "1.9.0")]
812 pub fn ttl(&self) -> io::Result<u32> {
816 #[stable(feature = "net2_mutators", since = "1.9.0")]
817 #[rustc_deprecated(since = "1.16.0",
818 reason = "this option can only be set before the socket is bound")]
819 #[allow(missing_docs)]
820 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
821 self.0.set_only_v6(only_v6)
824 #[stable(feature = "net2_mutators", since = "1.9.0")]
825 #[rustc_deprecated(since = "1.16.0",
826 reason = "this option can only be set before the socket is bound")]
827 #[allow(missing_docs)]
828 pub fn only_v6(&self) -> io::Result<bool> {
832 /// Gets the value of the `SO_ERROR` option on this socket.
834 /// This will retrieve the stored error in the underlying socket, clearing
835 /// the field in the process. This can be useful for checking errors between
841 /// use std::net::TcpListener;
843 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
844 /// listener.take_error().expect("No error was expected");
846 #[stable(feature = "net2_mutators", since = "1.9.0")]
847 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
851 /// Moves this TCP stream into or out of nonblocking mode.
853 /// This will result in the `accept` operation becoming nonblocking,
854 /// i.e., immediately returning from their calls. If the IO operation is
855 /// successful, `Ok` is returned and no further action is required. If the
856 /// IO operation could not be completed and needs to be retried, an error
857 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
859 /// On Unix platforms, calling this method corresponds to calling `fcntl`
860 /// `FIONBIO`. On Windows calling this method corresponds to calling
861 /// `ioctlsocket` `FIONBIO`.
865 /// Bind a TCP listener to an address, listen for connections, and read
866 /// bytes in nonblocking mode:
870 /// use std::net::TcpListener;
872 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
873 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
875 /// # fn wait_for_fd() { unimplemented!() }
876 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
877 /// for stream in listener.incoming() {
880 /// // do something with the TcpStream
881 /// handle_connection(s);
883 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
884 /// // wait until network socket is ready, typically implemented
885 /// // via platform-specific APIs such as epoll or IOCP
889 /// Err(e) => panic!("encountered IO error: {}", e),
894 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
895 #[stable(feature = "net2_mutators", since = "1.9.0")]
896 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
897 self.0.set_nonblocking(nonblocking)
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a> Iterator for Incoming<'a> {
903 type Item = io::Result<TcpStream>;
904 fn next(&mut self) -> Option<io::Result<TcpStream>> {
905 Some(self.listener.accept().map(|p| p.0))
909 impl AsInner<net_imp::TcpListener> for TcpListener {
910 fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
913 impl FromInner<net_imp::TcpListener> for TcpListener {
914 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
919 impl IntoInner<net_imp::TcpListener> for TcpListener {
920 fn into_inner(self) -> net_imp::TcpListener { self.0 }
923 #[stable(feature = "rust1", since = "1.0.0")]
924 impl fmt::Debug for TcpListener {
925 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
930 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
932 use crate::io::{ErrorKind, IoVec, IoVecMut};
933 use crate::io::prelude::*;
935 use crate::net::test::{next_test_ip4, next_test_ip6};
936 use crate::sync::mpsc::channel;
937 use crate::sys_common::AsInner;
938 use crate::time::{Instant, Duration};
941 fn each_ip(f: &mut dyn FnMut(SocketAddr)) {
950 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
957 match TcpListener::bind("1.1.1.1:9999") {
960 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
966 match TcpStream::connect("0.0.0.0:1") {
968 Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
969 e.kind() == ErrorKind::InvalidInput ||
970 e.kind() == ErrorKind::AddrInUse ||
971 e.kind() == ErrorKind::AddrNotAvailable,
972 "bad error: {} {:?}", e, e.kind()),
977 fn listen_localhost() {
978 let socket_addr = next_test_ip4();
979 let listener = t!(TcpListener::bind(&socket_addr));
981 let _t = thread::spawn(move || {
982 let mut stream = t!(TcpStream::connect(&("localhost",
983 socket_addr.port())));
984 t!(stream.write(&[144]));
987 let mut stream = t!(listener.accept()).0;
989 t!(stream.read(&mut buf));
990 assert!(buf[0] == 144);
994 fn connect_loopback() {
995 each_ip(&mut |addr| {
996 let acceptor = t!(TcpListener::bind(&addr));
998 let _t = thread::spawn(move|| {
999 let host = match addr {
1000 SocketAddr::V4(..) => "127.0.0.1",
1001 SocketAddr::V6(..) => "::1",
1003 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
1004 t!(stream.write(&[66]));
1007 let mut stream = t!(acceptor.accept()).0;
1009 t!(stream.read(&mut buf));
1010 assert!(buf[0] == 66);
1016 each_ip(&mut |addr| {
1017 let acceptor = t!(TcpListener::bind(&addr));
1019 let (tx, rx) = channel();
1020 let _t = thread::spawn(move|| {
1021 let mut stream = t!(TcpStream::connect(&addr));
1022 t!(stream.write(&[99]));
1023 tx.send(t!(stream.local_addr())).unwrap();
1026 let (mut stream, addr) = t!(acceptor.accept());
1028 t!(stream.read(&mut buf));
1029 assert!(buf[0] == 99);
1030 assert_eq!(addr, t!(rx.recv()));
1036 each_ip(&mut |addr| {
1037 let acceptor = t!(TcpListener::bind(&addr));
1039 let _t = thread::spawn(move|| {
1040 let _stream = t!(TcpStream::connect(&addr));
1044 let mut stream = t!(acceptor.accept()).0;
1046 let nread = t!(stream.read(&mut buf));
1047 assert_eq!(nread, 0);
1048 let nread = t!(stream.read(&mut buf));
1049 assert_eq!(nread, 0);
1055 each_ip(&mut |addr| {
1056 let acceptor = t!(TcpListener::bind(&addr));
1058 let (tx, rx) = channel();
1059 let _t = thread::spawn(move|| {
1060 drop(t!(TcpStream::connect(&addr)));
1061 tx.send(()).unwrap();
1064 let mut stream = t!(acceptor.accept()).0;
1067 match stream.write(&buf) {
1070 assert!(e.kind() == ErrorKind::ConnectionReset ||
1071 e.kind() == ErrorKind::BrokenPipe ||
1072 e.kind() == ErrorKind::ConnectionAborted,
1073 "unknown error: {}", e);
1080 fn multiple_connect_serial() {
1081 each_ip(&mut |addr| {
1083 let acceptor = t!(TcpListener::bind(&addr));
1085 let _t = thread::spawn(move|| {
1087 let mut stream = t!(TcpStream::connect(&addr));
1088 t!(stream.write(&[99]));
1092 for stream in acceptor.incoming().take(max) {
1093 let mut stream = t!(stream);
1095 t!(stream.read(&mut buf));
1096 assert_eq!(buf[0], 99);
1102 fn multiple_connect_interleaved_greedy_schedule() {
1103 const MAX: usize = 10;
1104 each_ip(&mut |addr| {
1105 let acceptor = t!(TcpListener::bind(&addr));
1107 let _t = thread::spawn(move|| {
1108 let acceptor = acceptor;
1109 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
1110 // Start another thread to handle the connection
1111 let _t = thread::spawn(move|| {
1112 let mut stream = t!(stream);
1114 t!(stream.read(&mut buf));
1115 assert!(buf[0] == i as u8);
1123 fn connect(i: usize, addr: SocketAddr) {
1124 if i == MAX { return }
1126 let t = thread::spawn(move|| {
1127 let mut stream = t!(TcpStream::connect(&addr));
1128 // Connect again before writing
1129 connect(i + 1, addr);
1130 t!(stream.write(&[i as u8]));
1132 t.join().ok().unwrap();
1137 fn multiple_connect_interleaved_lazy_schedule() {
1138 const MAX: usize = 10;
1139 each_ip(&mut |addr| {
1140 let acceptor = t!(TcpListener::bind(&addr));
1142 let _t = thread::spawn(move|| {
1143 for stream in acceptor.incoming().take(MAX) {
1144 // Start another thread to handle the connection
1145 let _t = thread::spawn(move|| {
1146 let mut stream = t!(stream);
1148 t!(stream.read(&mut buf));
1149 assert!(buf[0] == 99);
1157 fn connect(i: usize, addr: SocketAddr) {
1158 if i == MAX { return }
1160 let t = thread::spawn(move|| {
1161 let mut stream = t!(TcpStream::connect(&addr));
1162 connect(i + 1, addr);
1163 t!(stream.write(&[99]));
1165 t.join().ok().unwrap();
1170 fn socket_and_peer_name() {
1171 each_ip(&mut |addr| {
1172 let listener = t!(TcpListener::bind(&addr));
1173 let so_name = t!(listener.local_addr());
1174 assert_eq!(addr, so_name);
1175 let _t = thread::spawn(move|| {
1176 t!(listener.accept());
1179 let stream = t!(TcpStream::connect(&addr));
1180 assert_eq!(addr, t!(stream.peer_addr()));
1186 each_ip(&mut |addr| {
1187 let (tx, rx) = channel();
1188 let srv = t!(TcpListener::bind(&addr));
1189 let _t = thread::spawn(move|| {
1190 let mut cl = t!(srv.accept()).0;
1191 cl.write(&[10]).unwrap();
1193 t!(cl.read(&mut b));
1194 tx.send(()).unwrap();
1197 let mut c = t!(TcpStream::connect(&addr));
1198 let mut b = [0; 10];
1199 assert_eq!(c.read(&mut b).unwrap(), 1);
1206 fn read_vectored() {
1207 each_ip(&mut |addr| {
1208 let srv = t!(TcpListener::bind(&addr));
1209 let mut s1 = t!(TcpStream::connect(&addr));
1210 let mut s2 = t!(srv.accept()).0;
1212 let len = s1.write(&[10, 11, 12]).unwrap();
1218 let len = t!(s2.read_vectored(
1219 &mut [IoVecMut::new(&mut a), IoVecMut::new(&mut b), IoVecMut::new(&mut c)],
1222 assert_eq!(b, [10]);
1223 // some implementations don't support readv, so we may only fill the first buffer
1224 assert!(len == 1 || c == [11, 12, 0]);
1229 fn write_vectored() {
1230 each_ip(&mut |addr| {
1231 let srv = t!(TcpListener::bind(&addr));
1232 let mut s1 = t!(TcpStream::connect(&addr));
1233 let mut s2 = t!(srv.accept()).0;
1238 t!(s1.write_vectored(&[IoVec::new(&a), IoVec::new(&b), IoVec::new(&c)]));
1240 let mut buf = [0; 4];
1241 let len = t!(s2.read(&mut buf));
1242 // some implementations don't support writev, so we may only write the first buffer
1244 assert_eq!(buf, [10, 0, 0, 0]);
1247 assert_eq!(buf, [10, 11, 12, 0]);
1254 each_ip(&mut |addr| {
1255 let listener1 = t!(TcpListener::bind(&addr));
1256 match TcpListener::bind(&addr) {
1257 Ok(listener2) => panic!(
1258 "This system (perhaps due to options set by TcpListener::bind) \
1259 permits double binding: {:?} and {:?}",
1260 listener1, listener2
1263 assert!(e.kind() == ErrorKind::ConnectionRefused ||
1264 e.kind() == ErrorKind::Other ||
1265 e.kind() == ErrorKind::AddrInUse,
1266 "unknown error: {} {:?}", e, e.kind());
1274 each_ip(&mut |addr| {
1275 let acceptor = t!(TcpListener::bind(&addr));
1277 let _t = thread::spawn(move|| {
1278 t!(TcpStream::connect(&addr));
1281 t!(acceptor.accept());
1283 t!(TcpListener::bind(&addr));
1288 fn tcp_clone_smoke() {
1289 each_ip(&mut |addr| {
1290 let acceptor = t!(TcpListener::bind(&addr));
1292 let _t = thread::spawn(move|| {
1293 let mut s = t!(TcpStream::connect(&addr));
1294 let mut buf = [0, 0];
1295 assert_eq!(s.read(&mut buf).unwrap(), 1);
1296 assert_eq!(buf[0], 1);
1300 let mut s1 = t!(acceptor.accept()).0;
1301 let s2 = t!(s1.try_clone());
1303 let (tx1, rx1) = channel();
1304 let (tx2, rx2) = channel();
1305 let _t = thread::spawn(move|| {
1307 rx1.recv().unwrap();
1309 tx2.send(()).unwrap();
1311 tx1.send(()).unwrap();
1312 let mut buf = [0, 0];
1313 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1314 rx2.recv().unwrap();
1319 fn tcp_clone_two_read() {
1320 each_ip(&mut |addr| {
1321 let acceptor = t!(TcpListener::bind(&addr));
1322 let (tx1, rx) = channel();
1323 let tx2 = tx1.clone();
1325 let _t = thread::spawn(move|| {
1326 let mut s = t!(TcpStream::connect(&addr));
1333 let mut s1 = t!(acceptor.accept()).0;
1334 let s2 = t!(s1.try_clone());
1336 let (done, rx) = channel();
1337 let _t = thread::spawn(move|| {
1339 let mut buf = [0, 0];
1340 t!(s2.read(&mut buf));
1341 tx2.send(()).unwrap();
1342 done.send(()).unwrap();
1344 let mut buf = [0, 0];
1345 t!(s1.read(&mut buf));
1346 tx1.send(()).unwrap();
1353 fn tcp_clone_two_write() {
1354 each_ip(&mut |addr| {
1355 let acceptor = t!(TcpListener::bind(&addr));
1357 let _t = thread::spawn(move|| {
1358 let mut s = t!(TcpStream::connect(&addr));
1359 let mut buf = [0, 1];
1360 t!(s.read(&mut buf));
1361 t!(s.read(&mut buf));
1364 let mut s1 = t!(acceptor.accept()).0;
1365 let s2 = t!(s1.try_clone());
1367 let (done, rx) = channel();
1368 let _t = thread::spawn(move|| {
1371 done.send(()).unwrap();
1380 fn shutdown_smoke() {
1381 each_ip(&mut |addr| {
1382 let a = t!(TcpListener::bind(&addr));
1383 let _t = thread::spawn(move|| {
1384 let mut c = t!(a.accept()).0;
1386 assert_eq!(c.read(&mut b).unwrap(), 0);
1390 let mut s = t!(TcpStream::connect(&addr));
1391 t!(s.shutdown(Shutdown::Write));
1392 assert!(s.write(&[1]).is_err());
1394 assert_eq!(t!(s.read(&mut b)), 1);
1395 assert_eq!(b[0], 1);
1400 fn close_readwrite_smoke() {
1401 each_ip(&mut |addr| {
1402 let a = t!(TcpListener::bind(&addr));
1403 let (tx, rx) = channel::<()>();
1404 let _t = thread::spawn(move|| {
1405 let _s = t!(a.accept());
1410 let mut s = t!(TcpStream::connect(&addr));
1411 let mut s2 = t!(s.try_clone());
1413 // closing should prevent reads/writes
1414 t!(s.shutdown(Shutdown::Write));
1415 assert!(s.write(&[0]).is_err());
1416 t!(s.shutdown(Shutdown::Read));
1417 assert_eq!(s.read(&mut b).unwrap(), 0);
1419 // closing should affect previous handles
1420 assert!(s2.write(&[0]).is_err());
1421 assert_eq!(s2.read(&mut b).unwrap(), 0);
1423 // closing should affect new handles
1424 let mut s3 = t!(s.try_clone());
1425 assert!(s3.write(&[0]).is_err());
1426 assert_eq!(s3.read(&mut b).unwrap(), 0);
1428 // make sure these don't die
1429 let _ = s2.shutdown(Shutdown::Read);
1430 let _ = s2.shutdown(Shutdown::Write);
1431 let _ = s3.shutdown(Shutdown::Read);
1432 let _ = s3.shutdown(Shutdown::Write);
1438 #[cfg(unix)] // test doesn't work on Windows, see #31657
1439 fn close_read_wakes_up() {
1440 each_ip(&mut |addr| {
1441 let a = t!(TcpListener::bind(&addr));
1442 let (tx1, rx) = channel::<()>();
1443 let _t = thread::spawn(move|| {
1444 let _s = t!(a.accept());
1448 let s = t!(TcpStream::connect(&addr));
1449 let s2 = t!(s.try_clone());
1450 let (tx, rx) = channel();
1451 let _t = thread::spawn(move|| {
1453 assert_eq!(t!(s2.read(&mut [0])), 0);
1454 tx.send(()).unwrap();
1456 // this should wake up the child thread
1457 t!(s.shutdown(Shutdown::Read));
1459 // this test will never finish if the child doesn't wake up
1466 fn clone_while_reading() {
1467 each_ip(&mut |addr| {
1468 let accept = t!(TcpListener::bind(&addr));
1470 // Enqueue a thread to write to a socket
1471 let (tx, rx) = channel();
1472 let (txdone, rxdone) = channel();
1473 let txdone2 = txdone.clone();
1474 let _t = thread::spawn(move|| {
1475 let mut tcp = t!(TcpStream::connect(&addr));
1477 t!(tcp.write(&[0]));
1478 txdone2.send(()).unwrap();
1481 // Spawn off a reading clone
1482 let tcp = t!(accept.accept()).0;
1483 let tcp2 = t!(tcp.try_clone());
1484 let txdone3 = txdone.clone();
1485 let _t = thread::spawn(move|| {
1486 let mut tcp2 = tcp2;
1487 t!(tcp2.read(&mut [0]));
1488 txdone3.send(()).unwrap();
1491 // Try to ensure that the reading clone is indeed reading
1493 thread::yield_now();
1496 // clone the handle again while it's reading, then let it finish the
1498 let _ = t!(tcp.try_clone());
1499 tx.send(()).unwrap();
1500 rxdone.recv().unwrap();
1501 rxdone.recv().unwrap();
1506 fn clone_accept_smoke() {
1507 each_ip(&mut |addr| {
1508 let a = t!(TcpListener::bind(&addr));
1509 let a2 = t!(a.try_clone());
1511 let _t = thread::spawn(move|| {
1512 let _ = TcpStream::connect(&addr);
1514 let _t = thread::spawn(move|| {
1515 let _ = TcpStream::connect(&addr);
1524 fn clone_accept_concurrent() {
1525 each_ip(&mut |addr| {
1526 let a = t!(TcpListener::bind(&addr));
1527 let a2 = t!(a.try_clone());
1529 let (tx, rx) = channel();
1530 let tx2 = tx.clone();
1532 let _t = thread::spawn(move|| {
1533 tx.send(t!(a.accept())).unwrap();
1535 let _t = thread::spawn(move|| {
1536 tx2.send(t!(a2.accept())).unwrap();
1539 let _t = thread::spawn(move|| {
1540 let _ = TcpStream::connect(&addr);
1542 let _t = thread::spawn(move|| {
1543 let _ = TcpStream::connect(&addr);
1553 let name = if cfg!(windows) {"socket"} else {"fd"};
1554 let socket_addr = next_test_ip4();
1556 let listener = t!(TcpListener::bind(&socket_addr));
1557 let listener_inner = listener.0.socket().as_inner();
1558 let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
1559 socket_addr, name, listener_inner);
1560 assert_eq!(format!("{:?}", listener), compare);
1562 let stream = t!(TcpStream::connect(&("localhost",
1563 socket_addr.port())));
1564 let stream_inner = stream.0.socket().as_inner();
1565 let compare = format!("TcpStream {{ addr: {:?}, \
1566 peer: {:?}, {}: {:?} }}",
1567 stream.local_addr().unwrap(),
1568 stream.peer_addr().unwrap(),
1571 assert_eq!(format!("{:?}", stream), compare);
1574 // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
1575 // no longer has rounding errors.
1576 #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1579 let addr = next_test_ip4();
1580 let listener = t!(TcpListener::bind(&addr));
1582 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1583 let dur = Duration::new(15410, 0);
1585 assert_eq!(None, t!(stream.read_timeout()));
1587 t!(stream.set_read_timeout(Some(dur)));
1588 assert_eq!(Some(dur), t!(stream.read_timeout()));
1590 assert_eq!(None, t!(stream.write_timeout()));
1592 t!(stream.set_write_timeout(Some(dur)));
1593 assert_eq!(Some(dur), t!(stream.write_timeout()));
1595 t!(stream.set_read_timeout(None));
1596 assert_eq!(None, t!(stream.read_timeout()));
1598 t!(stream.set_write_timeout(None));
1599 assert_eq!(None, t!(stream.write_timeout()));
1604 fn test_read_timeout() {
1605 let addr = next_test_ip4();
1606 let listener = t!(TcpListener::bind(&addr));
1608 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1609 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1611 let mut buf = [0; 10];
1612 let start = Instant::now();
1613 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1614 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1615 "unexpected_error: {:?}", kind);
1616 assert!(start.elapsed() > Duration::from_millis(400));
1621 fn test_read_with_timeout() {
1622 let addr = next_test_ip4();
1623 let listener = t!(TcpListener::bind(&addr));
1625 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1626 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1628 let mut other_end = t!(listener.accept()).0;
1629 t!(other_end.write_all(b"hello world"));
1631 let mut buf = [0; 11];
1632 t!(stream.read(&mut buf));
1633 assert_eq!(b"hello world", &buf[..]);
1635 let start = Instant::now();
1636 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1637 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1638 "unexpected_error: {:?}", kind);
1639 assert!(start.elapsed() > Duration::from_millis(400));
1643 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1644 // when passed zero Durations
1646 fn test_timeout_zero_duration() {
1647 let addr = next_test_ip4();
1649 let listener = t!(TcpListener::bind(&addr));
1650 let stream = t!(TcpStream::connect(&addr));
1652 let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1653 let err = result.unwrap_err();
1654 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1656 let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1657 let err = result.unwrap_err();
1658 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1665 let addr = next_test_ip4();
1666 let _listener = t!(TcpListener::bind(&addr));
1668 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1670 assert_eq!(false, t!(stream.nodelay()));
1671 t!(stream.set_nodelay(true));
1672 assert_eq!(true, t!(stream.nodelay()));
1673 t!(stream.set_nodelay(false));
1674 assert_eq!(false, t!(stream.nodelay()));
1681 let addr = next_test_ip4();
1682 let listener = t!(TcpListener::bind(&addr));
1684 t!(listener.set_ttl(ttl));
1685 assert_eq!(ttl, t!(listener.ttl()));
1687 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1689 t!(stream.set_ttl(ttl));
1690 assert_eq!(ttl, t!(stream.ttl()));
1694 fn set_nonblocking() {
1695 let addr = next_test_ip4();
1696 let listener = t!(TcpListener::bind(&addr));
1698 t!(listener.set_nonblocking(true));
1699 t!(listener.set_nonblocking(false));
1701 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1703 t!(stream.set_nonblocking(false));
1704 t!(stream.set_nonblocking(true));
1707 match stream.read(&mut buf) {
1708 Ok(_) => panic!("expected error"),
1709 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1710 Err(e) => panic!("unexpected error {}", e),
1716 each_ip(&mut |addr| {
1717 let (txdone, rxdone) = channel();
1719 let srv = t!(TcpListener::bind(&addr));
1720 let _t = thread::spawn(move|| {
1721 let mut cl = t!(srv.accept()).0;
1722 cl.write(&[1,3,3,7]).unwrap();
1726 let mut c = t!(TcpStream::connect(&addr));
1727 let mut b = [0; 10];
1729 let len = c.peek(&mut b).unwrap();
1732 let len = c.read(&mut b).unwrap();
1735 t!(c.set_nonblocking(true));
1736 match c.peek(&mut b) {
1737 Ok(_) => panic!("expected error"),
1738 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1739 Err(e) => panic!("unexpected error {}", e),
1741 t!(txdone.send(()));
1746 fn connect_timeout_valid() {
1747 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1748 let addr = listener.local_addr().unwrap();
1749 TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();