1 #![deny(unsafe_op_in_unsafe_fn)]
3 #[cfg(all(test, not(target_os = "emscripten")))]
6 use crate::io::prelude::*;
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;
15 /// A TCP stream between a local and a remote socket.
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.
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`]
25 /// The Transmission Control Protocol is specified in [IETF RFC 793].
27 /// [`accept`]: TcpListener::accept
28 /// [`connect`]: TcpStream::connect
29 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
31 /// [`shutdown`]: TcpStream::shutdown
37 /// use std::io::prelude::*;
38 /// use std::net::TcpStream;
40 /// fn main() -> std::io::Result<()> {
41 /// let mut stream = TcpStream::connect("127.0.0.1:34254")?;
43 /// stream.write(&[1])?;
44 /// stream.read(&mut [0; 128])?;
46 /// } // the stream is closed here
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub struct TcpStream(net_imp::TcpStream);
51 /// A TCP socket server, listening for connections.
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`].
57 /// The socket will be closed when the value is dropped.
59 /// The Transmission Control Protocol is specified in [IETF RFC 793].
61 /// [`accept`]: TcpListener::accept
62 /// [`bind`]: TcpListener::bind
63 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
68 /// use std::net::{TcpListener, TcpStream};
70 /// fn handle_client(stream: TcpStream) {
74 /// fn main() -> std::io::Result<()> {
75 /// let listener = TcpListener::bind("127.0.0.1:80")?;
77 /// // accept connections and process them serially
78 /// for stream in listener.incoming() {
79 /// handle_client(stream?);
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct TcpListener(net_imp::TcpListener);
87 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
89 /// This `struct` is created by the [`TcpListener::incoming`] method.
90 /// See its documentation for more.
92 /// [`accept`]: TcpListener::accept
93 #[must_use = "iterators are lazy and do nothing unless consumed"]
94 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct Incoming<'a> {
97 listener: &'a TcpListener,
100 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
102 /// This `struct` is created by the [`TcpListener::into_incoming`] method.
103 /// See its documentation for more.
105 /// [`accept`]: TcpListener::accept
107 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
108 pub struct IntoIncoming {
109 listener: TcpListener,
113 /// Opens a TCP connection to a remote host.
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.
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.
126 /// Open a TCP connection to `127.0.0.1:8080`:
129 /// use std::net::TcpStream;
131 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
132 /// println!("Connected to the server!");
134 /// println!("Couldn't connect to server...");
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`:
142 /// use std::net::{SocketAddr, TcpStream};
145 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
146 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
148 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
149 /// println!("Connected to the server!");
151 /// println!("Couldn't connect to server...");
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)
159 /// Opens a TCP connection to a remote host with a timeout.
161 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
162 /// timeout must be applied to individual addresses.
164 /// It is an error to pass a zero `Duration` to this function.
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)
175 /// Returns the socket address of the remote peer of this TCP connection.
180 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
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)));
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
192 /// Returns the socket address of the local half of this TCP connection.
197 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
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)));
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn local_addr(&self) -> io::Result<SocketAddr> {
209 /// Shuts down the read, write, or both halves of this connection.
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`]).
215 /// # Platform-specific behavior
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.
225 /// use std::net::{Shutdown, TcpStream};
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");
231 #[stable(feature = "rust1", since = "1.0.0")]
232 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
236 /// Creates a new independently owned handle to the underlying socket.
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
246 /// use std::net::TcpStream;
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...");
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn try_clone(&self) -> io::Result<TcpStream> {
254 self.0.duplicate().map(TcpStream)
257 /// Sets the read timeout to the timeout specified.
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.
263 /// # Platform-specific behavior
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`].
269 /// [`read`]: Read::read
270 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
271 /// [`TimedOut`]: io::ErrorKind::TimedOut
276 /// use std::net::TcpStream;
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");
283 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
288 /// use std::net::TcpStream;
289 /// use std::time::Duration;
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)
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)
301 /// Sets the write timeout to the timeout specified.
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.
307 /// # Platform-specific behavior
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`].
313 /// [`write`]: Write::write
314 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
315 /// [`TimedOut`]: io::ErrorKind::TimedOut
320 /// use std::net::TcpStream;
322 /// let stream = TcpStream::connect("127.0.0.1:8080")
323 /// .expect("Couldn't connect to the server...");
324 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
327 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
332 /// use std::net::TcpStream;
333 /// use std::time::Duration;
335 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
336 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
337 /// let err = result.unwrap_err();
338 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
340 #[stable(feature = "socket_timeout", since = "1.4.0")]
341 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
342 self.0.set_write_timeout(dur)
345 /// Returns the read timeout of this socket.
347 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
349 /// # Platform-specific behavior
351 /// Some platforms do not provide access to the current timeout.
353 /// [`read`]: Read::read
358 /// use std::net::TcpStream;
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);
365 #[stable(feature = "socket_timeout", since = "1.4.0")]
366 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
367 self.0.read_timeout()
370 /// Returns the write timeout of this socket.
372 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
374 /// # Platform-specific behavior
376 /// Some platforms do not provide access to the current timeout.
378 /// [`write`]: Write::write
383 /// use std::net::TcpStream;
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);
390 #[stable(feature = "socket_timeout", since = "1.4.0")]
391 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
392 self.0.write_timeout()
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.
399 /// Successive calls return the same data. This is accomplished by passing
400 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
405 /// use std::net::TcpStream;
407 /// let stream = TcpStream::connect("127.0.0.1:8000")
408 /// .expect("Couldn't connect to the server...");
409 /// let mut buf = [0; 10];
410 /// let len = stream.peek(&mut buf).expect("peek failed");
412 #[stable(feature = "peek", since = "1.18.0")]
413 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
417 /// Sets the value of the `SO_LINGER` option on this socket.
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
428 /// #![feature(tcp_linger)]
430 /// use std::net::TcpStream;
431 /// use std::time::Duration;
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");
437 #[unstable(feature = "tcp_linger", issue = "88494")]
438 pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
439 self.0.set_linger(linger)
442 /// Gets the value of the `SO_LINGER` option on this socket.
444 /// For more information about this option, see [`TcpStream::set_linger`].
449 /// #![feature(tcp_linger)]
451 /// use std::net::TcpStream;
452 /// use std::time::Duration;
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)));
459 #[unstable(feature = "tcp_linger", issue = "88494")]
460 pub fn linger(&self) -> io::Result<Option<Duration>> {
464 /// Sets the value of the `TCP_NODELAY` option on this socket.
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
475 /// use std::net::TcpStream;
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");
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)
486 /// Gets the value of the `TCP_NODELAY` option on this socket.
488 /// For more information about this option, see [`TcpStream::set_nodelay`].
493 /// use std::net::TcpStream;
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);
500 #[stable(feature = "net2_mutators", since = "1.9.0")]
501 pub fn nodelay(&self) -> io::Result<bool> {
505 /// Sets the value for the `IP_TTL` option on this socket.
507 /// This value sets the time-to-live field that is used in every packet sent
508 /// from this socket.
513 /// use std::net::TcpStream;
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");
519 #[stable(feature = "net2_mutators", since = "1.9.0")]
520 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
524 /// Gets the value of the `IP_TTL` option for this socket.
526 /// For more information about this option, see [`TcpStream::set_ttl`].
531 /// use std::net::TcpStream;
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);
538 #[stable(feature = "net2_mutators", since = "1.9.0")]
539 pub fn ttl(&self) -> io::Result<u32> {
543 /// Gets the value of the `SO_ERROR` option on this socket.
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
552 /// use std::net::TcpStream;
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...");
558 #[stable(feature = "net2_mutators", since = "1.9.0")]
559 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
563 /// Moves this TCP stream into or out of nonblocking mode.
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
572 /// On Unix platforms, calling this method corresponds to calling `fcntl`
573 /// `FIONBIO`. On Windows calling this method corresponds to calling
574 /// `ioctlsocket` `FIONBIO`.
578 /// Reading bytes from a TCP stream in non-blocking mode:
581 /// use std::io::{self, Read};
582 /// use std::net::TcpStream;
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");
588 /// # fn wait_for_fd() { unimplemented!() }
589 /// let mut buf = vec![];
591 /// match stream.read_to_end(&mut buf) {
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
598 /// Err(e) => panic!("encountered IO error: {e}"),
601 /// println!("bytes: {buf:?}");
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)
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.
615 #[stable(feature = "rust1", since = "1.0.0")]
616 impl Read for TcpStream {
617 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
621 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
622 self.0.read_vectored(bufs)
626 fn is_read_vectored(&self) -> bool {
627 self.0.is_read_vectored()
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl Write for TcpStream {
632 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
636 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
637 self.0.write_vectored(bufs)
641 fn is_write_vectored(&self) -> bool {
642 self.0.is_write_vectored()
645 fn flush(&mut self) -> io::Result<()> {
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl Read for &TcpStream {
651 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
655 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
656 self.0.read_vectored(bufs)
660 fn is_read_vectored(&self) -> bool {
661 self.0.is_read_vectored()
664 #[stable(feature = "rust1", since = "1.0.0")]
665 impl Write for &TcpStream {
666 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
670 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
671 self.0.write_vectored(bufs)
675 fn is_write_vectored(&self) -> bool {
676 self.0.is_write_vectored()
679 fn flush(&mut self) -> io::Result<()> {
684 impl AsInner<net_imp::TcpStream> for TcpStream {
685 fn as_inner(&self) -> &net_imp::TcpStream {
690 impl FromInner<net_imp::TcpStream> for TcpStream {
691 fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
696 impl IntoInner<net_imp::TcpStream> for TcpStream {
697 fn into_inner(self) -> net_imp::TcpStream {
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl fmt::Debug for TcpStream {
704 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
710 /// Creates a new `TcpListener` which will be bound to the specified
713 /// The returned listener is ready for accepting connections.
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.
719 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
720 /// its documentation for concrete examples.
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.
729 /// Creates a TCP listener bound to `127.0.0.1:80`:
732 /// use std::net::TcpListener;
734 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
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`:
741 /// use std::net::{SocketAddr, TcpListener};
744 /// SocketAddr::from(([127, 0, 0, 1], 80)),
745 /// SocketAddr::from(([127, 0, 0, 1], 443)),
747 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
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)
754 /// Returns the local socket address of this listener.
759 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
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)));
765 #[stable(feature = "rust1", since = "1.0.0")]
766 pub fn local_addr(&self) -> io::Result<SocketAddr> {
770 /// Creates a new independently owned handle to the underlying socket.
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.
779 /// use std::net::TcpListener;
781 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
782 /// let listener_clone = listener.try_clone().unwrap();
784 #[stable(feature = "rust1", since = "1.0.0")]
785 pub fn try_clone(&self) -> io::Result<TcpListener> {
786 self.0.duplicate().map(TcpListener)
789 /// Accept a new incoming connection from this listener.
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.
798 /// use std::net::TcpListener;
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:?}"),
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))
814 /// Returns an iterator over the connections being received on this
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.
824 /// use std::net::{TcpListener, TcpStream};
826 /// fn handle_connection(stream: TcpStream) {
830 /// fn main() -> std::io::Result<()> {
831 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
833 /// for stream in listener.incoming() {
836 /// handle_connection(stream);
838 /// Err(e) => { /* connection failed */ }
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn incoming(&self) -> Incoming<'_> {
846 Incoming { listener: self }
849 /// Turn this into an iterator over the connections being received on this
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.
859 /// #![feature(tcplistener_into_incoming)]
860 /// use std::net::{TcpListener, TcpStream};
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 */
868 /// fn main() -> std::io::Result<()> {
869 /// for stream in listen_on(80) {
870 /// /* handle the connection here */
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 }
881 /// Sets the value for the `IP_TTL` option on this socket.
883 /// This value sets the time-to-live field that is used in every packet sent
884 /// from this socket.
889 /// use std::net::TcpListener;
891 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
892 /// listener.set_ttl(100).expect("could not set TTL");
894 #[stable(feature = "net2_mutators", since = "1.9.0")]
895 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
899 /// Gets the value of the `IP_TTL` option for this socket.
901 /// For more information about this option, see [`TcpListener::set_ttl`].
906 /// use std::net::TcpListener;
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);
912 #[stable(feature = "net2_mutators", since = "1.9.0")]
913 pub fn ttl(&self) -> io::Result<u32> {
917 #[stable(feature = "net2_mutators", since = "1.9.0")]
918 #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
919 #[allow(missing_docs)]
920 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
921 self.0.set_only_v6(only_v6)
924 #[stable(feature = "net2_mutators", since = "1.9.0")]
925 #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
926 #[allow(missing_docs)]
927 pub fn only_v6(&self) -> io::Result<bool> {
931 /// Gets the value of the `SO_ERROR` option on this socket.
933 /// This will retrieve the stored error in the underlying socket, clearing
934 /// the field in the process. This can be useful for checking errors between
940 /// use std::net::TcpListener;
942 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
943 /// listener.take_error().expect("No error was expected");
945 #[stable(feature = "net2_mutators", since = "1.9.0")]
946 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
950 /// Moves this TCP stream into or out of nonblocking mode.
952 /// This will result in the `accept` operation becoming nonblocking,
953 /// i.e., immediately returning from their calls. If the IO operation is
954 /// successful, `Ok` is returned and no further action is required. If the
955 /// IO operation could not be completed and needs to be retried, an error
956 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
958 /// On Unix platforms, calling this method corresponds to calling `fcntl`
959 /// `FIONBIO`. On Windows calling this method corresponds to calling
960 /// `ioctlsocket` `FIONBIO`.
964 /// Bind a TCP listener to an address, listen for connections, and read
965 /// bytes in nonblocking mode:
969 /// use std::net::TcpListener;
971 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
972 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
974 /// # fn wait_for_fd() { unimplemented!() }
975 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
976 /// for stream in listener.incoming() {
979 /// // do something with the TcpStream
980 /// handle_connection(s);
982 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
983 /// // wait until network socket is ready, typically implemented
984 /// // via platform-specific APIs such as epoll or IOCP
988 /// Err(e) => panic!("encountered IO error: {e}"),
992 #[stable(feature = "net2_mutators", since = "1.9.0")]
993 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
994 self.0.set_nonblocking(nonblocking)
998 // In addition to the `impl`s here, `TcpListener` also has `impl`s for
999 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1000 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1001 // `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
1002 // `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 impl<'a> Iterator for Incoming<'a> {
1006 type Item = io::Result<TcpStream>;
1007 fn next(&mut self) -> Option<io::Result<TcpStream>> {
1008 Some(self.listener.accept().map(|p| p.0))
1012 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
1013 impl Iterator for IntoIncoming {
1014 type Item = io::Result<TcpStream>;
1015 fn next(&mut self) -> Option<io::Result<TcpStream>> {
1016 Some(self.listener.accept().map(|p| p.0))
1020 impl AsInner<net_imp::TcpListener> for TcpListener {
1021 fn as_inner(&self) -> &net_imp::TcpListener {
1026 impl FromInner<net_imp::TcpListener> for TcpListener {
1027 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
1032 impl IntoInner<net_imp::TcpListener> for TcpListener {
1033 fn into_inner(self) -> net_imp::TcpListener {
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 impl fmt::Debug for TcpListener {
1040 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {