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 /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket.
612 ///
613 /// This value sets the unicast hop limit field that is used in every packet
614 /// sent from this socket.
615 ///
616 /// # Examples
617 ///
618 /// ```no_run
619 /// #![feature(ipv6_hop_limit)]
620 /// use std::net::TcpStream;
621 ///
622 /// let stream = TcpStream::connect("[::1]:12345")
623 /// .expect("Couldn't connect to the server...");
624 /// stream.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
625 /// ```
626 #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
627 pub fn set_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
628 self.0.set_hop_limit_v6(limit)
629 }
630
631 /// Gets the value of the `IPV6_UNICAST_HOPS` option on this socket.
632 ///
633 /// For more information about this option, see [`TcpStream::set_hop_limit_v6`].
634 ///
635 /// # Examples
636 ///
637 /// ```no_run
638 /// #![feature(ipv6_hop_limit)]
639 /// use std::net::TcpStream;
640 ///
641 /// let stream = TcpStream::connect("[::1]:12345")
642 /// .expect("Couldn't connect to the server...");
643 /// stream.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
644 /// assert_eq!(stream.hop_limit_v6().unwrap(), 88);
645 /// ```
646 #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
647 pub fn hop_limit_v6(&self) -> io::Result<u8> {
648 self.0.hop_limit_v6()
649 }
650
651 /// Gets the value of the `SO_ERROR` option on this socket.
652 ///
653 /// This will retrieve the stored error in the underlying socket, clearing
654 /// the field in the process. This can be useful for checking errors between
655 /// calls.
656 ///
657 /// # Examples
658 ///
659 /// ```no_run
660 /// use std::net::TcpStream;
661 ///
662 /// let stream = TcpStream::connect("127.0.0.1:8080")
663 /// .expect("Couldn't connect to the server...");
664 /// stream.take_error().expect("No error was expected...");
665 /// ```
666 #[stable(feature = "net2_mutators", since = "1.9.0")]
667 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
668 self.0.take_error()
669 }
670
671 /// Moves this TCP stream into or out of nonblocking mode.
672 ///
673 /// This will result in `read`, `write`, `recv` and `send` system operations
674 /// becoming nonblocking, i.e., immediately returning from their calls.
675 /// If the IO operation is successful, `Ok` is returned and no further
676 /// action is required. If the IO operation could not be completed and needs
677 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
678 /// returned.
679 ///
680 /// On most Unix platforms, calling this method corresponds to calling `ioctl`
681 /// `FIONBIO`. On Windows, calling this method corresponds to calling
682 /// `ioctlsocket` `FIONBIO`.
683 ///
684 /// # Examples
685 ///
686 /// Reading bytes from a TCP stream in non-blocking mode:
687 ///
688 /// ```no_run
689 /// use std::io::{self, Read};
690 /// use std::net::TcpStream;
691 ///
692 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
693 /// .expect("Couldn't connect to the server...");
694 /// stream.set_nonblocking(true).expect("set_nonblocking should succeed");
695 ///
696 /// # fn wait_for_fd() { unimplemented!() }
697 /// let mut buf = vec![];
698 /// loop {
699 /// match stream.read_to_end(&mut buf) {
700 /// Ok(_) => break,
701 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
702 /// // wait until network socket is ready, typically implemented
703 /// // via platform-specific APIs such as epoll or IOCP
704 /// wait_for_fd();
705 /// }
706 /// Err(e) => panic!("encountered IO error: {e}"),
707 /// };
708 /// };
709 /// println!("bytes: {buf:?}");
710 /// ```
711 #[stable(feature = "net2_mutators", since = "1.9.0")]
712 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
713 self.0.set_nonblocking(nonblocking)
714 }
715}
716
717// In addition to the `impl`s here, `TcpStream` also has `impl`s for
718// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
719// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
720// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
721// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
722
723#[stable(feature = "rust1", since = "1.0.0")]
724impl Read for TcpStream {
725 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
726 self.0.read(buf)
727 }
728
729 fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
730 self.0.read_buf(buf)
731 }
732
733 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
734 self.0.read_vectored(bufs)
735 }
736
737 #[inline]
738 fn is_read_vectored(&self) -> bool {
739 self.0.is_read_vectored()
740 }
741}
742#[stable(feature = "rust1", since = "1.0.0")]
743impl Write for TcpStream {
744 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
745 self.0.write(buf)
746 }
747
748 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
749 self.0.write_vectored(bufs)
750 }
751
752 #[inline]
753 fn is_write_vectored(&self) -> bool {
754 self.0.is_write_vectored()
755 }
756
757 #[inline]
758 fn flush(&mut self) -> io::Result<()> {
759 Ok(())
760 }
761}
762#[stable(feature = "rust1", since = "1.0.0")]
763impl Read for &TcpStream {
764 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
765 self.0.read(buf)
766 }
767
768 fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
769 self.0.read_buf(buf)
770 }
771
772 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
773 self.0.read_vectored(bufs)
774 }
775
776 #[inline]
777 fn is_read_vectored(&self) -> bool {
778 self.0.is_read_vectored()
779 }
780}
781#[stable(feature = "rust1", since = "1.0.0")]
782impl Write for &TcpStream {
783 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
784 self.0.write(buf)
785 }
786
787 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
788 self.0.write_vectored(bufs)
789 }
790
791 #[inline]
792 fn is_write_vectored(&self) -> bool {
793 self.0.is_write_vectored()
794 }
795
796 #[inline]
797 fn flush(&mut self) -> io::Result<()> {
798 Ok(())
799 }
800}
801
802impl AsInner<net_imp::TcpStream> for TcpStream {
803 #[inline]
804 fn as_inner(&self) -> &net_imp::TcpStream {
805 &self.0
806 }
807}
808
809impl FromInner<net_imp::TcpStream> for TcpStream {
810 fn from_inner(inner: net_imp::TcpStream) -> TcpStream {
811 TcpStream(inner)
812 }
813}
814
815impl IntoInner<net_imp::TcpStream> for TcpStream {
816 fn into_inner(self) -> net_imp::TcpStream {
817 self.0
818 }
819}
820
821#[stable(feature = "rust1", since = "1.0.0")]
822impl fmt::Debug for TcpStream {
823 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
824 self.0.fmt(f)
825 }
826}
827
828impl TcpListener {
829 /// Creates a new `TcpListener` which will be bound to the specified
830 /// address.
831 ///
832 /// The returned listener is ready for accepting connections.
833 ///
834 /// Binding with a port number of 0 will request that the OS assigns a port
835 /// to this listener. The port allocated can be queried via the
836 /// [`TcpListener::local_addr`] method.
837 ///
838 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
839 /// its documentation for concrete examples.
840 ///
841 /// If `addr` yields multiple addresses, `bind` will be attempted with
842 /// each of the addresses until one succeeds and returns the listener. If
843 /// none of the addresses succeed in creating a listener, the error returned
844 /// from the last attempt (the last address) is returned.
845 ///
846 /// # Examples
847 ///
848 /// Creates a TCP listener bound to `127.0.0.1:80`:
849 ///
850 /// ```no_run
851 /// use std::net::TcpListener;
852 ///
853 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
854 /// ```
855 ///
856 /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
857 /// TCP listener bound to `127.0.0.1:443`:
858 ///
859 /// ```no_run
860 /// use std::net::{SocketAddr, TcpListener};
861 ///
862 /// let addrs = [
863 /// SocketAddr::from(([127, 0, 0, 1], 80)),
864 /// SocketAddr::from(([127, 0, 0, 1], 443)),
865 /// ];
866 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
867 /// ```
868 ///
869 /// Creates a TCP listener bound to a port assigned by the operating system
870 /// at `127.0.0.1`.
871 ///
872 /// ```no_run
873 /// use std::net::TcpListener;
874 ///
875 /// let socket = TcpListener::bind("127.0.0.1:0").unwrap();
876 /// ```
877 #[stable(feature = "rust1", since = "1.0.0")]
878 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
879 net_imp::TcpListener::bind(addr).map(TcpListener)
880 }
881
882 /// Returns the local socket address of this listener.
883 ///
884 /// # Examples
885 ///
886 /// ```no_run
887 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
888 ///
889 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
890 /// assert_eq!(listener.local_addr().unwrap(),
891 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
892 /// ```
893 #[stable(feature = "rust1", since = "1.0.0")]
894 pub fn local_addr(&self) -> io::Result<SocketAddr> {
895 self.0.socket_addr()
896 }
897
898 /// Creates a new independently owned handle to the underlying socket.
899 ///
900 /// The returned [`TcpListener`] is a reference to the same socket that this
901 /// object references. Both handles can be used to accept incoming
902 /// connections and options set on one listener will affect the other.
903 ///
904 /// # Examples
905 ///
906 /// ```no_run
907 /// use std::net::TcpListener;
908 ///
909 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
910 /// let listener_clone = listener.try_clone().unwrap();
911 /// ```
912 #[stable(feature = "rust1", since = "1.0.0")]
913 pub fn try_clone(&self) -> io::Result<TcpListener> {
914 self.0.duplicate().map(TcpListener)
915 }
916
917 /// Accept a new incoming connection from this listener.
918 ///
919 /// This function will block the calling thread until a new TCP connection
920 /// is established. When established, the corresponding [`TcpStream`] and the
921 /// remote peer's address will be returned.
922 ///
923 /// # Errors
924 ///
925 /// Some errors this function returns do not indicate a problem with the
926 /// listener itself, and a program serving a long-lived listener will
927 /// usually want to handle them and keep accepting connections rather than
928 /// treat them as fatal. These include, but are not limited to:
929 ///
930 /// - An error specific to a single incoming connection that failed before
931 /// it could be accepted, such as one aborted by the peer
932 /// ([`ConnectionAborted`]). A later call may succeed immediately.
933 /// - An error from reaching the per-process or system-wide open file
934 /// descriptor limit. The call can be retried once other file descriptors
935 /// have been closed, typically after a short delay.
936 /// - An error from failing to allocate memory while accepting a connection
937 /// ([`OutOfMemory`]).
938 ///
939 /// Which errors can occur is platform-specific. On Unix, [`Interrupted`]
940 /// errors are retried internally rather than being returned.
941 ///
942 /// [`ConnectionAborted`]: io::ErrorKind::ConnectionAborted
943 /// [`OutOfMemory`]: io::ErrorKind::OutOfMemory
944 /// [`Interrupted`]: io::ErrorKind::Interrupted
945 ///
946 /// # Examples
947 ///
948 /// ```no_run
949 /// use std::net::TcpListener;
950 ///
951 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
952 /// match listener.accept() {
953 /// Ok((_socket, addr)) => println!("new client: {addr:?}"),
954 /// Err(e) => println!("couldn't get client: {e:?}"),
955 /// }
956 /// ```
957 #[stable(feature = "rust1", since = "1.0.0")]
958 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
959 // On wasm*-unknown-unknown, `TcpStream` is uninhabited (as it's
960 // unsupported) and so the `a` variable here is technically unused.
961 #[cfg_attr(all(target_family = "wasm", target_os = "unknown"), allow(unused_variables))]
962 self.0.accept().map(|(a, b)| (TcpStream(a), b))
963 }
964
965 /// Returns 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 /// use std::net::{TcpListener, TcpStream};
981 ///
982 /// fn handle_connection(stream: TcpStream) {
983 /// //...
984 /// }
985 ///
986 /// fn main() -> std::io::Result<()> {
987 /// let listener = TcpListener::bind("127.0.0.1:80")?;
988 ///
989 /// for stream in listener.incoming() {
990 /// match stream {
991 /// Ok(stream) => {
992 /// handle_connection(stream);
993 /// }
994 /// Err(e) => { /* connection failed */ }
995 /// }
996 /// }
997 /// Ok(())
998 /// }
999 /// ```
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 pub fn incoming(&self) -> Incoming<'_> {
1002 Incoming { listener: self }
1003 }
1004
1005 /// Turn this into an iterator over the connections being received on this
1006 /// listener.
1007 ///
1008 /// The returned iterator will never return [`None`] and will also not yield
1009 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
1010 /// calling [`TcpListener::accept`] in a loop.
1011 ///
1012 /// # Errors
1013 ///
1014 /// Each connection yielded by the iterator can fail for the same reasons as
1015 /// [`TcpListener::accept`]; see its documentation for details.
1016 ///
1017 /// # Examples
1018 ///
1019 /// ```no_run
1020 /// #![feature(tcplistener_into_incoming)]
1021 /// use std::net::{TcpListener, TcpStream};
1022 ///
1023 /// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
1024 /// let listener = TcpListener::bind(("127.0.0.1", port)).unwrap();
1025 /// listener.into_incoming()
1026 /// .filter_map(Result::ok) /* Ignore failed connections */
1027 /// }
1028 ///
1029 /// fn main() -> std::io::Result<()> {
1030 /// for stream in listen_on(80) {
1031 /// /* handle the connection here */
1032 /// }
1033 /// Ok(())
1034 /// }
1035 /// ```
1036 #[must_use = "`self` will be dropped if the result is not used"]
1037 #[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1038 pub fn into_incoming(self) -> IntoIncoming {
1039 IntoIncoming { listener: self }
1040 }
1041
1042 /// Sets the value for the `IP_TTL` option on this socket.
1043 ///
1044 /// This value sets the time-to-live field that is used in every packet sent
1045 /// from this socket.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```no_run
1050 /// use std::net::TcpListener;
1051 ///
1052 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
1053 /// listener.set_ttl(100).expect("set_ttl should succeed");
1054 /// ```
1055 #[stable(feature = "net2_mutators", since = "1.9.0")]
1056 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
1057 self.0.set_ttl(ttl)
1058 }
1059
1060 /// Gets the value of the `IP_TTL` option for this socket.
1061 ///
1062 /// For more information about this option, see [`TcpListener::set_ttl`].
1063 ///
1064 /// # Examples
1065 ///
1066 /// ```no_run
1067 /// use std::net::TcpListener;
1068 ///
1069 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
1070 /// listener.set_ttl(100).expect("set_ttl should succeed");
1071 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
1072 /// ```
1073 #[stable(feature = "net2_mutators", since = "1.9.0")]
1074 pub fn ttl(&self) -> io::Result<u32> {
1075 self.0.ttl()
1076 }
1077
1078 /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket.
1079 ///
1080 /// This value sets the unicast hop limit field that is used in every packet
1081 /// sent from this socket.
1082 ///
1083 /// # Examples
1084 ///
1085 /// ```no_run
1086 /// #![feature(ipv6_hop_limit)]
1087 /// use std::net::TcpListener;
1088 ///
1089 /// let listener = TcpListener::bind("[::1]:12345").unwrap();
1090 /// listener.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
1091 /// ```
1092 #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
1093 pub fn set_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
1094 self.0.set_hop_limit_v6(limit)
1095 }
1096
1097 /// Gets the value of the `IPV6_UNICAST_HOPS` option on this socket.
1098 ///
1099 /// For more information about this option, see [`TcpListener::set_hop_limit_v6`].
1100 ///
1101 /// # Examples
1102 ///
1103 /// ```no_run
1104 /// #![feature(ipv6_hop_limit)]
1105 /// use std::net::TcpListener;
1106 ///
1107 /// let listener = TcpListener::bind("[::1]:12345").unwrap();
1108 /// listener.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
1109 /// assert_eq!(listener.hop_limit_v6().unwrap(), 88);
1110 /// ```
1111 #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
1112 pub fn hop_limit_v6(&self) -> io::Result<u8> {
1113 self.0.hop_limit_v6()
1114 }
1115
1116 #[stable(feature = "net2_mutators", since = "1.9.0")]
1117 #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
1118 #[allow(missing_docs)]
1119 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
1120 self.0.set_only_v6(only_v6)
1121 }
1122
1123 #[stable(feature = "net2_mutators", since = "1.9.0")]
1124 #[deprecated(since = "1.16.0", note = "this option can only be set before the socket is bound")]
1125 #[allow(missing_docs)]
1126 pub fn only_v6(&self) -> io::Result<bool> {
1127 self.0.only_v6()
1128 }
1129
1130 /// Gets the value of the `SO_ERROR` option on this socket.
1131 ///
1132 /// This will retrieve the stored error in the underlying socket, clearing
1133 /// the field in the process. This can be useful for checking errors between
1134 /// calls.
1135 ///
1136 /// # Examples
1137 ///
1138 /// ```no_run
1139 /// use std::net::TcpListener;
1140 ///
1141 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
1142 /// listener.take_error().expect("`take_error` should succeed");
1143 /// ```
1144 #[stable(feature = "net2_mutators", since = "1.9.0")]
1145 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1146 self.0.take_error()
1147 }
1148
1149 /// Moves this TCP stream into or out of nonblocking mode.
1150 ///
1151 /// This will result in the `accept` operation becoming nonblocking,
1152 /// i.e., immediately returning from their calls. If the IO operation is
1153 /// successful, `Ok` is returned and no further action is required. If the
1154 /// IO operation could not be completed and needs to be retried, an error
1155 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
1156 ///
1157 /// On most Unix platforms, calling this method corresponds to calling `ioctl`
1158 /// `FIONBIO`. On Windows, calling this method corresponds to calling
1159 /// `ioctlsocket` `FIONBIO`.
1160 ///
1161 /// # Examples
1162 ///
1163 /// Bind a TCP listener to an address, listen for connections, and read
1164 /// bytes in nonblocking mode:
1165 ///
1166 /// ```no_run
1167 /// use std::io;
1168 /// use std::net::TcpListener;
1169 ///
1170 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
1171 /// listener.set_nonblocking(true).expect("set_nonblocking should succeed");
1172 ///
1173 /// # fn wait_for_fd() { unimplemented!() }
1174 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
1175 /// for stream in listener.incoming() {
1176 /// match stream {
1177 /// Ok(s) => {
1178 /// // do something with the TcpStream
1179 /// handle_connection(s);
1180 /// }
1181 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1182 /// // wait until network socket is ready, typically implemented
1183 /// // via platform-specific APIs such as epoll or IOCP
1184 /// wait_for_fd();
1185 /// continue;
1186 /// }
1187 /// Err(e) => panic!("encountered IO error: {e}"),
1188 /// }
1189 /// }
1190 /// ```
1191 #[stable(feature = "net2_mutators", since = "1.9.0")]
1192 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1193 self.0.set_nonblocking(nonblocking)
1194 }
1195}
1196
1197// In addition to the `impl`s here, `TcpListener` also has `impl`s for
1198// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
1199// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
1200// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
1201// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
1202
1203#[stable(feature = "rust1", since = "1.0.0")]
1204impl<'a> Iterator for Incoming<'a> {
1205 type Item = io::Result<TcpStream>;
1206 fn next(&mut self) -> Option<io::Result<TcpStream>> {
1207 Some(self.listener.accept().map(|p| p.0))
1208 }
1209}
1210
1211#[stable(feature = "tcp_listener_incoming_fused_iterator", since = "1.64.0")]
1212impl FusedIterator for Incoming<'_> {}
1213
1214#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1215impl Iterator for IntoIncoming {
1216 type Item = io::Result<TcpStream>;
1217 fn next(&mut self) -> Option<io::Result<TcpStream>> {
1218 Some(self.listener.accept().map(|p| p.0))
1219 }
1220}
1221
1222#[unstable(feature = "tcplistener_into_incoming", issue = "88373")]
1223impl FusedIterator for IntoIncoming {}
1224
1225impl AsInner<net_imp::TcpListener> for TcpListener {
1226 #[inline]
1227 fn as_inner(&self) -> &net_imp::TcpListener {
1228 &self.0
1229 }
1230}
1231
1232impl FromInner<net_imp::TcpListener> for TcpListener {
1233 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
1234 TcpListener(inner)
1235 }
1236}
1237
1238impl IntoInner<net_imp::TcpListener> for TcpListener {
1239 fn into_inner(self) -> net_imp::TcpListener {
1240 self.0
1241 }
1242}
1243
1244#[stable(feature = "rust1", since = "1.0.0")]
1245impl fmt::Debug for TcpListener {
1246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1247 self.0.fmt(f)
1248 }
1249}