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::iter::FusedIterator;
11 use crate::net::{Shutdown, SocketAddr, ToSocketAddrs};
12 use crate::sys_common::net as net_imp;
13 use crate::sys_common::{AsInner, FromInner, IntoInner};
14 use crate::time::Duration;
16 /// A TCP stream between a local and a remote socket.
18 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
19 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
20 /// by [reading] and [writing] to it.
22 /// The connection will be closed when the value is dropped. The reading and writing
23 /// portions of the connection can also be shut down individually with the [`shutdown`]
26 /// The Transmission Control Protocol is specified in [IETF RFC 793].
28 /// [`accept`]: TcpListener::accept
29 /// [`connect`]: TcpStream::connect
30 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
32 /// [`shutdown`]: TcpStream::shutdown
38 /// use std::io::prelude::*;
39 /// use std::net::TcpStream;
41 /// fn main() -> std::io::Result<()> {
42 /// let mut stream = TcpStream::connect("127.0.0.1:34254")?;
44 /// stream.write(&[1])?;
45 /// stream.read(&mut [0; 128])?;
47 /// } // the stream is closed here
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub struct TcpStream(net_imp::TcpStream);
52 /// A TCP socket server, listening for connections.
54 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
55 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
56 /// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
58 /// The socket will be closed when the value is dropped.
60 /// The Transmission Control Protocol is specified in [IETF RFC 793].
62 /// [`accept`]: TcpListener::accept
63 /// [`bind`]: TcpListener::bind
64 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
69 /// use std::net::{TcpListener, TcpStream};
71 /// fn handle_client(stream: TcpStream) {
75 /// fn main() -> std::io::Result<()> {
76 /// let listener = TcpListener::bind("127.0.0.1:80")?;
78 /// // accept connections and process them serially
79 /// for stream in listener.incoming() {
80 /// handle_client(stream?);
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct TcpListener(net_imp::TcpListener);
88 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
90 /// This `struct` is created by the [`TcpListener::incoming`] method.
91 /// See its documentation for more.
93 /// [`accept`]: TcpListener::accept
94 #[must_use = "iterators are lazy and do nothing unless consumed"]
95 #[stable(feature = "rust1", since = "1.0.0")]
97 pub struct Incoming<'a> {
98 listener: &'a TcpListener,
101 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
103 /// This `struct` is created by the [`TcpListener::into_incoming`] method.
104 /// See its documentation for more.
106 /// [`accept`]: TcpListener::accept
108 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
109 pub struct IntoIncoming {
110 listener: TcpListener,
114 /// Opens a TCP connection to a remote host.
116 /// `addr` is an address of the remote host. Anything which implements
117 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
118 /// documentation for concrete examples.
120 /// If `addr` yields multiple addresses, `connect` will be attempted with
121 /// each of the addresses until a connection is successful. If none of
122 /// the addresses result in a successful connection, the error returned from
123 /// the last connection attempt (the last address) is returned.
127 /// Open a TCP connection to `127.0.0.1:8080`:
130 /// use std::net::TcpStream;
132 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
133 /// println!("Connected to the server!");
135 /// println!("Couldn't connect to server...");
139 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
140 /// a TCP connection to `127.0.0.1:8081`:
143 /// use std::net::{SocketAddr, TcpStream};
146 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
147 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
149 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
150 /// println!("Connected to the server!");
152 /// println!("Couldn't connect to server...");
155 #[stable(feature = "rust1", since = "1.0.0")]
156 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
157 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
160 /// Opens a TCP connection to a remote host with a timeout.
162 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
163 /// timeout must be applied to individual addresses.
165 /// It is an error to pass a zero `Duration` to this function.
167 /// Unlike other methods on `TcpStream`, this does not correspond to a
168 /// single system call. It instead calls `connect` in nonblocking mode and
169 /// then uses an OS-specific mechanism to await the completion of the
170 /// connection request.
171 #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
172 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
173 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
176 /// Returns the socket address of the remote peer of this TCP connection.
181 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
183 /// let stream = TcpStream::connect("127.0.0.1:8080")
184 /// .expect("Couldn't connect to the server...");
185 /// assert_eq!(stream.peer_addr().unwrap(),
186 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
188 #[stable(feature = "rust1", since = "1.0.0")]
189 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
193 /// Returns the socket address of the local half of this TCP connection.
198 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
200 /// let stream = TcpStream::connect("127.0.0.1:8080")
201 /// .expect("Couldn't connect to the server...");
202 /// assert_eq!(stream.local_addr().unwrap().ip(),
203 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
205 #[stable(feature = "rust1", since = "1.0.0")]
206 pub fn local_addr(&self) -> io::Result<SocketAddr> {
210 /// Shuts down the read, write, or both halves of this connection.
212 /// This function will cause all pending and future I/O on the specified
213 /// portions to return immediately with an appropriate value (see the
214 /// documentation of [`Shutdown`]).
216 /// # Platform-specific behavior
218 /// Calling this function multiple times may result in different behavior,
219 /// depending on the operating system. On Linux, the second call will
220 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
221 /// This may change in the future.
226 /// use std::net::{Shutdown, TcpStream};
228 /// let stream = TcpStream::connect("127.0.0.1:8080")
229 /// .expect("Couldn't connect to the server...");
230 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
237 /// Creates a new independently owned handle to the underlying socket.
239 /// The returned `TcpStream` is a reference to the same stream that this
240 /// object references. Both handles will read and write the same stream of
241 /// data, and options set on one stream will be propagated to the other
247 /// use std::net::TcpStream;
249 /// let stream = TcpStream::connect("127.0.0.1:8080")
250 /// .expect("Couldn't connect to the server...");
251 /// let stream_clone = stream.try_clone().expect("clone failed...");
253 #[stable(feature = "rust1", since = "1.0.0")]
254 pub fn try_clone(&self) -> io::Result<TcpStream> {
255 self.0.duplicate().map(TcpStream)
258 /// Sets the read timeout to the timeout specified.
260 /// If the value specified is [`None`], then [`read`] calls will block
261 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
262 /// passed to this method.
264 /// # Platform-specific behavior
266 /// Platforms may return a different error code whenever a read times out as
267 /// a result of setting this option. For example Unix typically returns an
268 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
270 /// [`read`]: Read::read
271 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
272 /// [`TimedOut`]: io::ErrorKind::TimedOut
277 /// use std::net::TcpStream;
279 /// let stream = TcpStream::connect("127.0.0.1:8080")
280 /// .expect("Couldn't connect to the server...");
281 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
284 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
289 /// use std::net::TcpStream;
290 /// use std::time::Duration;
292 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
293 /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
294 /// let err = result.unwrap_err();
295 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
297 #[stable(feature = "socket_timeout", since = "1.4.0")]
298 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
299 self.0.set_read_timeout(dur)
302 /// Sets the write timeout to the timeout specified.
304 /// If the value specified is [`None`], then [`write`] calls will block
305 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
306 /// passed to this method.
308 /// # Platform-specific behavior
310 /// Platforms may return a different error code whenever a write times out
311 /// as a result of setting this option. For example Unix typically returns
312 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
314 /// [`write`]: Write::write
315 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
316 /// [`TimedOut`]: io::ErrorKind::TimedOut
321 /// use std::net::TcpStream;
323 /// let stream = TcpStream::connect("127.0.0.1:8080")
324 /// .expect("Couldn't connect to the server...");
325 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
328 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
333 /// use std::net::TcpStream;
334 /// use std::time::Duration;
336 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
337 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
338 /// let err = result.unwrap_err();
339 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
341 #[stable(feature = "socket_timeout", since = "1.4.0")]
342 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
343 self.0.set_write_timeout(dur)
346 /// Returns the read timeout of this socket.
348 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
350 /// # Platform-specific behavior
352 /// Some platforms do not provide access to the current timeout.
354 /// [`read`]: Read::read
359 /// use std::net::TcpStream;
361 /// let stream = TcpStream::connect("127.0.0.1:8080")
362 /// .expect("Couldn't connect to the server...");
363 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
364 /// assert_eq!(stream.read_timeout().unwrap(), None);
366 #[stable(feature = "socket_timeout", since = "1.4.0")]
367 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
368 self.0.read_timeout()
371 /// Returns the write timeout of this socket.
373 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
375 /// # Platform-specific behavior
377 /// Some platforms do not provide access to the current timeout.
379 /// [`write`]: Write::write
384 /// use std::net::TcpStream;
386 /// let stream = TcpStream::connect("127.0.0.1:8080")
387 /// .expect("Couldn't connect to the server...");
388 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
389 /// assert_eq!(stream.write_timeout().unwrap(), None);
391 #[stable(feature = "socket_timeout", since = "1.4.0")]
392 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
393 self.0.write_timeout()
396 /// Receives data on the socket from the remote address to which it is
397 /// connected, without removing that data from the queue. On success,
398 /// returns the number of bytes peeked.
400 /// Successive calls return the same data. This is accomplished by passing
401 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
406 /// use std::net::TcpStream;
408 /// let stream = TcpStream::connect("127.0.0.1:8000")
409 /// .expect("Couldn't connect to the server...");
410 /// let mut buf = [0; 10];
411 /// let len = stream.peek(&mut buf).expect("peek failed");
413 #[stable(feature = "peek", since = "1.18.0")]
414 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
418 /// Sets the value of the `SO_LINGER` option on this socket.
420 /// This value controls how the socket is closed when data remains
421 /// to be sent. If `SO_LINGER` is set, the socket will remain open
422 /// for the specified duration as the system attempts to send pending data.
423 /// Otherwise, the system may close the socket immediately, or wait for a
429 /// #![feature(tcp_linger)]
431 /// use std::net::TcpStream;
432 /// use std::time::Duration;
434 /// let stream = TcpStream::connect("127.0.0.1:8080")
435 /// .expect("Couldn't connect to the server...");
436 /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
438 #[unstable(feature = "tcp_linger", issue = "88494")]
439 pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
440 self.0.set_linger(linger)
443 /// Gets the value of the `SO_LINGER` option on this socket.
445 /// For more information about this option, see [`TcpStream::set_linger`].
450 /// #![feature(tcp_linger)]
452 /// use std::net::TcpStream;
453 /// use std::time::Duration;
455 /// let stream = TcpStream::connect("127.0.0.1:8080")
456 /// .expect("Couldn't connect to the server...");
457 /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
458 /// assert_eq!(stream.linger().unwrap(), Some(Duration::from_secs(0)));
460 #[unstable(feature = "tcp_linger", issue = "88494")]
461 pub fn linger(&self) -> io::Result<Option<Duration>> {
465 /// Sets the value of the `TCP_NODELAY` option on this socket.
467 /// If set, this option disables the Nagle algorithm. This means that
468 /// segments are always sent as soon as possible, even if there is only a
469 /// small amount of data. When not set, data is buffered until there is a
470 /// sufficient amount to send out, thereby avoiding the frequent sending of
476 /// use std::net::TcpStream;
478 /// let stream = TcpStream::connect("127.0.0.1:8080")
479 /// .expect("Couldn't connect to the server...");
480 /// stream.set_nodelay(true).expect("set_nodelay call failed");
482 #[stable(feature = "net2_mutators", since = "1.9.0")]
483 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
484 self.0.set_nodelay(nodelay)
487 /// Gets the value of the `TCP_NODELAY` option on this socket.
489 /// For more information about this option, see [`TcpStream::set_nodelay`].
494 /// use std::net::TcpStream;
496 /// let stream = TcpStream::connect("127.0.0.1:8080")
497 /// .expect("Couldn't connect to the server...");
498 /// stream.set_nodelay(true).expect("set_nodelay call failed");
499 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
501 #[stable(feature = "net2_mutators", since = "1.9.0")]
502 pub fn nodelay(&self) -> io::Result<bool> {
506 /// Sets the value for the `IP_TTL` option on this socket.
508 /// This value sets the time-to-live field that is used in every packet sent
509 /// from this socket.
514 /// use std::net::TcpStream;
516 /// let stream = TcpStream::connect("127.0.0.1:8080")
517 /// .expect("Couldn't connect to the server...");
518 /// stream.set_ttl(100).expect("set_ttl call failed");
520 #[stable(feature = "net2_mutators", since = "1.9.0")]
521 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
525 /// Gets the value of the `IP_TTL` option for this socket.
527 /// For more information about this option, see [`TcpStream::set_ttl`].
532 /// use std::net::TcpStream;
534 /// let stream = TcpStream::connect("127.0.0.1:8080")
535 /// .expect("Couldn't connect to the server...");
536 /// stream.set_ttl(100).expect("set_ttl call failed");
537 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
539 #[stable(feature = "net2_mutators", since = "1.9.0")]
540 pub fn ttl(&self) -> io::Result<u32> {
544 /// Gets the value of the `SO_ERROR` option on this socket.
546 /// This will retrieve the stored error in the underlying socket, clearing
547 /// the field in the process. This can be useful for checking errors between
553 /// use std::net::TcpStream;
555 /// let stream = TcpStream::connect("127.0.0.1:8080")
556 /// .expect("Couldn't connect to the server...");
557 /// stream.take_error().expect("No error was expected...");
559 #[stable(feature = "net2_mutators", since = "1.9.0")]
560 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
564 /// Moves this TCP stream into or out of nonblocking mode.
566 /// This will result in `read`, `write`, `recv` and `send` operations
567 /// becoming nonblocking, i.e., immediately returning from their calls.
568 /// If the IO operation is successful, `Ok` is returned and no further
569 /// action is required. If the IO operation could not be completed and needs
570 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
573 /// On Unix platforms, calling this method corresponds to calling `fcntl`
574 /// `FIONBIO`. On Windows calling this method corresponds to calling
575 /// `ioctlsocket` `FIONBIO`.
579 /// Reading bytes from a TCP stream in non-blocking mode:
582 /// use std::io::{self, Read};
583 /// use std::net::TcpStream;
585 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
586 /// .expect("Couldn't connect to the server...");
587 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
589 /// # fn wait_for_fd() { unimplemented!() }
590 /// let mut buf = vec![];
592 /// match stream.read_to_end(&mut buf) {
594 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
595 /// // wait until network socket is ready, typically implemented
596 /// // via platform-specific APIs such as epoll or IOCP
599 /// Err(e) => panic!("encountered IO error: {e}"),
602 /// println!("bytes: {buf:?}");
604 #[stable(feature = "net2_mutators", since = "1.9.0")]
605 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
606 self.0.set_nonblocking(nonblocking)
610 // In addition to the `impl`s here, `TcpStream` also has `impl`s for
611 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
612 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
613 // `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
614 // `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl Read for TcpStream {
618 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
622 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
623 self.0.read_vectored(bufs)
627 fn is_read_vectored(&self) -> bool {
628 self.0.is_read_vectored()
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl Write for TcpStream {
633 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
637 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
638 self.0.write_vectored(bufs)
642 fn is_write_vectored(&self) -> bool {
643 self.0.is_write_vectored()
646 fn flush(&mut self) -> io::Result<()> {
650 #[stable(feature = "rust1", since = "1.0.0")]
651 impl Read for &TcpStream {
652 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
656 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
657 self.0.read_vectored(bufs)
661 fn is_read_vectored(&self) -> bool {
662 self.0.is_read_vectored()
665 #[stable(feature = "rust1", since = "1.0.0")]
666 impl Write for &TcpStream {
667 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
671 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
672 self.0.write_vectored(bufs)
676 fn is_write_vectored(&self) -> bool {
677 self.0.is_write_vectored()
680 fn flush(&mut self) -> io::Result<()> {
685 impl AsInner<net_imp::TcpStream> for TcpStream {
686 fn as_inner(&self) -> &net_imp::TcpStream {
691 impl FromInner<net_imp::TcpStream> for TcpStream {
692 fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
697 impl IntoInner<net_imp::TcpStream> for TcpStream {
698 fn into_inner(self) -> net_imp::TcpStream {
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl fmt::Debug for TcpStream {
705 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
711 /// Creates a new `TcpListener` which will be bound to the specified
714 /// The returned listener is ready for accepting connections.
716 /// Binding with a port number of 0 will request that the OS assigns a port
717 /// to this listener. The port allocated can be queried via the
718 /// [`TcpListener::local_addr`] method.
720 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
721 /// its documentation for concrete examples.
723 /// If `addr` yields multiple addresses, `bind` will be attempted with
724 /// each of the addresses until one succeeds and returns the listener. If
725 /// none of the addresses succeed in creating a listener, the error returned
726 /// from the last attempt (the last address) is returned.
730 /// Creates a TCP listener bound to `127.0.0.1:80`:
733 /// use std::net::TcpListener;
735 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
738 /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
739 /// TCP listener bound to `127.0.0.1:443`:
742 /// use std::net::{SocketAddr, TcpListener};
745 /// SocketAddr::from(([127, 0, 0, 1], 80)),
746 /// SocketAddr::from(([127, 0, 0, 1], 443)),
748 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
750 #[stable(feature = "rust1", since = "1.0.0")]
751 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
752 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
755 /// Returns the local socket address of this listener.
760 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
762 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
763 /// assert_eq!(listener.local_addr().unwrap(),
764 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
766 #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn local_addr(&self) -> io::Result<SocketAddr> {
771 /// Creates a new independently owned handle to the underlying socket.
773 /// The returned [`TcpListener`] is a reference to the same socket that this
774 /// object references. Both handles can be used to accept incoming
775 /// connections and options set on one listener will affect the other.
780 /// use std::net::TcpListener;
782 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
783 /// let listener_clone = listener.try_clone().unwrap();
785 #[stable(feature = "rust1", since = "1.0.0")]
786 pub fn try_clone(&self) -> io::Result<TcpListener> {
787 self.0.duplicate().map(TcpListener)
790 /// Accept a new incoming connection from this listener.
792 /// This function will block the calling thread until a new TCP connection
793 /// is established. When established, the corresponding [`TcpStream`] and the
794 /// remote peer's address will be returned.
799 /// use std::net::TcpListener;
801 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
802 /// match listener.accept() {
803 /// Ok((_socket, addr)) => println!("new client: {addr:?}"),
804 /// Err(e) => println!("couldn't get client: {e:?}"),
807 #[stable(feature = "rust1", since = "1.0.0")]
808 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
809 // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
810 // the `a` variable here is technically unused.
811 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
812 self.0.accept().map(|(a, b)| (TcpStream(a), b))
815 /// Returns an iterator over the connections being received on this
818 /// The returned iterator will never return [`None`] and will also not yield
819 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
820 /// calling [`TcpListener::accept`] in a loop.
825 /// use std::net::{TcpListener, TcpStream};
827 /// fn handle_connection(stream: TcpStream) {
831 /// fn main() -> std::io::Result<()> {
832 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
834 /// for stream in listener.incoming() {
837 /// handle_connection(stream);
839 /// Err(e) => { /* connection failed */ }
845 #[stable(feature = "rust1", since = "1.0.0")]
846 pub fn incoming(&self) -> Incoming<'_> {
847 Incoming { listener: self }
850 /// Turn this into an iterator over the connections being received on this
853 /// The returned iterator will never return [`None`] and will also not yield
854 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
855 /// calling [`TcpListener::accept`] in a loop.
860 /// #![feature(tcplistener_into_incoming)]
861 /// use std::net::{TcpListener, TcpStream};
863 /// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
864 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
865 /// listener.into_incoming()
866 /// .filter_map(Result::ok) /* Ignore failed connections */
869 /// fn main() -> std::io::Result<()> {
870 /// for stream in listen_on(80) {
871 /// /* handle the connection here */
876 #[must_use = "`self` will be dropped if the result is not used"]
877 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
878 pub fn into_incoming(self) -> IntoIncoming {
879 IntoIncoming { listener: self }
882 /// Sets the value for the `IP_TTL` option on this socket.
884 /// This value sets the time-to-live field that is used in every packet sent
885 /// from this socket.
890 /// use std::net::TcpListener;
892 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
893 /// listener.set_ttl(100).expect("could not set TTL");
895 #[stable(feature = "net2_mutators", since = "1.9.0")]
896 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
900 /// Gets the value of the `IP_TTL` option for this socket.
902 /// For more information about this option, see [`TcpListener::set_ttl`].
907 /// use std::net::TcpListener;
909 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
910 /// listener.set_ttl(100).expect("could not set TTL");
911 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
913 #[stable(feature = "net2_mutators", since = "1.9.0")]
914 pub fn ttl(&self) -> io::Result<u32> {
918 #[stable(feature = "net2_mutators", since = "1.9.0")]
919 #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
920 #[allow(missing_docs)]
921 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
922 self.0.set_only_v6(only_v6)
925 #[stable(feature = "net2_mutators", since = "1.9.0")]
926 #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
927 #[allow(missing_docs)]
928 pub fn only_v6(&self) -> io::Result<bool> {
932 /// Gets the value of the `SO_ERROR` option on this socket.
934 /// This will retrieve the stored error in the underlying socket, clearing
935 /// the field in the process. This can be useful for checking errors between
941 /// use std::net::TcpListener;
943 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
944 /// listener.take_error().expect("No error was expected");
946 #[stable(feature = "net2_mutators", since = "1.9.0")]
947 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
951 /// Moves this TCP stream into or out of nonblocking mode.
953 /// This will result in the `accept` operation becoming nonblocking,
954 /// i.e., immediately returning from their calls. If the IO operation is
955 /// successful, `Ok` is returned and no further action is required. If the
956 /// IO operation could not be completed and needs to be retried, an error
957 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
959 /// On Unix platforms, calling this method corresponds to calling `fcntl`
960 /// `FIONBIO`. On Windows calling this method corresponds to calling
961 /// `ioctlsocket` `FIONBIO`.
965 /// Bind a TCP listener to an address, listen for connections, and read
966 /// bytes in nonblocking mode:
970 /// use std::net::TcpListener;
972 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
973 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
975 /// # fn wait_for_fd() { unimplemented!() }
976 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
977 /// for stream in listener.incoming() {
980 /// // do something with the TcpStream
981 /// handle_connection(s);
983 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
984 /// // wait until network socket is ready, typically implemented
985 /// // via platform-specific APIs such as epoll or IOCP
989 /// Err(e) => panic!("encountered IO error: {e}"),
993 #[stable(feature = "net2_mutators", since = "1.9.0")]
994 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
995 self.0.set_nonblocking(nonblocking)
999 // In addition to the `impl`s here, `TcpListener` also has `impl`s for
1000 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1001 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1002 // `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
1003 // `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 impl<'a> Iterator for Incoming<'a> {
1007 type Item = io::Result<TcpStream>;
1008 fn next(&mut self) -> Option<io::Result<TcpStream>> {
1009 Some(self.listener.accept().map(|p| p.0))
1013 #[stable(feature = "tcp_listener_incoming_fused_iterator", since = "1.64.0")]
1014 impl FusedIterator for Incoming<'_> {}
1016 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
1017 impl Iterator for IntoIncoming {
1018 type Item = io::Result<TcpStream>;
1019 fn next(&mut self) -> Option<io::Result<TcpStream>> {
1020 Some(self.listener.accept().map(|p| p.0))
1024 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
1025 impl FusedIterator for IntoIncoming {}
1027 impl AsInner<net_imp::TcpListener> for TcpListener {
1028 fn as_inner(&self) -> &net_imp::TcpListener {
1033 impl FromInner<net_imp::TcpListener> for TcpListener {
1034 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
1039 impl IntoInner<net_imp::TcpListener> for TcpListener {
1040 fn into_inner(self) -> net_imp::TcpListener {
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl fmt::Debug for TcpListener {
1047 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {