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