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