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