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