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`]: ../../std/net/struct.TcpListener.html#method.accept
24 /// [`connect`]: #method.connect
25 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
26 /// [reading]: ../../std/io/trait.Read.html
27 /// [`shutdown`]: #method.shutdown
28 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
29 /// [writing]: ../../std/io/trait.Write.html
34 /// use std::io::prelude::*;
35 /// use std::net::TcpStream;
37 /// fn main() -> std::io::Result<()> {
38 /// let mut stream = TcpStream::connect("127.0.0.1:34254")?;
40 /// stream.write(&[1])?;
41 /// stream.read(&mut [0; 128])?;
43 /// } // the stream is closed here
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct TcpStream(net_imp::TcpStream);
48 /// A TCP socket server, listening for connections.
50 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
51 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
52 /// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
54 /// The socket will be closed when the value is dropped.
56 /// The Transmission Control Protocol is specified in [IETF RFC 793].
58 /// [`accept`]: #method.accept
59 /// [`bind`]: #method.bind
60 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
61 /// [`Incoming`]: ../../std/net/struct.Incoming.html
62 /// [`TcpListener::incoming`]: #method.incoming
67 /// use std::net::{TcpListener, TcpStream};
69 /// fn handle_client(stream: TcpStream) {
73 /// fn main() -> std::io::Result<()> {
74 /// let listener = TcpListener::bind("127.0.0.1:80")?;
76 /// // accept connections and process them serially
77 /// for stream in listener.incoming() {
78 /// handle_client(stream?);
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct TcpListener(net_imp::TcpListener);
86 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
88 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
89 /// See its documentation for more.
91 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
92 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
93 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
94 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct Incoming<'a> {
97 listener: &'a TcpListener,
101 /// Opens a TCP connection to a remote host.
103 /// `addr` is an address of the remote host. Anything which implements
104 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
105 /// documentation for concrete examples.
107 /// If `addr` yields multiple addresses, `connect` will be attempted with
108 /// each of the addresses until a connection is successful. If none of
109 /// the addresses result in a successful connection, the error returned from
110 /// the last connection attempt (the last address) is returned.
112 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
116 /// Open a TCP connection to `127.0.0.1:8080`:
119 /// use std::net::TcpStream;
121 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
122 /// println!("Connected to the server!");
124 /// println!("Couldn't connect to server...");
128 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
129 /// a TCP connection to `127.0.0.1:8081`:
132 /// use std::net::{SocketAddr, TcpStream};
135 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
136 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
138 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
139 /// println!("Connected to the server!");
141 /// println!("Couldn't connect to server...");
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
146 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
149 /// Opens a TCP connection to a remote host with a timeout.
151 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
152 /// timeout must be applied to individual addresses.
154 /// It is an error to pass a zero `Duration` to this function.
156 /// Unlike other methods on `TcpStream`, this does not correspond to a
157 /// single system call. It instead calls `connect` in nonblocking mode and
158 /// then uses an OS-specific mechanism to await the completion of the
159 /// connection request.
161 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
162 #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
163 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
164 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
167 /// Returns the socket address of the remote peer of this TCP connection.
172 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
174 /// let stream = TcpStream::connect("127.0.0.1:8080")
175 /// .expect("Couldn't connect to the server...");
176 /// assert_eq!(stream.peer_addr().unwrap(),
177 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
184 /// Returns the socket address of the local half of this TCP connection.
189 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
191 /// let stream = TcpStream::connect("127.0.0.1:8080")
192 /// .expect("Couldn't connect to the server...");
193 /// assert_eq!(stream.local_addr().unwrap().ip(),
194 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub fn local_addr(&self) -> io::Result<SocketAddr> {
201 /// Shuts down the read, write, or both halves of this connection.
203 /// This function will cause all pending and future I/O on the specified
204 /// portions to return immediately with an appropriate value (see the
205 /// documentation of [`Shutdown`]).
207 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
209 /// # Platform-specific behavior
211 /// Calling this function multiple times may result in different behavior,
212 /// depending on the operating system. On Linux, the second call will
213 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
214 /// This may change in the future.
219 /// use std::net::{Shutdown, TcpStream};
221 /// let stream = TcpStream::connect("127.0.0.1:8080")
222 /// .expect("Couldn't connect to the server...");
223 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
225 #[stable(feature = "rust1", since = "1.0.0")]
226 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
230 /// Creates a new independently owned handle to the underlying socket.
232 /// The returned `TcpStream` is a reference to the same stream that this
233 /// object references. Both handles will read and write the same stream of
234 /// data, and options set on one stream will be propagated to the other
240 /// use std::net::TcpStream;
242 /// let stream = TcpStream::connect("127.0.0.1:8080")
243 /// .expect("Couldn't connect to the server...");
244 /// let stream_clone = stream.try_clone().expect("clone failed...");
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub fn try_clone(&self) -> io::Result<TcpStream> {
248 self.0.duplicate().map(TcpStream)
251 /// Sets the read timeout to the timeout specified.
253 /// If the value specified is [`None`], then [`read`] calls will block
254 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
255 /// passed to this method.
257 /// # Platform-specific behavior
259 /// Platforms may return a different error code whenever a read times out as
260 /// a result of setting this option. For example Unix typically returns an
261 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
263 /// [`None`]: ../../std/option/enum.Option.html#variant.None
264 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
265 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
266 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
267 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
268 /// [`Duration`]: ../../std/time/struct.Duration.html
273 /// use std::net::TcpStream;
275 /// let stream = TcpStream::connect("127.0.0.1:8080")
276 /// .expect("Couldn't connect to the server...");
277 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
280 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
285 /// use std::net::TcpStream;
286 /// use std::time::Duration;
288 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
289 /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
290 /// let err = result.unwrap_err();
291 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
293 #[stable(feature = "socket_timeout", since = "1.4.0")]
294 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
295 self.0.set_read_timeout(dur)
298 /// Sets the write timeout to the timeout specified.
300 /// If the value specified is [`None`], then [`write`] calls will block
301 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
302 /// passed to this method.
304 /// # Platform-specific behavior
306 /// Platforms may return a different error code whenever a write times out
307 /// as a result of setting this option. For example Unix typically returns
308 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
310 /// [`None`]: ../../std/option/enum.Option.html#variant.None
311 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
312 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
313 /// [`Duration`]: ../../std/time/struct.Duration.html
314 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
315 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
320 /// use std::net::TcpStream;
322 /// let stream = TcpStream::connect("127.0.0.1:8080")
323 /// .expect("Couldn't connect to the server...");
324 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
327 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
332 /// use std::net::TcpStream;
333 /// use std::time::Duration;
335 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
336 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
337 /// let err = result.unwrap_err();
338 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
340 #[stable(feature = "socket_timeout", since = "1.4.0")]
341 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
342 self.0.set_write_timeout(dur)
345 /// Returns the read timeout of this socket.
347 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
349 /// # Platform-specific behavior
351 /// Some platforms do not provide access to the current timeout.
353 /// [`None`]: ../../std/option/enum.Option.html#variant.None
354 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
359 /// use std::net::TcpStream;
361 /// let stream = TcpStream::connect("127.0.0.1:8080")
362 /// .expect("Couldn't connect to the server...");
363 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
364 /// assert_eq!(stream.read_timeout().unwrap(), None);
366 #[stable(feature = "socket_timeout", since = "1.4.0")]
367 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
368 self.0.read_timeout()
371 /// Returns the write timeout of this socket.
373 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
375 /// # Platform-specific behavior
377 /// Some platforms do not provide access to the current timeout.
379 /// [`None`]: ../../std/option/enum.Option.html#variant.None
380 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
385 /// use std::net::TcpStream;
387 /// let stream = TcpStream::connect("127.0.0.1:8080")
388 /// .expect("Couldn't connect to the server...");
389 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
390 /// assert_eq!(stream.write_timeout().unwrap(), None);
392 #[stable(feature = "socket_timeout", since = "1.4.0")]
393 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
394 self.0.write_timeout()
397 /// Receives data on the socket from the remote address to which it is
398 /// connected, without removing that data from the queue. On success,
399 /// returns the number of bytes peeked.
401 /// Successive calls return the same data. This is accomplished by passing
402 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
407 /// use std::net::TcpStream;
409 /// let stream = TcpStream::connect("127.0.0.1:8000")
410 /// .expect("couldn't bind to address");
411 /// let mut buf = [0; 10];
412 /// let len = stream.peek(&mut buf).expect("peek failed");
414 #[stable(feature = "peek", since = "1.18.0")]
415 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
419 /// Sets the value of the `TCP_NODELAY` option on this socket.
421 /// If set, this option disables the Nagle algorithm. This means that
422 /// segments are always sent as soon as possible, even if there is only a
423 /// small amount of data. When not set, data is buffered until there is a
424 /// sufficient amount to send out, thereby avoiding the frequent sending of
430 /// use std::net::TcpStream;
432 /// let stream = TcpStream::connect("127.0.0.1:8080")
433 /// .expect("Couldn't connect to the server...");
434 /// stream.set_nodelay(true).expect("set_nodelay call failed");
436 #[stable(feature = "net2_mutators", since = "1.9.0")]
437 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
438 self.0.set_nodelay(nodelay)
441 /// Gets the value of the `TCP_NODELAY` option on this socket.
443 /// For more information about this option, see [`set_nodelay`][link].
445 /// [link]: #method.set_nodelay
450 /// use std::net::TcpStream;
452 /// let stream = TcpStream::connect("127.0.0.1:8080")
453 /// .expect("Couldn't connect to the server...");
454 /// stream.set_nodelay(true).expect("set_nodelay call failed");
455 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
457 #[stable(feature = "net2_mutators", since = "1.9.0")]
458 pub fn nodelay(&self) -> io::Result<bool> {
462 /// Sets the value for the `IP_TTL` option on this socket.
464 /// This value sets the time-to-live field that is used in every packet sent
465 /// from this socket.
470 /// use std::net::TcpStream;
472 /// let stream = TcpStream::connect("127.0.0.1:8080")
473 /// .expect("Couldn't connect to the server...");
474 /// stream.set_ttl(100).expect("set_ttl call failed");
476 #[stable(feature = "net2_mutators", since = "1.9.0")]
477 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
481 /// Gets the value of the `IP_TTL` option for this socket.
483 /// For more information about this option, see [`set_ttl`][link].
485 /// [link]: #method.set_ttl
490 /// use std::net::TcpStream;
492 /// let stream = TcpStream::connect("127.0.0.1:8080")
493 /// .expect("Couldn't connect to the server...");
494 /// stream.set_ttl(100).expect("set_ttl call failed");
495 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
497 #[stable(feature = "net2_mutators", since = "1.9.0")]
498 pub fn ttl(&self) -> io::Result<u32> {
502 /// Gets the value of the `SO_ERROR` option on this socket.
504 /// This will retrieve the stored error in the underlying socket, clearing
505 /// the field in the process. This can be useful for checking errors between
511 /// use std::net::TcpStream;
513 /// let stream = TcpStream::connect("127.0.0.1:8080")
514 /// .expect("Couldn't connect to the server...");
515 /// stream.take_error().expect("No error was expected...");
517 #[stable(feature = "net2_mutators", since = "1.9.0")]
518 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
522 /// Moves this TCP stream into or out of nonblocking mode.
524 /// This will result in `read`, `write`, `recv` and `send` operations
525 /// becoming nonblocking, i.e., immediately returning from their calls.
526 /// If the IO operation is successful, `Ok` is returned and no further
527 /// action is required. If the IO operation could not be completed and needs
528 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
531 /// On Unix platforms, calling this method corresponds to calling `fcntl`
532 /// `FIONBIO`. On Windows calling this method corresponds to calling
533 /// `ioctlsocket` `FIONBIO`.
537 /// Reading bytes from a TCP stream in non-blocking mode:
540 /// use std::io::{self, Read};
541 /// use std::net::TcpStream;
543 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
544 /// .expect("Couldn't connect to the server...");
545 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
547 /// # fn wait_for_fd() { unimplemented!() }
548 /// let mut buf = vec![];
550 /// match stream.read_to_end(&mut buf) {
552 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
553 /// // wait until network socket is ready, typically implemented
554 /// // via platform-specific APIs such as epoll or IOCP
557 /// Err(e) => panic!("encountered IO error: {}", e),
560 /// println!("bytes: {:?}", buf);
563 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
564 #[stable(feature = "net2_mutators", since = "1.9.0")]
565 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
566 self.0.set_nonblocking(nonblocking)
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl Read for TcpStream {
572 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
576 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
577 self.0.read_vectored(bufs)
581 fn is_read_vectored(&self) -> bool {
582 self.0.is_read_vectored()
586 unsafe fn initializer(&self) -> Initializer {
587 // SAFETY: Read is guaranteed to work on uninitialized memory
588 unsafe { Initializer::nop() }
591 #[stable(feature = "rust1", since = "1.0.0")]
592 impl Write for TcpStream {
593 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
597 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
598 self.0.write_vectored(bufs)
602 fn is_write_vectored(&self) -> bool {
603 self.0.is_write_vectored()
606 fn flush(&mut self) -> io::Result<()> {
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl Read for &TcpStream {
612 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
616 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
617 self.0.read_vectored(bufs)
621 fn is_read_vectored(&self) -> bool {
622 self.0.is_read_vectored()
626 unsafe fn initializer(&self) -> Initializer {
627 // SAFETY: Read is guaranteed to work on uninitialized memory
628 unsafe { Initializer::nop() }
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl Write for &TcpStream {
633 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
637 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
638 self.0.write_vectored(bufs)
642 fn is_write_vectored(&self) -> bool {
643 self.0.is_write_vectored()
646 fn flush(&mut self) -> io::Result<()> {
651 impl AsInner<net_imp::TcpStream> for TcpStream {
652 fn as_inner(&self) -> &net_imp::TcpStream {
657 impl FromInner<net_imp::TcpStream> for TcpStream {
658 fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
663 impl IntoInner<net_imp::TcpStream> for TcpStream {
664 fn into_inner(self) -> net_imp::TcpStream {
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl fmt::Debug for TcpStream {
671 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677 /// Creates a new `TcpListener` which will be bound to the specified
680 /// The returned listener is ready for accepting connections.
682 /// Binding with a port number of 0 will request that the OS assigns a port
683 /// to this listener. The port allocated can be queried via the
684 /// [`local_addr`] method.
686 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
687 /// its documentation for concrete examples.
689 /// If `addr` yields multiple addresses, `bind` will be attempted with
690 /// each of the addresses until one succeeds and returns the listener. If
691 /// none of the addresses succeed in creating a listener, the error returned
692 /// from the last attempt (the last address) is returned.
694 /// [`local_addr`]: #method.local_addr
695 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
699 /// Creates a TCP listener bound to `127.0.0.1:80`:
702 /// use std::net::TcpListener;
704 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
707 /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
708 /// TCP listener bound to `127.0.0.1:443`:
711 /// use std::net::{SocketAddr, TcpListener};
714 /// SocketAddr::from(([127, 0, 0, 1], 80)),
715 /// SocketAddr::from(([127, 0, 0, 1], 443)),
717 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
719 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
721 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
724 /// Returns the local socket address of this listener.
729 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
731 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
732 /// assert_eq!(listener.local_addr().unwrap(),
733 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
735 #[stable(feature = "rust1", since = "1.0.0")]
736 pub fn local_addr(&self) -> io::Result<SocketAddr> {
740 /// Creates a new independently owned handle to the underlying socket.
742 /// The returned [`TcpListener`] is a reference to the same socket that this
743 /// object references. Both handles can be used to accept incoming
744 /// connections and options set on one listener will affect the other.
746 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
751 /// use std::net::TcpListener;
753 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
754 /// let listener_clone = listener.try_clone().unwrap();
756 #[stable(feature = "rust1", since = "1.0.0")]
757 pub fn try_clone(&self) -> io::Result<TcpListener> {
758 self.0.duplicate().map(TcpListener)
761 /// Accept a new incoming connection from this listener.
763 /// This function will block the calling thread until a new TCP connection
764 /// is established. When established, the corresponding [`TcpStream`] and the
765 /// remote peer's address will be returned.
767 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
772 /// use std::net::TcpListener;
774 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
775 /// match listener.accept() {
776 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
777 /// Err(e) => println!("couldn't get client: {:?}", e),
780 #[stable(feature = "rust1", since = "1.0.0")]
781 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
782 // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
783 // the `a` variable here is technically unused.
784 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
785 self.0.accept().map(|(a, b)| (TcpStream(a), b))
788 /// Returns an iterator over the connections being received on this
791 /// The returned iterator will never return [`None`] and will also not yield
792 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
793 /// calling [`accept`] in a loop.
795 /// [`None`]: ../../std/option/enum.Option.html#variant.None
796 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
797 /// [`accept`]: #method.accept
802 /// use std::net::TcpListener;
804 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
806 /// for stream in listener.incoming() {
809 /// println!("new client!");
811 /// Err(e) => { /* connection failed */ }
815 #[stable(feature = "rust1", since = "1.0.0")]
816 pub fn incoming(&self) -> Incoming<'_> {
817 Incoming { listener: self }
820 /// Sets the value for the `IP_TTL` option on this socket.
822 /// This value sets the time-to-live field that is used in every packet sent
823 /// from this socket.
828 /// use std::net::TcpListener;
830 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
831 /// listener.set_ttl(100).expect("could not set TTL");
833 #[stable(feature = "net2_mutators", since = "1.9.0")]
834 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
838 /// Gets the value of the `IP_TTL` option for this socket.
840 /// For more information about this option, see [`set_ttl`][link].
842 /// [link]: #method.set_ttl
847 /// use std::net::TcpListener;
849 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
850 /// listener.set_ttl(100).expect("could not set TTL");
851 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
853 #[stable(feature = "net2_mutators", since = "1.9.0")]
854 pub fn ttl(&self) -> io::Result<u32> {
858 #[stable(feature = "net2_mutators", since = "1.9.0")]
861 reason = "this option can only be set before the socket is bound"
863 #[allow(missing_docs)]
864 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
865 self.0.set_only_v6(only_v6)
868 #[stable(feature = "net2_mutators", since = "1.9.0")]
871 reason = "this option can only be set before the socket is bound"
873 #[allow(missing_docs)]
874 pub fn only_v6(&self) -> io::Result<bool> {
878 /// Gets the value of the `SO_ERROR` option on this socket.
880 /// This will retrieve the stored error in the underlying socket, clearing
881 /// the field in the process. This can be useful for checking errors between
887 /// use std::net::TcpListener;
889 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
890 /// listener.take_error().expect("No error was expected");
892 #[stable(feature = "net2_mutators", since = "1.9.0")]
893 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
897 /// Moves this TCP stream into or out of nonblocking mode.
899 /// This will result in the `accept` operation becoming nonblocking,
900 /// i.e., immediately returning from their calls. If the IO operation is
901 /// successful, `Ok` is returned and no further action is required. If the
902 /// IO operation could not be completed and needs to be retried, an error
903 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
905 /// On Unix platforms, calling this method corresponds to calling `fcntl`
906 /// `FIONBIO`. On Windows calling this method corresponds to calling
907 /// `ioctlsocket` `FIONBIO`.
911 /// Bind a TCP listener to an address, listen for connections, and read
912 /// bytes in nonblocking mode:
916 /// use std::net::TcpListener;
918 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
919 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
921 /// # fn wait_for_fd() { unimplemented!() }
922 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
923 /// for stream in listener.incoming() {
926 /// // do something with the TcpStream
927 /// handle_connection(s);
929 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
930 /// // wait until network socket is ready, typically implemented
931 /// // via platform-specific APIs such as epoll or IOCP
935 /// Err(e) => panic!("encountered IO error: {}", e),
940 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
941 #[stable(feature = "net2_mutators", since = "1.9.0")]
942 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
943 self.0.set_nonblocking(nonblocking)
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<'a> Iterator for Incoming<'a> {
949 type Item = io::Result<TcpStream>;
950 fn next(&mut self) -> Option<io::Result<TcpStream>> {
951 Some(self.listener.accept().map(|p| p.0))
955 impl AsInner<net_imp::TcpListener> for TcpListener {
956 fn as_inner(&self) -> &net_imp::TcpListener {
961 impl FromInner<net_imp::TcpListener> for TcpListener {
962 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
967 impl IntoInner<net_imp::TcpListener> for TcpListener {
968 fn into_inner(self) -> net_imp::TcpListener {
973 #[stable(feature = "rust1", since = "1.0.0")]
974 impl fmt::Debug for TcpListener {
975 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
980 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
983 use crate::io::prelude::*;
984 use crate::io::{ErrorKind, IoSlice, IoSliceMut};
985 use crate::net::test::{next_test_ip4, next_test_ip6};
987 use crate::sync::mpsc::channel;
989 use crate::time::{Duration, Instant};
991 fn each_ip(f: &mut dyn FnMut(SocketAddr)) {
1000 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
1007 match TcpListener::bind("1.1.1.1:9999") {
1009 Err(e) => assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
1014 fn connect_error() {
1015 match TcpStream::connect("0.0.0.0:1") {
1018 e.kind() == ErrorKind::ConnectionRefused
1019 || e.kind() == ErrorKind::InvalidInput
1020 || e.kind() == ErrorKind::AddrInUse
1021 || e.kind() == ErrorKind::AddrNotAvailable,
1022 "bad error: {} {:?}",
1030 fn listen_localhost() {
1031 let socket_addr = next_test_ip4();
1032 let listener = t!(TcpListener::bind(&socket_addr));
1034 let _t = thread::spawn(move || {
1035 let mut stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
1036 t!(stream.write(&[144]));
1039 let mut stream = t!(listener.accept()).0;
1041 t!(stream.read(&mut buf));
1042 assert!(buf[0] == 144);
1046 fn connect_loopback() {
1047 each_ip(&mut |addr| {
1048 let acceptor = t!(TcpListener::bind(&addr));
1050 let _t = thread::spawn(move || {
1051 let host = match addr {
1052 SocketAddr::V4(..) => "127.0.0.1",
1053 SocketAddr::V6(..) => "::1",
1055 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
1056 t!(stream.write(&[66]));
1059 let mut stream = t!(acceptor.accept()).0;
1061 t!(stream.read(&mut buf));
1062 assert!(buf[0] == 66);
1068 each_ip(&mut |addr| {
1069 let acceptor = t!(TcpListener::bind(&addr));
1071 let (tx, rx) = channel();
1072 let _t = thread::spawn(move || {
1073 let mut stream = t!(TcpStream::connect(&addr));
1074 t!(stream.write(&[99]));
1075 tx.send(t!(stream.local_addr())).unwrap();
1078 let (mut stream, addr) = t!(acceptor.accept());
1080 t!(stream.read(&mut buf));
1081 assert!(buf[0] == 99);
1082 assert_eq!(addr, t!(rx.recv()));
1088 each_ip(&mut |addr| {
1089 let acceptor = t!(TcpListener::bind(&addr));
1091 let _t = thread::spawn(move || {
1092 let _stream = t!(TcpStream::connect(&addr));
1096 let mut stream = t!(acceptor.accept()).0;
1098 let nread = t!(stream.read(&mut buf));
1099 assert_eq!(nread, 0);
1100 let nread = t!(stream.read(&mut buf));
1101 assert_eq!(nread, 0);
1107 each_ip(&mut |addr| {
1108 let acceptor = t!(TcpListener::bind(&addr));
1110 let (tx, rx) = channel();
1111 let _t = thread::spawn(move || {
1112 drop(t!(TcpStream::connect(&addr)));
1113 tx.send(()).unwrap();
1116 let mut stream = t!(acceptor.accept()).0;
1119 match stream.write(&buf) {
1123 e.kind() == ErrorKind::ConnectionReset
1124 || e.kind() == ErrorKind::BrokenPipe
1125 || e.kind() == ErrorKind::ConnectionAborted,
1126 "unknown error: {}",
1135 fn multiple_connect_serial() {
1136 each_ip(&mut |addr| {
1138 let acceptor = t!(TcpListener::bind(&addr));
1140 let _t = thread::spawn(move || {
1142 let mut stream = t!(TcpStream::connect(&addr));
1143 t!(stream.write(&[99]));
1147 for stream in acceptor.incoming().take(max) {
1148 let mut stream = t!(stream);
1150 t!(stream.read(&mut buf));
1151 assert_eq!(buf[0], 99);
1157 fn multiple_connect_interleaved_greedy_schedule() {
1158 const MAX: usize = 10;
1159 each_ip(&mut |addr| {
1160 let acceptor = t!(TcpListener::bind(&addr));
1162 let _t = thread::spawn(move || {
1163 let acceptor = acceptor;
1164 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
1165 // Start another thread to handle the connection
1166 let _t = thread::spawn(move || {
1167 let mut stream = t!(stream);
1169 t!(stream.read(&mut buf));
1170 assert!(buf[0] == i as u8);
1178 fn connect(i: usize, addr: SocketAddr) {
1183 let t = thread::spawn(move || {
1184 let mut stream = t!(TcpStream::connect(&addr));
1185 // Connect again before writing
1186 connect(i + 1, addr);
1187 t!(stream.write(&[i as u8]));
1189 t.join().ok().expect("thread panicked");
1194 fn multiple_connect_interleaved_lazy_schedule() {
1195 const MAX: usize = 10;
1196 each_ip(&mut |addr| {
1197 let acceptor = t!(TcpListener::bind(&addr));
1199 let _t = thread::spawn(move || {
1200 for stream in acceptor.incoming().take(MAX) {
1201 // Start another thread to handle the connection
1202 let _t = thread::spawn(move || {
1203 let mut stream = t!(stream);
1205 t!(stream.read(&mut buf));
1206 assert!(buf[0] == 99);
1214 fn connect(i: usize, addr: SocketAddr) {
1219 let t = thread::spawn(move || {
1220 let mut stream = t!(TcpStream::connect(&addr));
1221 connect(i + 1, addr);
1222 t!(stream.write(&[99]));
1224 t.join().ok().expect("thread panicked");
1229 fn socket_and_peer_name() {
1230 each_ip(&mut |addr| {
1231 let listener = t!(TcpListener::bind(&addr));
1232 let so_name = t!(listener.local_addr());
1233 assert_eq!(addr, so_name);
1234 let _t = thread::spawn(move || {
1235 t!(listener.accept());
1238 let stream = t!(TcpStream::connect(&addr));
1239 assert_eq!(addr, t!(stream.peer_addr()));
1245 each_ip(&mut |addr| {
1246 let (tx, rx) = channel();
1247 let srv = t!(TcpListener::bind(&addr));
1248 let _t = thread::spawn(move || {
1249 let mut cl = t!(srv.accept()).0;
1250 cl.write(&[10]).unwrap();
1252 t!(cl.read(&mut b));
1253 tx.send(()).unwrap();
1256 let mut c = t!(TcpStream::connect(&addr));
1257 let mut b = [0; 10];
1258 assert_eq!(c.read(&mut b).unwrap(), 1);
1265 fn read_vectored() {
1266 each_ip(&mut |addr| {
1267 let srv = t!(TcpListener::bind(&addr));
1268 let mut s1 = t!(TcpStream::connect(&addr));
1269 let mut s2 = t!(srv.accept()).0;
1271 let len = s1.write(&[10, 11, 12]).unwrap();
1277 let len = t!(s2.read_vectored(&mut [
1278 IoSliceMut::new(&mut a),
1279 IoSliceMut::new(&mut b),
1280 IoSliceMut::new(&mut c)
1283 assert_eq!(b, [10]);
1284 // some implementations don't support readv, so we may only fill the first buffer
1285 assert!(len == 1 || c == [11, 12, 0]);
1290 fn write_vectored() {
1291 each_ip(&mut |addr| {
1292 let srv = t!(TcpListener::bind(&addr));
1293 let mut s1 = t!(TcpStream::connect(&addr));
1294 let mut s2 = t!(srv.accept()).0;
1299 t!(s1.write_vectored(&[IoSlice::new(&a), IoSlice::new(&b), IoSlice::new(&c)]));
1301 let mut buf = [0; 4];
1302 let len = t!(s2.read(&mut buf));
1303 // some implementations don't support writev, so we may only write the first buffer
1305 assert_eq!(buf, [10, 0, 0, 0]);
1308 assert_eq!(buf, [10, 11, 12, 0]);
1315 each_ip(&mut |addr| {
1316 let listener1 = t!(TcpListener::bind(&addr));
1317 match TcpListener::bind(&addr) {
1318 Ok(listener2) => panic!(
1319 "This system (perhaps due to options set by TcpListener::bind) \
1320 permits double binding: {:?} and {:?}",
1321 listener1, listener2
1325 e.kind() == ErrorKind::ConnectionRefused
1326 || e.kind() == ErrorKind::Other
1327 || e.kind() == ErrorKind::AddrInUse,
1328 "unknown error: {} {:?}",
1338 fn tcp_clone_smoke() {
1339 each_ip(&mut |addr| {
1340 let acceptor = t!(TcpListener::bind(&addr));
1342 let _t = thread::spawn(move || {
1343 let mut s = t!(TcpStream::connect(&addr));
1344 let mut buf = [0, 0];
1345 assert_eq!(s.read(&mut buf).unwrap(), 1);
1346 assert_eq!(buf[0], 1);
1350 let mut s1 = t!(acceptor.accept()).0;
1351 let s2 = t!(s1.try_clone());
1353 let (tx1, rx1) = channel();
1354 let (tx2, rx2) = channel();
1355 let _t = thread::spawn(move || {
1357 rx1.recv().unwrap();
1359 tx2.send(()).unwrap();
1361 tx1.send(()).unwrap();
1362 let mut buf = [0, 0];
1363 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1364 rx2.recv().unwrap();
1369 fn tcp_clone_two_read() {
1370 each_ip(&mut |addr| {
1371 let acceptor = t!(TcpListener::bind(&addr));
1372 let (tx1, rx) = channel();
1373 let tx2 = tx1.clone();
1375 let _t = thread::spawn(move || {
1376 let mut s = t!(TcpStream::connect(&addr));
1383 let mut s1 = t!(acceptor.accept()).0;
1384 let s2 = t!(s1.try_clone());
1386 let (done, rx) = channel();
1387 let _t = thread::spawn(move || {
1389 let mut buf = [0, 0];
1390 t!(s2.read(&mut buf));
1391 tx2.send(()).unwrap();
1392 done.send(()).unwrap();
1394 let mut buf = [0, 0];
1395 t!(s1.read(&mut buf));
1396 tx1.send(()).unwrap();
1403 fn tcp_clone_two_write() {
1404 each_ip(&mut |addr| {
1405 let acceptor = t!(TcpListener::bind(&addr));
1407 let _t = thread::spawn(move || {
1408 let mut s = t!(TcpStream::connect(&addr));
1409 let mut buf = [0, 1];
1410 t!(s.read(&mut buf));
1411 t!(s.read(&mut buf));
1414 let mut s1 = t!(acceptor.accept()).0;
1415 let s2 = t!(s1.try_clone());
1417 let (done, rx) = channel();
1418 let _t = thread::spawn(move || {
1421 done.send(()).unwrap();
1430 // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1431 #[cfg_attr(target_env = "sgx", ignore)]
1432 fn shutdown_smoke() {
1433 each_ip(&mut |addr| {
1434 let a = t!(TcpListener::bind(&addr));
1435 let _t = thread::spawn(move || {
1436 let mut c = t!(a.accept()).0;
1438 assert_eq!(c.read(&mut b).unwrap(), 0);
1442 let mut s = t!(TcpStream::connect(&addr));
1443 t!(s.shutdown(Shutdown::Write));
1444 assert!(s.write(&[1]).is_err());
1446 assert_eq!(t!(s.read(&mut b)), 1);
1447 assert_eq!(b[0], 1);
1452 // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1453 #[cfg_attr(target_env = "sgx", ignore)]
1454 fn close_readwrite_smoke() {
1455 each_ip(&mut |addr| {
1456 let a = t!(TcpListener::bind(&addr));
1457 let (tx, rx) = channel::<()>();
1458 let _t = thread::spawn(move || {
1459 let _s = t!(a.accept());
1464 let mut s = t!(TcpStream::connect(&addr));
1465 let mut s2 = t!(s.try_clone());
1467 // closing should prevent reads/writes
1468 t!(s.shutdown(Shutdown::Write));
1469 assert!(s.write(&[0]).is_err());
1470 t!(s.shutdown(Shutdown::Read));
1471 assert_eq!(s.read(&mut b).unwrap(), 0);
1473 // closing should affect previous handles
1474 assert!(s2.write(&[0]).is_err());
1475 assert_eq!(s2.read(&mut b).unwrap(), 0);
1477 // closing should affect new handles
1478 let mut s3 = t!(s.try_clone());
1479 assert!(s3.write(&[0]).is_err());
1480 assert_eq!(s3.read(&mut b).unwrap(), 0);
1482 // make sure these don't die
1483 let _ = s2.shutdown(Shutdown::Read);
1484 let _ = s2.shutdown(Shutdown::Write);
1485 let _ = s3.shutdown(Shutdown::Read);
1486 let _ = s3.shutdown(Shutdown::Write);
1492 #[cfg(unix)] // test doesn't work on Windows, see #31657
1493 fn close_read_wakes_up() {
1494 each_ip(&mut |addr| {
1495 let a = t!(TcpListener::bind(&addr));
1496 let (tx1, rx) = channel::<()>();
1497 let _t = thread::spawn(move || {
1498 let _s = t!(a.accept());
1502 let s = t!(TcpStream::connect(&addr));
1503 let s2 = t!(s.try_clone());
1504 let (tx, rx) = channel();
1505 let _t = thread::spawn(move || {
1507 assert_eq!(t!(s2.read(&mut [0])), 0);
1508 tx.send(()).unwrap();
1510 // this should wake up the child thread
1511 t!(s.shutdown(Shutdown::Read));
1513 // this test will never finish if the child doesn't wake up
1520 fn clone_while_reading() {
1521 each_ip(&mut |addr| {
1522 let accept = t!(TcpListener::bind(&addr));
1524 // Enqueue a thread to write to a socket
1525 let (tx, rx) = channel();
1526 let (txdone, rxdone) = channel();
1527 let txdone2 = txdone.clone();
1528 let _t = thread::spawn(move || {
1529 let mut tcp = t!(TcpStream::connect(&addr));
1531 t!(tcp.write(&[0]));
1532 txdone2.send(()).unwrap();
1535 // Spawn off a reading clone
1536 let tcp = t!(accept.accept()).0;
1537 let tcp2 = t!(tcp.try_clone());
1538 let txdone3 = txdone.clone();
1539 let _t = thread::spawn(move || {
1540 let mut tcp2 = tcp2;
1541 t!(tcp2.read(&mut [0]));
1542 txdone3.send(()).unwrap();
1545 // Try to ensure that the reading clone is indeed reading
1547 thread::yield_now();
1550 // clone the handle again while it's reading, then let it finish the
1552 let _ = t!(tcp.try_clone());
1553 tx.send(()).unwrap();
1554 rxdone.recv().unwrap();
1555 rxdone.recv().unwrap();
1560 fn clone_accept_smoke() {
1561 each_ip(&mut |addr| {
1562 let a = t!(TcpListener::bind(&addr));
1563 let a2 = t!(a.try_clone());
1565 let _t = thread::spawn(move || {
1566 let _ = TcpStream::connect(&addr);
1568 let _t = thread::spawn(move || {
1569 let _ = TcpStream::connect(&addr);
1578 fn clone_accept_concurrent() {
1579 each_ip(&mut |addr| {
1580 let a = t!(TcpListener::bind(&addr));
1581 let a2 = t!(a.try_clone());
1583 let (tx, rx) = channel();
1584 let tx2 = tx.clone();
1586 let _t = thread::spawn(move || {
1587 tx.send(t!(a.accept())).unwrap();
1589 let _t = thread::spawn(move || {
1590 tx2.send(t!(a2.accept())).unwrap();
1593 let _t = thread::spawn(move || {
1594 let _ = TcpStream::connect(&addr);
1596 let _t = thread::spawn(move || {
1597 let _ = TcpStream::connect(&addr);
1607 #[cfg(not(target_env = "sgx"))]
1608 fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1611 #[cfg(target_env = "sgx")]
1612 fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1616 #[cfg(target_env = "sgx")]
1617 use crate::os::fortanix_sgx::io::AsRawFd;
1619 use crate::os::unix::io::AsRawFd;
1620 #[cfg(not(windows))]
1621 fn render_inner(addr: &dyn AsRawFd) -> impl fmt::Debug {
1625 fn render_inner(addr: &dyn crate::os::windows::io::AsRawSocket) -> impl fmt::Debug {
1626 addr.as_raw_socket()
1629 let inner_name = if cfg!(windows) { "socket" } else { "fd" };
1630 let socket_addr = next_test_ip4();
1632 let listener = t!(TcpListener::bind(&socket_addr));
1633 let compare = format!(
1634 "TcpListener {{ addr: {:?}, {}: {:?} }}",
1635 render_socket_addr(&socket_addr),
1637 render_inner(&listener)
1639 assert_eq!(format!("{:?}", listener), compare);
1641 let stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
1642 let compare = format!(
1643 "TcpStream {{ addr: {:?}, peer: {:?}, {}: {:?} }}",
1644 render_socket_addr(&stream.local_addr().unwrap()),
1645 render_socket_addr(&stream.peer_addr().unwrap()),
1647 render_inner(&stream)
1649 assert_eq!(format!("{:?}", stream), compare);
1652 // FIXME: re-enabled openbsd tests once their socket timeout code
1653 // no longer has rounding errors.
1654 // VxWorks ignores SO_SNDTIMEO.
1655 #[cfg_attr(any(target_os = "netbsd", target_os = "openbsd", target_os = "vxworks"), ignore)]
1656 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1659 let addr = next_test_ip4();
1660 let listener = t!(TcpListener::bind(&addr));
1662 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1663 let dur = Duration::new(15410, 0);
1665 assert_eq!(None, t!(stream.read_timeout()));
1667 t!(stream.set_read_timeout(Some(dur)));
1668 assert_eq!(Some(dur), t!(stream.read_timeout()));
1670 assert_eq!(None, t!(stream.write_timeout()));
1672 t!(stream.set_write_timeout(Some(dur)));
1673 assert_eq!(Some(dur), t!(stream.write_timeout()));
1675 t!(stream.set_read_timeout(None));
1676 assert_eq!(None, t!(stream.read_timeout()));
1678 t!(stream.set_write_timeout(None));
1679 assert_eq!(None, t!(stream.write_timeout()));
1684 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1685 fn test_read_timeout() {
1686 let addr = next_test_ip4();
1687 let listener = t!(TcpListener::bind(&addr));
1689 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1690 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1692 let mut buf = [0; 10];
1693 let start = Instant::now();
1694 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1696 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1697 "unexpected_error: {:?}",
1700 assert!(start.elapsed() > Duration::from_millis(400));
1705 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1706 fn test_read_with_timeout() {
1707 let addr = next_test_ip4();
1708 let listener = t!(TcpListener::bind(&addr));
1710 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1711 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1713 let mut other_end = t!(listener.accept()).0;
1714 t!(other_end.write_all(b"hello world"));
1716 let mut buf = [0; 11];
1717 t!(stream.read(&mut buf));
1718 assert_eq!(b"hello world", &buf[..]);
1720 let start = Instant::now();
1721 let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1723 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1724 "unexpected_error: {:?}",
1727 assert!(start.elapsed() > Duration::from_millis(400));
1731 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1732 // when passed zero Durations
1734 fn test_timeout_zero_duration() {
1735 let addr = next_test_ip4();
1737 let listener = t!(TcpListener::bind(&addr));
1738 let stream = t!(TcpStream::connect(&addr));
1740 let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1741 let err = result.unwrap_err();
1742 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1744 let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1745 let err = result.unwrap_err();
1746 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1752 #[cfg_attr(target_env = "sgx", ignore)]
1754 let addr = next_test_ip4();
1755 let _listener = t!(TcpListener::bind(&addr));
1757 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1759 assert_eq!(false, t!(stream.nodelay()));
1760 t!(stream.set_nodelay(true));
1761 assert_eq!(true, t!(stream.nodelay()));
1762 t!(stream.set_nodelay(false));
1763 assert_eq!(false, t!(stream.nodelay()));
1767 #[cfg_attr(target_env = "sgx", ignore)]
1771 let addr = next_test_ip4();
1772 let listener = t!(TcpListener::bind(&addr));
1774 t!(listener.set_ttl(ttl));
1775 assert_eq!(ttl, t!(listener.ttl()));
1777 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1779 t!(stream.set_ttl(ttl));
1780 assert_eq!(ttl, t!(stream.ttl()));
1784 #[cfg_attr(target_env = "sgx", ignore)]
1785 fn set_nonblocking() {
1786 let addr = next_test_ip4();
1787 let listener = t!(TcpListener::bind(&addr));
1789 t!(listener.set_nonblocking(true));
1790 t!(listener.set_nonblocking(false));
1792 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1794 t!(stream.set_nonblocking(false));
1795 t!(stream.set_nonblocking(true));
1798 match stream.read(&mut buf) {
1799 Ok(_) => panic!("expected error"),
1800 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1801 Err(e) => panic!("unexpected error {}", e),
1806 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1808 each_ip(&mut |addr| {
1809 let (txdone, rxdone) = channel();
1811 let srv = t!(TcpListener::bind(&addr));
1812 let _t = thread::spawn(move || {
1813 let mut cl = t!(srv.accept()).0;
1814 cl.write(&[1, 3, 3, 7]).unwrap();
1818 let mut c = t!(TcpStream::connect(&addr));
1819 let mut b = [0; 10];
1821 let len = c.peek(&mut b).unwrap();
1824 let len = c.read(&mut b).unwrap();
1827 t!(c.set_nonblocking(true));
1828 match c.peek(&mut b) {
1829 Ok(_) => panic!("expected error"),
1830 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1831 Err(e) => panic!("unexpected error {}", e),
1833 t!(txdone.send(()));
1838 #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1839 fn connect_timeout_valid() {
1840 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1841 let addr = listener.local_addr().unwrap();
1842 TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();