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