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, 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;
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 #[stable(feature = "rust1", since = "1.0.0")]
95 pub struct Incoming<'a> {
96 listener: &'a TcpListener,
99 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
101 /// This `struct` is created by the [`TcpListener::into_incoming`] method.
102 /// See its documentation for more.
104 /// [`accept`]: TcpListener::accept
106 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
107 pub struct IntoIncoming {
108 listener: TcpListener,
112 /// Opens a TCP connection to a remote host.
114 /// `addr` is an address of the remote host. Anything which implements
115 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
116 /// documentation for concrete examples.
118 /// If `addr` yields multiple addresses, `connect` will be attempted with
119 /// each of the addresses until a connection is successful. If none of
120 /// the addresses result in a successful connection, the error returned from
121 /// the last connection attempt (the last address) is returned.
125 /// Open a TCP connection to `127.0.0.1:8080`:
128 /// use std::net::TcpStream;
130 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
131 /// println!("Connected to the server!");
133 /// println!("Couldn't connect to server...");
137 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
138 /// a TCP connection to `127.0.0.1:8081`:
141 /// use std::net::{SocketAddr, TcpStream};
144 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
145 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
147 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
148 /// println!("Connected to the server!");
150 /// println!("Couldn't connect to server...");
153 #[stable(feature = "rust1", since = "1.0.0")]
154 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
155 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
158 /// Opens a TCP connection to a remote host with a timeout.
160 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
161 /// timeout must be applied to individual addresses.
163 /// It is an error to pass a zero `Duration` to this function.
165 /// Unlike other methods on `TcpStream`, this does not correspond to a
166 /// single system call. It instead calls `connect` in nonblocking mode and
167 /// then uses an OS-specific mechanism to await the completion of the
168 /// connection request.
169 #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
170 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
171 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
174 /// Returns the socket address of the remote peer of this TCP connection.
179 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
181 /// let stream = TcpStream::connect("127.0.0.1:8080")
182 /// .expect("Couldn't connect to the server...");
183 /// assert_eq!(stream.peer_addr().unwrap(),
184 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
191 /// Returns the socket address of the local half of this TCP connection.
196 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
198 /// let stream = TcpStream::connect("127.0.0.1:8080")
199 /// .expect("Couldn't connect to the server...");
200 /// assert_eq!(stream.local_addr().unwrap().ip(),
201 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub fn local_addr(&self) -> io::Result<SocketAddr> {
208 /// Shuts down the read, write, or both halves of this connection.
210 /// This function will cause all pending and future I/O on the specified
211 /// portions to return immediately with an appropriate value (see the
212 /// documentation of [`Shutdown`]).
214 /// # Platform-specific behavior
216 /// Calling this function multiple times may result in different behavior,
217 /// depending on the operating system. On Linux, the second call will
218 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
219 /// This may change in the future.
224 /// use std::net::{Shutdown, TcpStream};
226 /// let stream = TcpStream::connect("127.0.0.1:8080")
227 /// .expect("Couldn't connect to the server...");
228 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
230 #[stable(feature = "rust1", since = "1.0.0")]
231 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
235 /// Creates a new independently owned handle to the underlying socket.
237 /// The returned `TcpStream` is a reference to the same stream that this
238 /// object references. Both handles will read and write the same stream of
239 /// data, and options set on one stream will be propagated to the other
245 /// use std::net::TcpStream;
247 /// let stream = TcpStream::connect("127.0.0.1:8080")
248 /// .expect("Couldn't connect to the server...");
249 /// let stream_clone = stream.try_clone().expect("clone failed...");
251 #[stable(feature = "rust1", since = "1.0.0")]
252 pub fn try_clone(&self) -> io::Result<TcpStream> {
253 self.0.duplicate().map(TcpStream)
256 /// Sets the read timeout to the timeout specified.
258 /// If the value specified is [`None`], then [`read`] calls will block
259 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
260 /// passed to this method.
262 /// # Platform-specific behavior
264 /// Platforms may return a different error code whenever a read times out as
265 /// a result of setting this option. For example Unix typically returns an
266 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
268 /// [`read`]: Read::read
269 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
270 /// [`TimedOut`]: io::ErrorKind::TimedOut
275 /// use std::net::TcpStream;
277 /// let stream = TcpStream::connect("127.0.0.1:8080")
278 /// .expect("Couldn't connect to the server...");
279 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
282 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
287 /// use std::net::TcpStream;
288 /// use std::time::Duration;
290 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
291 /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
292 /// let err = result.unwrap_err();
293 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
295 #[stable(feature = "socket_timeout", since = "1.4.0")]
296 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
297 self.0.set_read_timeout(dur)
300 /// Sets the write timeout to the timeout specified.
302 /// If the value specified is [`None`], then [`write`] calls will block
303 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
304 /// passed to this method.
306 /// # Platform-specific behavior
308 /// Platforms may return a different error code whenever a write times out
309 /// as a result of setting this option. For example Unix typically returns
310 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
312 /// [`write`]: Write::write
313 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
314 /// [`TimedOut`]: io::ErrorKind::TimedOut
319 /// use std::net::TcpStream;
321 /// let stream = TcpStream::connect("127.0.0.1:8080")
322 /// .expect("Couldn't connect to the server...");
323 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
326 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
331 /// use std::net::TcpStream;
332 /// use std::time::Duration;
334 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
335 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
336 /// let err = result.unwrap_err();
337 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
339 #[stable(feature = "socket_timeout", since = "1.4.0")]
340 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
341 self.0.set_write_timeout(dur)
344 /// Returns the read timeout of this socket.
346 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
348 /// # Platform-specific behavior
350 /// Some platforms do not provide access to the current timeout.
352 /// [`read`]: Read::read
357 /// use std::net::TcpStream;
359 /// let stream = TcpStream::connect("127.0.0.1:8080")
360 /// .expect("Couldn't connect to the server...");
361 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
362 /// assert_eq!(stream.read_timeout().unwrap(), None);
364 #[stable(feature = "socket_timeout", since = "1.4.0")]
365 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
366 self.0.read_timeout()
369 /// Returns the write timeout of this socket.
371 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
373 /// # Platform-specific behavior
375 /// Some platforms do not provide access to the current timeout.
377 /// [`write`]: Write::write
382 /// use std::net::TcpStream;
384 /// let stream = TcpStream::connect("127.0.0.1:8080")
385 /// .expect("Couldn't connect to the server...");
386 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
387 /// assert_eq!(stream.write_timeout().unwrap(), None);
389 #[stable(feature = "socket_timeout", since = "1.4.0")]
390 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
391 self.0.write_timeout()
394 /// Receives data on the socket from the remote address to which it is
395 /// connected, without removing that data from the queue. On success,
396 /// returns the number of bytes peeked.
398 /// Successive calls return the same data. This is accomplished by passing
399 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
404 /// use std::net::TcpStream;
406 /// let stream = TcpStream::connect("127.0.0.1:8000")
407 /// .expect("couldn't bind to address");
408 /// let mut buf = [0; 10];
409 /// let len = stream.peek(&mut buf).expect("peek failed");
411 #[stable(feature = "peek", since = "1.18.0")]
412 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
416 /// Sets the value of the `SO_LINGER` option on this socket.
418 /// This value controls how the socket is closed when data remains
419 /// to be sent. If `SO_LINGER` is set, the socket will remain open
420 /// for the specified duration as the system attempts to send pending data.
421 /// Otherwise, the system may close the socket immediately, or wait for a
427 /// #![feature(tcp_linger)]
429 /// use std::net::TcpStream;
430 /// use std::time::Duration;
432 /// let stream = TcpStream::connect("127.0.0.1:8080")
433 /// .expect("Couldn't connect to the server...");
434 /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
436 #[unstable(feature = "tcp_linger", issue = "88494")]
437 pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
438 self.0.set_linger(linger)
441 /// Gets the value of the `SO_LINGER` option on this socket.
443 /// For more information about this option, see [`TcpStream::set_linger`].
448 /// #![feature(tcp_linger)]
450 /// use std::net::TcpStream;
451 /// use std::time::Duration;
453 /// let stream = TcpStream::connect("127.0.0.1:8080")
454 /// .expect("Couldn't connect to the server...");
455 /// stream.set_linger(Some(Duration::from_secs(0))).expect("set_linger call failed");
456 /// assert_eq!(stream.linger().unwrap(), Some(Duration::from_secs(0)));
458 #[unstable(feature = "tcp_linger", issue = "88494")]
459 pub fn linger(&self) -> io::Result<Option<Duration>> {
463 /// Sets the value of the `TCP_NODELAY` option on this socket.
465 /// If set, this option disables the Nagle algorithm. This means that
466 /// segments are always sent as soon as possible, even if there is only a
467 /// small amount of data. When not set, data is buffered until there is a
468 /// sufficient amount to send out, thereby avoiding the frequent sending of
474 /// use std::net::TcpStream;
476 /// let stream = TcpStream::connect("127.0.0.1:8080")
477 /// .expect("Couldn't connect to the server...");
478 /// stream.set_nodelay(true).expect("set_nodelay call failed");
480 #[stable(feature = "net2_mutators", since = "1.9.0")]
481 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
482 self.0.set_nodelay(nodelay)
485 /// Gets the value of the `TCP_NODELAY` option on this socket.
487 /// For more information about this option, see [`TcpStream::set_nodelay`].
492 /// use std::net::TcpStream;
494 /// let stream = TcpStream::connect("127.0.0.1:8080")
495 /// .expect("Couldn't connect to the server...");
496 /// stream.set_nodelay(true).expect("set_nodelay call failed");
497 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
499 #[stable(feature = "net2_mutators", since = "1.9.0")]
500 pub fn nodelay(&self) -> io::Result<bool> {
504 /// Sets the value for the `IP_TTL` option on this socket.
506 /// This value sets the time-to-live field that is used in every packet sent
507 /// from this socket.
512 /// use std::net::TcpStream;
514 /// let stream = TcpStream::connect("127.0.0.1:8080")
515 /// .expect("Couldn't connect to the server...");
516 /// stream.set_ttl(100).expect("set_ttl call failed");
518 #[stable(feature = "net2_mutators", since = "1.9.0")]
519 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
523 /// Gets the value of the `IP_TTL` option for this socket.
525 /// For more information about this option, see [`TcpStream::set_ttl`].
530 /// use std::net::TcpStream;
532 /// let stream = TcpStream::connect("127.0.0.1:8080")
533 /// .expect("Couldn't connect to the server...");
534 /// stream.set_ttl(100).expect("set_ttl call failed");
535 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
537 #[stable(feature = "net2_mutators", since = "1.9.0")]
538 pub fn ttl(&self) -> io::Result<u32> {
542 /// Gets the value of the `SO_ERROR` option on this socket.
544 /// This will retrieve the stored error in the underlying socket, clearing
545 /// the field in the process. This can be useful for checking errors between
551 /// use std::net::TcpStream;
553 /// let stream = TcpStream::connect("127.0.0.1:8080")
554 /// .expect("Couldn't connect to the server...");
555 /// stream.take_error().expect("No error was expected...");
557 #[stable(feature = "net2_mutators", since = "1.9.0")]
558 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
562 /// Moves this TCP stream into or out of nonblocking mode.
564 /// This will result in `read`, `write`, `recv` and `send` operations
565 /// becoming nonblocking, i.e., immediately returning from their calls.
566 /// If the IO operation is successful, `Ok` is returned and no further
567 /// action is required. If the IO operation could not be completed and needs
568 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
571 /// On Unix platforms, calling this method corresponds to calling `fcntl`
572 /// `FIONBIO`. On Windows calling this method corresponds to calling
573 /// `ioctlsocket` `FIONBIO`.
577 /// Reading bytes from a TCP stream in non-blocking mode:
580 /// use std::io::{self, Read};
581 /// use std::net::TcpStream;
583 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
584 /// .expect("Couldn't connect to the server...");
585 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
587 /// # fn wait_for_fd() { unimplemented!() }
588 /// let mut buf = vec![];
590 /// match stream.read_to_end(&mut buf) {
592 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
593 /// // wait until network socket is ready, typically implemented
594 /// // via platform-specific APIs such as epoll or IOCP
597 /// Err(e) => panic!("encountered IO error: {}", e),
600 /// println!("bytes: {:?}", buf);
602 #[stable(feature = "net2_mutators", since = "1.9.0")]
603 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
604 self.0.set_nonblocking(nonblocking)
608 // In addition to the `impl`s here, `TcpStream` also has `impl`s for
609 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
610 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
611 // `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
612 // `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl Read for TcpStream {
616 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
620 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
621 self.0.read_vectored(bufs)
625 fn is_read_vectored(&self) -> bool {
626 self.0.is_read_vectored()
630 unsafe fn initializer(&self) -> Initializer {
631 // SAFETY: Read is guaranteed to work on uninitialized memory
632 unsafe { Initializer::nop() }
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl Write for TcpStream {
637 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
641 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
642 self.0.write_vectored(bufs)
646 fn is_write_vectored(&self) -> bool {
647 self.0.is_write_vectored()
650 fn flush(&mut self) -> io::Result<()> {
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl Read for &TcpStream {
656 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
660 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
661 self.0.read_vectored(bufs)
665 fn is_read_vectored(&self) -> bool {
666 self.0.is_read_vectored()
670 unsafe fn initializer(&self) -> Initializer {
671 // SAFETY: Read is guaranteed to work on uninitialized memory
672 unsafe { Initializer::nop() }
675 #[stable(feature = "rust1", since = "1.0.0")]
676 impl Write for &TcpStream {
677 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
681 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
682 self.0.write_vectored(bufs)
686 fn is_write_vectored(&self) -> bool {
687 self.0.is_write_vectored()
690 fn flush(&mut self) -> io::Result<()> {
695 impl AsInner<net_imp::TcpStream> for TcpStream {
696 fn as_inner(&self) -> &net_imp::TcpStream {
701 impl FromInner<net_imp::TcpStream> for TcpStream {
702 fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
707 impl IntoInner<net_imp::TcpStream> for TcpStream {
708 fn into_inner(self) -> net_imp::TcpStream {
713 #[stable(feature = "rust1", since = "1.0.0")]
714 impl fmt::Debug for TcpStream {
715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
721 /// Creates a new `TcpListener` which will be bound to the specified
724 /// The returned listener is ready for accepting connections.
726 /// Binding with a port number of 0 will request that the OS assigns a port
727 /// to this listener. The port allocated can be queried via the
728 /// [`TcpListener::local_addr`] method.
730 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
731 /// its documentation for concrete examples.
733 /// If `addr` yields multiple addresses, `bind` will be attempted with
734 /// each of the addresses until one succeeds and returns the listener. If
735 /// none of the addresses succeed in creating a listener, the error returned
736 /// from the last attempt (the last address) is returned.
740 /// Creates a TCP listener bound to `127.0.0.1:80`:
743 /// use std::net::TcpListener;
745 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
748 /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
749 /// TCP listener bound to `127.0.0.1:443`:
752 /// use std::net::{SocketAddr, TcpListener};
755 /// SocketAddr::from(([127, 0, 0, 1], 80)),
756 /// SocketAddr::from(([127, 0, 0, 1], 443)),
758 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
762 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
765 /// Returns the local socket address of this listener.
770 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
772 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
773 /// assert_eq!(listener.local_addr().unwrap(),
774 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub fn local_addr(&self) -> io::Result<SocketAddr> {
781 /// Creates a new independently owned handle to the underlying socket.
783 /// The returned [`TcpListener`] is a reference to the same socket that this
784 /// object references. Both handles can be used to accept incoming
785 /// connections and options set on one listener will affect the other.
790 /// use std::net::TcpListener;
792 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
793 /// let listener_clone = listener.try_clone().unwrap();
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub fn try_clone(&self) -> io::Result<TcpListener> {
797 self.0.duplicate().map(TcpListener)
800 /// Accept a new incoming connection from this listener.
802 /// This function will block the calling thread until a new TCP connection
803 /// is established. When established, the corresponding [`TcpStream`] and the
804 /// remote peer's address will be returned.
809 /// use std::net::TcpListener;
811 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
812 /// match listener.accept() {
813 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
814 /// Err(e) => println!("couldn't get client: {:?}", e),
817 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
819 // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
820 // the `a` variable here is technically unused.
821 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
822 self.0.accept().map(|(a, b)| (TcpStream(a), b))
825 /// Returns an iterator over the connections being received on this
828 /// The returned iterator will never return [`None`] and will also not yield
829 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
830 /// calling [`TcpListener::accept`] in a loop.
835 /// use std::net::{TcpListener, TcpStream};
837 /// fn handle_connection(stream: TcpStream) {
841 /// fn main() -> std::io::Result<()> {
842 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
844 /// for stream in listener.incoming() {
847 /// handle_connection(stream);
849 /// Err(e) => { /* connection failed */ }
855 #[stable(feature = "rust1", since = "1.0.0")]
856 pub fn incoming(&self) -> Incoming<'_> {
857 Incoming { listener: self }
860 /// Turn this into an iterator over the connections being received on this
863 /// The returned iterator will never return [`None`] and will also not yield
864 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
865 /// calling [`TcpListener::accept`] in a loop.
870 /// #![feature(tcplistener_into_incoming)]
871 /// use std::net::{TcpListener, TcpStream};
873 /// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
874 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
875 /// listener.into_incoming()
876 /// .filter_map(Result::ok) /* Ignore failed connections */
879 /// fn main() -> std::io::Result<()> {
880 /// for stream in listen_on(80) {
881 /// /* handle the connection here */
886 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
887 pub fn into_incoming(self) -> IntoIncoming {
888 IntoIncoming { listener: self }
891 /// Sets the value for the `IP_TTL` option on this socket.
893 /// This value sets the time-to-live field that is used in every packet sent
894 /// from this socket.
899 /// use std::net::TcpListener;
901 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
902 /// listener.set_ttl(100).expect("could not set TTL");
904 #[stable(feature = "net2_mutators", since = "1.9.0")]
905 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
909 /// Gets the value of the `IP_TTL` option for this socket.
911 /// For more information about this option, see [`TcpListener::set_ttl`].
916 /// use std::net::TcpListener;
918 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
919 /// listener.set_ttl(100).expect("could not set TTL");
920 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
922 #[stable(feature = "net2_mutators", since = "1.9.0")]
923 pub fn ttl(&self) -> io::Result<u32> {
927 #[stable(feature = "net2_mutators", since = "1.9.0")]
930 reason = "this option can only be set before the socket is bound"
932 #[allow(missing_docs)]
933 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
934 self.0.set_only_v6(only_v6)
937 #[stable(feature = "net2_mutators", since = "1.9.0")]
940 reason = "this option can only be set before the socket is bound"
942 #[allow(missing_docs)]
943 pub fn only_v6(&self) -> io::Result<bool> {
947 /// Gets the value of the `SO_ERROR` option on this socket.
949 /// This will retrieve the stored error in the underlying socket, clearing
950 /// the field in the process. This can be useful for checking errors between
956 /// use std::net::TcpListener;
958 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
959 /// listener.take_error().expect("No error was expected");
961 #[stable(feature = "net2_mutators", since = "1.9.0")]
962 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
966 /// Moves this TCP stream into or out of nonblocking mode.
968 /// This will result in the `accept` operation becoming nonblocking,
969 /// i.e., immediately returning from their calls. If the IO operation is
970 /// successful, `Ok` is returned and no further action is required. If the
971 /// IO operation could not be completed and needs to be retried, an error
972 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
974 /// On Unix platforms, calling this method corresponds to calling `fcntl`
975 /// `FIONBIO`. On Windows calling this method corresponds to calling
976 /// `ioctlsocket` `FIONBIO`.
980 /// Bind a TCP listener to an address, listen for connections, and read
981 /// bytes in nonblocking mode:
985 /// use std::net::TcpListener;
987 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
988 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
990 /// # fn wait_for_fd() { unimplemented!() }
991 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
992 /// for stream in listener.incoming() {
995 /// // do something with the TcpStream
996 /// handle_connection(s);
998 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
999 /// // wait until network socket is ready, typically implemented
1000 /// // via platform-specific APIs such as epoll or IOCP
1004 /// Err(e) => panic!("encountered IO error: {}", e),
1008 #[stable(feature = "net2_mutators", since = "1.9.0")]
1009 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1010 self.0.set_nonblocking(nonblocking)
1014 // In addition to the `impl`s here, `TcpListener` also has `impl`s for
1015 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1016 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1017 // `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
1018 // `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a> Iterator for Incoming<'a> {
1022 type Item = io::Result<TcpStream>;
1023 fn next(&mut self) -> Option<io::Result<TcpStream>> {
1024 Some(self.listener.accept().map(|p| p.0))
1028 #[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
1029 impl Iterator for IntoIncoming {
1030 type Item = io::Result<TcpStream>;
1031 fn next(&mut self) -> Option<io::Result<TcpStream>> {
1032 Some(self.listener.accept().map(|p| p.0))
1036 impl AsInner<net_imp::TcpListener> for TcpListener {
1037 fn as_inner(&self) -> &net_imp::TcpListener {
1042 impl FromInner<net_imp::TcpListener> for TcpListener {
1043 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
1048 impl IntoInner<net_imp::TcpListener> for TcpListener {
1049 fn into_inner(self) -> net_imp::TcpListener {
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 impl fmt::Debug for TcpListener {
1056 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {