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