]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/tcp.rs
Rollup merge of #107074 - lcnr:validate-dont-skip-opaque, r=compiler-errors
[rust.git] / library / std / src / net / tcp.rs
1 #![deny(unsafe_op_in_unsafe_fn)]
2
3 #[cfg(all(test, not(target_os = "emscripten")))]
4 mod tests;
5
6 use crate::io::prelude::*;
7
8 use crate::fmt;
9 use crate::io::{self, IoSlice, IoSliceMut};
10 use crate::iter::FusedIterator;
11 use crate::net::{Shutdown, SocketAddr, ToSocketAddrs};
12 use crate::sys_common::net as net_imp;
13 use crate::sys_common::{AsInner, FromInner, IntoInner};
14 use crate::time::Duration;
15
16 /// A TCP stream between a local and a remote socket.
17 ///
18 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
19 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
20 /// by [reading] and [writing] to it.
21 ///
22 /// The connection will be closed when the value is dropped. The reading and writing
23 /// portions of the connection can also be shut down individually with the [`shutdown`]
24 /// method.
25 ///
26 /// The Transmission Control Protocol is specified in [IETF RFC 793].
27 ///
28 /// [`accept`]: TcpListener::accept
29 /// [`connect`]: TcpStream::connect
30 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
31 /// [reading]: Read
32 /// [`shutdown`]: TcpStream::shutdown
33 /// [writing]: Write
34 ///
35 /// # Examples
36 ///
37 /// ```no_run
38 /// use std::io::prelude::*;
39 /// use std::net::TcpStream;
40 ///
41 /// fn main() -> std::io::Result<()> {
42 ///     let mut stream = TcpStream::connect("127.0.0.1:34254")?;
43 ///
44 ///     stream.write(&[1])?;
45 ///     stream.read(&mut [0; 128])?;
46 ///     Ok(())
47 /// } // the stream is closed here
48 /// ```
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub struct TcpStream(net_imp::TcpStream);
51
52 /// A TCP socket server, listening for connections.
53 ///
54 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
55 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
56 /// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
57 ///
58 /// The socket will be closed when the value is dropped.
59 ///
60 /// The Transmission Control Protocol is specified in [IETF RFC 793].
61 ///
62 /// [`accept`]: TcpListener::accept
63 /// [`bind`]: TcpListener::bind
64 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
65 ///
66 /// # Examples
67 ///
68 /// ```no_run
69 /// use std::net::{TcpListener, TcpStream};
70 ///
71 /// fn handle_client(stream: TcpStream) {
72 ///     // ...
73 /// }
74 ///
75 /// fn main() -> std::io::Result<()> {
76 ///     let listener = TcpListener::bind("127.0.0.1:80")?;
77 ///
78 ///     // accept connections and process them serially
79 ///     for stream in listener.incoming() {
80 ///         handle_client(stream?);
81 ///     }
82 ///     Ok(())
83 /// }
84 /// ```
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct TcpListener(net_imp::TcpListener);
87
88 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
89 ///
90 /// This `struct` is created by the [`TcpListener::incoming`] method.
91 /// See its documentation for more.
92 ///
93 /// [`accept`]: TcpListener::accept
94 #[must_use = "iterators are lazy and do nothing unless consumed"]
95 #[stable(feature = "rust1", since = "1.0.0")]
96 #[derive(Debug)]
97 pub struct Incoming<'a> {
98     listener: &'a TcpListener,
99 }
100
101 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
102 ///
103 /// This `struct` is created by the [`TcpListener::into_incoming`] method.
104 /// See its documentation for more.
105 ///
106 /// [`accept`]: TcpListener::accept
107 #[derive(Debug)]
108 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
109 pub struct IntoIncoming {
110     listener: TcpListener,
111 }
112
113 impl TcpStream {
114     /// Opens a TCP connection to a remote host.
115     ///
116     /// `addr` is an address of the remote host. Anything which implements
117     /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
118     /// documentation for concrete examples.
119     ///
120     /// If `addr` yields multiple addresses, `connect` will be attempted with
121     /// each of the addresses until a connection is successful. If none of
122     /// the addresses result in a successful connection, the error returned from
123     /// the last connection attempt (the last address) is returned.
124     ///
125     /// # Examples
126     ///
127     /// Open a TCP connection to `127.0.0.1:8080`:
128     ///
129     /// ```no_run
130     /// use std::net::TcpStream;
131     ///
132     /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
133     ///     println!("Connected to the server!");
134     /// } else {
135     ///     println!("Couldn't connect to server...");
136     /// }
137     /// ```
138     ///
139     /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
140     /// a TCP connection to `127.0.0.1:8081`:
141     ///
142     /// ```no_run
143     /// use std::net::{SocketAddr, TcpStream};
144     ///
145     /// let addrs = [
146     ///     SocketAddr::from(([127, 0, 0, 1], 8080)),
147     ///     SocketAddr::from(([127, 0, 0, 1], 8081)),
148     /// ];
149     /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
150     ///     println!("Connected to the server!");
151     /// } else {
152     ///     println!("Couldn't connect to server...");
153     /// }
154     /// ```
155     #[stable(feature = "rust1", since = "1.0.0")]
156     pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
157         super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
158     }
159
160     /// Opens a TCP connection to a remote host with a timeout.
161     ///
162     /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
163     /// timeout must be applied to individual addresses.
164     ///
165     /// It is an error to pass a zero `Duration` to this function.
166     ///
167     /// Unlike other methods on `TcpStream`, this does not correspond to a
168     /// single system call. It instead calls `connect` in nonblocking mode and
169     /// then uses an OS-specific mechanism to await the completion of the
170     /// connection request.
171     #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
172     pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
173         net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
174     }
175
176     /// Returns the socket address of the remote peer of this TCP connection.
177     ///
178     /// # Examples
179     ///
180     /// ```no_run
181     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
182     ///
183     /// let stream = TcpStream::connect("127.0.0.1:8080")
184     ///                        .expect("Couldn't connect to the server...");
185     /// assert_eq!(stream.peer_addr().unwrap(),
186     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
187     /// ```
188     #[stable(feature = "rust1", since = "1.0.0")]
189     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
190         self.0.peer_addr()
191     }
192
193     /// Returns the socket address of the local half of this TCP connection.
194     ///
195     /// # Examples
196     ///
197     /// ```no_run
198     /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
199     ///
200     /// let stream = TcpStream::connect("127.0.0.1:8080")
201     ///                        .expect("Couldn't connect to the server...");
202     /// assert_eq!(stream.local_addr().unwrap().ip(),
203     ///            IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
204     /// ```
205     #[stable(feature = "rust1", since = "1.0.0")]
206     pub fn local_addr(&self) -> io::Result<SocketAddr> {
207         self.0.socket_addr()
208     }
209
210     /// Shuts down the read, write, or both halves of this connection.
211     ///
212     /// This function will cause all pending and future I/O on the specified
213     /// portions to return immediately with an appropriate value (see the
214     /// documentation of [`Shutdown`]).
215     ///
216     /// # Platform-specific behavior
217     ///
218     /// Calling this function multiple times may result in different behavior,
219     /// depending on the operating system. On Linux, the second call will
220     /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
221     /// This may change in the future.
222     ///
223     /// # Examples
224     ///
225     /// ```no_run
226     /// use std::net::{Shutdown, TcpStream};
227     ///
228     /// let stream = TcpStream::connect("127.0.0.1:8080")
229     ///                        .expect("Couldn't connect to the server...");
230     /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
231     /// ```
232     #[stable(feature = "rust1", since = "1.0.0")]
233     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
234         self.0.shutdown(how)
235     }
236
237     /// Creates a new independently owned handle to the underlying socket.
238     ///
239     /// The returned `TcpStream` is a reference to the same stream that this
240     /// object references. Both handles will read and write the same stream of
241     /// data, and options set on one stream will be propagated to the other
242     /// stream.
243     ///
244     /// # Examples
245     ///
246     /// ```no_run
247     /// use std::net::TcpStream;
248     ///
249     /// let stream = TcpStream::connect("127.0.0.1:8080")
250     ///                        .expect("Couldn't connect to the server...");
251     /// let stream_clone = stream.try_clone().expect("clone failed...");
252     /// ```
253     #[stable(feature = "rust1", since = "1.0.0")]
254     pub fn try_clone(&self) -> io::Result<TcpStream> {
255         self.0.duplicate().map(TcpStream)
256     }
257
258     /// Sets the read timeout to the timeout specified.
259     ///
260     /// If the value specified is [`None`], then [`read`] calls will block
261     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
262     /// passed to this method.
263     ///
264     /// # Platform-specific behavior
265     ///
266     /// Platforms may return a different error code whenever a read times out as
267     /// a result of setting this option. For example Unix typically returns an
268     /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
269     ///
270     /// [`read`]: Read::read
271     /// [`WouldBlock`]: io::ErrorKind::WouldBlock
272     /// [`TimedOut`]: io::ErrorKind::TimedOut
273     ///
274     /// # Examples
275     ///
276     /// ```no_run
277     /// use std::net::TcpStream;
278     ///
279     /// let stream = TcpStream::connect("127.0.0.1:8080")
280     ///                        .expect("Couldn't connect to the server...");
281     /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
282     /// ```
283     ///
284     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
285     /// method:
286     ///
287     /// ```no_run
288     /// use std::io;
289     /// use std::net::TcpStream;
290     /// use std::time::Duration;
291     ///
292     /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
293     /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
294     /// let err = result.unwrap_err();
295     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
296     /// ```
297     #[stable(feature = "socket_timeout", since = "1.4.0")]
298     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
299         self.0.set_read_timeout(dur)
300     }
301
302     /// Sets the write timeout to the timeout specified.
303     ///
304     /// If the value specified is [`None`], then [`write`] calls will block
305     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
306     /// passed to this method.
307     ///
308     /// # Platform-specific behavior
309     ///
310     /// Platforms may return a different error code whenever a write times out
311     /// as a result of setting this option. For example Unix typically returns
312     /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
313     ///
314     /// [`write`]: Write::write
315     /// [`WouldBlock`]: io::ErrorKind::WouldBlock
316     /// [`TimedOut`]: io::ErrorKind::TimedOut
317     ///
318     /// # Examples
319     ///
320     /// ```no_run
321     /// use std::net::TcpStream;
322     ///
323     /// let stream = TcpStream::connect("127.0.0.1:8080")
324     ///                        .expect("Couldn't connect to the server...");
325     /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
326     /// ```
327     ///
328     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
329     /// method:
330     ///
331     /// ```no_run
332     /// use std::io;
333     /// use std::net::TcpStream;
334     /// use std::time::Duration;
335     ///
336     /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
337     /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
338     /// let err = result.unwrap_err();
339     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
340     /// ```
341     #[stable(feature = "socket_timeout", since = "1.4.0")]
342     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
343         self.0.set_write_timeout(dur)
344     }
345
346     /// Returns the read timeout of this socket.
347     ///
348     /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
349     ///
350     /// # Platform-specific behavior
351     ///
352     /// Some platforms do not provide access to the current timeout.
353     ///
354     /// [`read`]: Read::read
355     ///
356     /// # Examples
357     ///
358     /// ```no_run
359     /// use std::net::TcpStream;
360     ///
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);
365     /// ```
366     #[stable(feature = "socket_timeout", since = "1.4.0")]
367     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
368         self.0.read_timeout()
369     }
370
371     /// Returns the write timeout of this socket.
372     ///
373     /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
374     ///
375     /// # Platform-specific behavior
376     ///
377     /// Some platforms do not provide access to the current timeout.
378     ///
379     /// [`write`]: Write::write
380     ///
381     /// # Examples
382     ///
383     /// ```no_run
384     /// use std::net::TcpStream;
385     ///
386     /// let stream = TcpStream::connect("127.0.0.1:8080")
387     ///                        .expect("Couldn't connect to the server...");
388     /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
389     /// assert_eq!(stream.write_timeout().unwrap(), None);
390     /// ```
391     #[stable(feature = "socket_timeout", since = "1.4.0")]
392     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
393         self.0.write_timeout()
394     }
395
396     /// Receives data on the socket from the remote address to which it is
397     /// connected, without removing that data from the queue. On success,
398     /// returns the number of bytes peeked.
399     ///
400     /// Successive calls return the same data. This is accomplished by passing
401     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
402     ///
403     /// # Examples
404     ///
405     /// ```no_run
406     /// use std::net::TcpStream;
407     ///
408     /// let stream = TcpStream::connect("127.0.0.1:8000")
409     ///                        .expect("Couldn't connect to the server...");
410     /// let mut buf = [0; 10];
411     /// let len = stream.peek(&mut buf).expect("peek failed");
412     /// ```
413     #[stable(feature = "peek", since = "1.18.0")]
414     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
415         self.0.peek(buf)
416     }
417
418     /// Sets the value of the `SO_LINGER` option on this socket.
419     ///
420     /// This value controls how the socket is closed when data remains
421     /// to be sent. If `SO_LINGER` is set, the socket will remain open
422     /// for the specified duration as the system attempts to send pending data.
423     /// Otherwise, the system may close the socket immediately, or wait for a
424     /// default timeout.
425     ///
426     /// # Examples
427     ///
428     /// ```no_run
429     /// #![feature(tcp_linger)]
430     ///
431     /// use std::net::TcpStream;
432     /// use std::time::Duration;
433     ///
434     /// let stream = TcpStream::connect("127.0.0.1:8080")
435     ///                        .expect("Couldn't connect to the server...");
436     /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
437     /// ```
438     #[unstable(feature = "tcp_linger", issue = "88494")]
439     pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
440         self.0.set_linger(linger)
441     }
442
443     /// Gets the value of the `SO_LINGER` option on this socket.
444     ///
445     /// For more information about this option, see [`TcpStream::set_linger`].
446     ///
447     /// # Examples
448     ///
449     /// ```no_run
450     /// #![feature(tcp_linger)]
451     ///
452     /// use std::net::TcpStream;
453     /// use std::time::Duration;
454     ///
455     /// let stream = TcpStream::connect("127.0.0.1:8080")
456     ///                        .expect("Couldn't connect to the server...");
457     /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
458     /// assert_eq!(stream.linger().unwrap(), Some(Duration::from_secs(0)));
459     /// ```
460     #[unstable(feature = "tcp_linger", issue = "88494")]
461     pub fn linger(&self) -> io::Result<Option<Duration>> {
462         self.0.linger()
463     }
464
465     /// Sets the value of the `TCP_NODELAY` option on this socket.
466     ///
467     /// If set, this option disables the Nagle algorithm. This means that
468     /// segments are always sent as soon as possible, even if there is only a
469     /// small amount of data. When not set, data is buffered until there is a
470     /// sufficient amount to send out, thereby avoiding the frequent sending of
471     /// small packets.
472     ///
473     /// # Examples
474     ///
475     /// ```no_run
476     /// use std::net::TcpStream;
477     ///
478     /// let stream = TcpStream::connect("127.0.0.1:8080")
479     ///                        .expect("Couldn't connect to the server...");
480     /// stream.set_nodelay(true).expect("set_nodelay call failed");
481     /// ```
482     #[stable(feature = "net2_mutators", since = "1.9.0")]
483     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
484         self.0.set_nodelay(nodelay)
485     }
486
487     /// Gets the value of the `TCP_NODELAY` option on this socket.
488     ///
489     /// For more information about this option, see [`TcpStream::set_nodelay`].
490     ///
491     /// # Examples
492     ///
493     /// ```no_run
494     /// use std::net::TcpStream;
495     ///
496     /// let stream = TcpStream::connect("127.0.0.1:8080")
497     ///                        .expect("Couldn't connect to the server...");
498     /// stream.set_nodelay(true).expect("set_nodelay call failed");
499     /// assert_eq!(stream.nodelay().unwrap_or(false), true);
500     /// ```
501     #[stable(feature = "net2_mutators", since = "1.9.0")]
502     pub fn nodelay(&self) -> io::Result<bool> {
503         self.0.nodelay()
504     }
505
506     /// Sets the value for the `IP_TTL` option on this socket.
507     ///
508     /// This value sets the time-to-live field that is used in every packet sent
509     /// from this socket.
510     ///
511     /// # Examples
512     ///
513     /// ```no_run
514     /// use std::net::TcpStream;
515     ///
516     /// let stream = TcpStream::connect("127.0.0.1:8080")
517     ///                        .expect("Couldn't connect to the server...");
518     /// stream.set_ttl(100).expect("set_ttl call failed");
519     /// ```
520     #[stable(feature = "net2_mutators", since = "1.9.0")]
521     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
522         self.0.set_ttl(ttl)
523     }
524
525     /// Gets the value of the `IP_TTL` option for this socket.
526     ///
527     /// For more information about this option, see [`TcpStream::set_ttl`].
528     ///
529     /// # Examples
530     ///
531     /// ```no_run
532     /// use std::net::TcpStream;
533     ///
534     /// let stream = TcpStream::connect("127.0.0.1:8080")
535     ///                        .expect("Couldn't connect to the server...");
536     /// stream.set_ttl(100).expect("set_ttl call failed");
537     /// assert_eq!(stream.ttl().unwrap_or(0), 100);
538     /// ```
539     #[stable(feature = "net2_mutators", since = "1.9.0")]
540     pub fn ttl(&self) -> io::Result<u32> {
541         self.0.ttl()
542     }
543
544     /// Gets the value of the `SO_ERROR` option on this socket.
545     ///
546     /// This will retrieve the stored error in the underlying socket, clearing
547     /// the field in the process. This can be useful for checking errors between
548     /// calls.
549     ///
550     /// # Examples
551     ///
552     /// ```no_run
553     /// use std::net::TcpStream;
554     ///
555     /// let stream = TcpStream::connect("127.0.0.1:8080")
556     ///                        .expect("Couldn't connect to the server...");
557     /// stream.take_error().expect("No error was expected...");
558     /// ```
559     #[stable(feature = "net2_mutators", since = "1.9.0")]
560     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
561         self.0.take_error()
562     }
563
564     /// Moves this TCP stream into or out of nonblocking mode.
565     ///
566     /// This will result in `read`, `write`, `recv` and `send` operations
567     /// becoming nonblocking, i.e., immediately returning from their calls.
568     /// If the IO operation is successful, `Ok` is returned and no further
569     /// action is required. If the IO operation could not be completed and needs
570     /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
571     /// returned.
572     ///
573     /// On Unix platforms, calling this method corresponds to calling `fcntl`
574     /// `FIONBIO`. On Windows calling this method corresponds to calling
575     /// `ioctlsocket` `FIONBIO`.
576     ///
577     /// # Examples
578     ///
579     /// Reading bytes from a TCP stream in non-blocking mode:
580     ///
581     /// ```no_run
582     /// use std::io::{self, Read};
583     /// use std::net::TcpStream;
584     ///
585     /// let mut stream = TcpStream::connect("127.0.0.1:7878")
586     ///     .expect("Couldn't connect to the server...");
587     /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
588     ///
589     /// # fn wait_for_fd() { unimplemented!() }
590     /// let mut buf = vec![];
591     /// loop {
592     ///     match stream.read_to_end(&mut buf) {
593     ///         Ok(_) => break,
594     ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
595     ///             // wait until network socket is ready, typically implemented
596     ///             // via platform-specific APIs such as epoll or IOCP
597     ///             wait_for_fd();
598     ///         }
599     ///         Err(e) => panic!("encountered IO error: {e}"),
600     ///     };
601     /// };
602     /// println!("bytes: {buf:?}");
603     /// ```
604     #[stable(feature = "net2_mutators", since = "1.9.0")]
605     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
606         self.0.set_nonblocking(nonblocking)
607     }
608 }
609
610 // In addition to the `impl`s here, `TcpStream` also has `impl`s for
611 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
612 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
613 // `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
614 // `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
615
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl Read for TcpStream {
618     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
619         self.0.read(buf)
620     }
621
622     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
623         self.0.read_vectored(bufs)
624     }
625
626     #[inline]
627     fn is_read_vectored(&self) -> bool {
628         self.0.is_read_vectored()
629     }
630 }
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl Write for TcpStream {
633     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
634         self.0.write(buf)
635     }
636
637     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
638         self.0.write_vectored(bufs)
639     }
640
641     #[inline]
642     fn is_write_vectored(&self) -> bool {
643         self.0.is_write_vectored()
644     }
645
646     fn flush(&mut self) -> io::Result<()> {
647         Ok(())
648     }
649 }
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl Read for &TcpStream {
652     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
653         self.0.read(buf)
654     }
655
656     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
657         self.0.read_vectored(bufs)
658     }
659
660     #[inline]
661     fn is_read_vectored(&self) -> bool {
662         self.0.is_read_vectored()
663     }
664 }
665 #[stable(feature = "rust1", since = "1.0.0")]
666 impl Write for &TcpStream {
667     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
668         self.0.write(buf)
669     }
670
671     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
672         self.0.write_vectored(bufs)
673     }
674
675     #[inline]
676     fn is_write_vectored(&self) -> bool {
677         self.0.is_write_vectored()
678     }
679
680     fn flush(&mut self) -> io::Result<()> {
681         Ok(())
682     }
683 }
684
685 impl AsInner<net_imp::TcpStream> for TcpStream {
686     fn as_inner(&self) -> &net_imp::TcpStream {
687         &self.0
688     }
689 }
690
691 impl FromInner<net_imp::TcpStream> for TcpStream {
692     fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
693         TcpStream(inner)
694     }
695 }
696
697 impl IntoInner<net_imp::TcpStream> for TcpStream {
698     fn into_inner(self) -> net_imp::TcpStream {
699         self.0
700     }
701 }
702
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl fmt::Debug for TcpStream {
705     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
706         self.0.fmt(f)
707     }
708 }
709
710 impl TcpListener {
711     /// Creates a new `TcpListener` which will be bound to the specified
712     /// address.
713     ///
714     /// The returned listener is ready for accepting connections.
715     ///
716     /// Binding with a port number of 0 will request that the OS assigns a port
717     /// to this listener. The port allocated can be queried via the
718     /// [`TcpListener::local_addr`] method.
719     ///
720     /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
721     /// its documentation for concrete examples.
722     ///
723     /// If `addr` yields multiple addresses, `bind` will be attempted with
724     /// each of the addresses until one succeeds and returns the listener. If
725     /// none of the addresses succeed in creating a listener, the error returned
726     /// from the last attempt (the last address) is returned.
727     ///
728     /// # Examples
729     ///
730     /// Creates a TCP listener bound to `127.0.0.1:80`:
731     ///
732     /// ```no_run
733     /// use std::net::TcpListener;
734     ///
735     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
736     /// ```
737     ///
738     /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
739     /// TCP listener bound to `127.0.0.1:443`:
740     ///
741     /// ```no_run
742     /// use std::net::{SocketAddr, TcpListener};
743     ///
744     /// let addrs = [
745     ///     SocketAddr::from(([127, 0, 0, 1], 80)),
746     ///     SocketAddr::from(([127, 0, 0, 1], 443)),
747     /// ];
748     /// let listener = TcpListener::bind(&addrs[..]).unwrap();
749     /// ```
750     #[stable(feature = "rust1", since = "1.0.0")]
751     pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
752         super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
753     }
754
755     /// Returns the local socket address of this listener.
756     ///
757     /// # Examples
758     ///
759     /// ```no_run
760     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
761     ///
762     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
763     /// assert_eq!(listener.local_addr().unwrap(),
764     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
765     /// ```
766     #[stable(feature = "rust1", since = "1.0.0")]
767     pub fn local_addr(&self) -> io::Result<SocketAddr> {
768         self.0.socket_addr()
769     }
770
771     /// Creates a new independently owned handle to the underlying socket.
772     ///
773     /// The returned [`TcpListener`] is a reference to the same socket that this
774     /// object references. Both handles can be used to accept incoming
775     /// connections and options set on one listener will affect the other.
776     ///
777     /// # Examples
778     ///
779     /// ```no_run
780     /// use std::net::TcpListener;
781     ///
782     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
783     /// let listener_clone = listener.try_clone().unwrap();
784     /// ```
785     #[stable(feature = "rust1", since = "1.0.0")]
786     pub fn try_clone(&self) -> io::Result<TcpListener> {
787         self.0.duplicate().map(TcpListener)
788     }
789
790     /// Accept a new incoming connection from this listener.
791     ///
792     /// This function will block the calling thread until a new TCP connection
793     /// is established. When established, the corresponding [`TcpStream`] and the
794     /// remote peer's address will be returned.
795     ///
796     /// # Examples
797     ///
798     /// ```no_run
799     /// use std::net::TcpListener;
800     ///
801     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
802     /// match listener.accept() {
803     ///     Ok((_socket, addr)) => println!("new client: {addr:?}"),
804     ///     Err(e) => println!("couldn't get client: {e:?}"),
805     /// }
806     /// ```
807     #[stable(feature = "rust1", since = "1.0.0")]
808     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
809         // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
810         // the `a` variable here is technically unused.
811         #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
812         self.0.accept().map(|(a, b)| (TcpStream(a), b))
813     }
814
815     /// Returns an iterator over the connections being received on this
816     /// listener.
817     ///
818     /// The returned iterator will never return [`None`] and will also not yield
819     /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
820     /// calling [`TcpListener::accept`] in a loop.
821     ///
822     /// # Examples
823     ///
824     /// ```no_run
825     /// use std::net::{TcpListener, TcpStream};
826     ///
827     /// fn handle_connection(stream: TcpStream) {
828     ///    //...
829     /// }
830     ///
831     /// fn main() -> std::io::Result<()> {
832     ///     let listener = TcpListener::bind("127.0.0.1:80").unwrap();
833     ///
834     ///     for stream in listener.incoming() {
835     ///         match stream {
836     ///             Ok(stream) => {
837     ///                 handle_connection(stream);
838     ///             }
839     ///             Err(e) => { /* connection failed */ }
840     ///         }
841     ///     }
842     ///     Ok(())
843     /// }
844     /// ```
845     #[stable(feature = "rust1", since = "1.0.0")]
846     pub fn incoming(&self) -> Incoming<'_> {
847         Incoming { listener: self }
848     }
849
850     /// Turn this into an iterator over the connections being received on this
851     /// listener.
852     ///
853     /// The returned iterator will never return [`None`] and will also not yield
854     /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
855     /// calling [`TcpListener::accept`] in a loop.
856     ///
857     /// # Examples
858     ///
859     /// ```no_run
860     /// #![feature(tcplistener_into_incoming)]
861     /// use std::net::{TcpListener, TcpStream};
862     ///
863     /// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
864     ///     let listener = TcpListener::bind("127.0.0.1:80").unwrap();
865     ///     listener.into_incoming()
866     ///         .filter_map(Result::ok) /* Ignore failed connections */
867     /// }
868     ///
869     /// fn main() -> std::io::Result<()> {
870     ///     for stream in listen_on(80) {
871     ///         /* handle the connection here */
872     ///     }
873     ///     Ok(())
874     /// }
875     /// ```
876     #[must_use = "`self` will be dropped if the result is not used"]
877     #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
878     pub fn into_incoming(self) -> IntoIncoming {
879         IntoIncoming { listener: self }
880     }
881
882     /// Sets the value for the `IP_TTL` option on this socket.
883     ///
884     /// This value sets the time-to-live field that is used in every packet sent
885     /// from this socket.
886     ///
887     /// # Examples
888     ///
889     /// ```no_run
890     /// use std::net::TcpListener;
891     ///
892     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
893     /// listener.set_ttl(100).expect("could not set TTL");
894     /// ```
895     #[stable(feature = "net2_mutators", since = "1.9.0")]
896     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
897         self.0.set_ttl(ttl)
898     }
899
900     /// Gets the value of the `IP_TTL` option for this socket.
901     ///
902     /// For more information about this option, see [`TcpListener::set_ttl`].
903     ///
904     /// # Examples
905     ///
906     /// ```no_run
907     /// use std::net::TcpListener;
908     ///
909     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
910     /// listener.set_ttl(100).expect("could not set TTL");
911     /// assert_eq!(listener.ttl().unwrap_or(0), 100);
912     /// ```
913     #[stable(feature = "net2_mutators", since = "1.9.0")]
914     pub fn ttl(&self) -> io::Result<u32> {
915         self.0.ttl()
916     }
917
918     #[stable(feature = "net2_mutators", since = "1.9.0")]
919     #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
920     #[allow(missing_docs)]
921     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
922         self.0.set_only_v6(only_v6)
923     }
924
925     #[stable(feature = "net2_mutators", since = "1.9.0")]
926     #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
927     #[allow(missing_docs)]
928     pub fn only_v6(&self) -> io::Result<bool> {
929         self.0.only_v6()
930     }
931
932     /// Gets the value of the `SO_ERROR` option on this socket.
933     ///
934     /// This will retrieve the stored error in the underlying socket, clearing
935     /// the field in the process. This can be useful for checking errors between
936     /// calls.
937     ///
938     /// # Examples
939     ///
940     /// ```no_run
941     /// use std::net::TcpListener;
942     ///
943     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
944     /// listener.take_error().expect("No error was expected");
945     /// ```
946     #[stable(feature = "net2_mutators", since = "1.9.0")]
947     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
948         self.0.take_error()
949     }
950
951     /// Moves this TCP stream into or out of nonblocking mode.
952     ///
953     /// This will result in the `accept` operation becoming nonblocking,
954     /// i.e., immediately returning from their calls. If the IO operation is
955     /// successful, `Ok` is returned and no further action is required. If the
956     /// IO operation could not be completed and needs to be retried, an error
957     /// with kind [`io::ErrorKind::WouldBlock`] is returned.
958     ///
959     /// On Unix platforms, calling this method corresponds to calling `fcntl`
960     /// `FIONBIO`. On Windows calling this method corresponds to calling
961     /// `ioctlsocket` `FIONBIO`.
962     ///
963     /// # Examples
964     ///
965     /// Bind a TCP listener to an address, listen for connections, and read
966     /// bytes in nonblocking mode:
967     ///
968     /// ```no_run
969     /// use std::io;
970     /// use std::net::TcpListener;
971     ///
972     /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
973     /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
974     ///
975     /// # fn wait_for_fd() { unimplemented!() }
976     /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
977     /// for stream in listener.incoming() {
978     ///     match stream {
979     ///         Ok(s) => {
980     ///             // do something with the TcpStream
981     ///             handle_connection(s);
982     ///         }
983     ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
984     ///             // wait until network socket is ready, typically implemented
985     ///             // via platform-specific APIs such as epoll or IOCP
986     ///             wait_for_fd();
987     ///             continue;
988     ///         }
989     ///         Err(e) => panic!("encountered IO error: {e}"),
990     ///     }
991     /// }
992     /// ```
993     #[stable(feature = "net2_mutators", since = "1.9.0")]
994     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
995         self.0.set_nonblocking(nonblocking)
996     }
997 }
998
999 // In addition to the `impl`s here, `TcpListener` also has `impl`s for
1000 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1001 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1002 // `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
1003 // `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
1004
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 impl<'a> Iterator for Incoming<'a> {
1007     type Item = io::Result<TcpStream>;
1008     fn next(&mut self) -> Option<io::Result<TcpStream>> {
1009         Some(self.listener.accept().map(|p| p.0))
1010     }
1011 }
1012
1013 #[stable(feature = "tcp_listener_incoming_fused_iterator", since = "1.64.0")]
1014 impl FusedIterator for Incoming<'_> {}
1015
1016 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
1017 impl Iterator for IntoIncoming {
1018     type Item = io::Result<TcpStream>;
1019     fn next(&mut self) -> Option<io::Result<TcpStream>> {
1020         Some(self.listener.accept().map(|p| p.0))
1021     }
1022 }
1023
1024 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
1025 impl FusedIterator for IntoIncoming {}
1026
1027 impl AsInner<net_imp::TcpListener> for TcpListener {
1028     fn as_inner(&self) -> &net_imp::TcpListener {
1029         &self.0
1030     }
1031 }
1032
1033 impl FromInner<net_imp::TcpListener> for TcpListener {
1034     fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
1035         TcpListener(inner)
1036     }
1037 }
1038
1039 impl IntoInner<net_imp::TcpListener> for TcpListener {
1040     fn into_inner(self) -> net_imp::TcpListener {
1041         self.0
1042     }
1043 }
1044
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl fmt::Debug for TcpListener {
1047     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048         self.0.fmt(f)
1049     }
1050 }