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