1 #![deny(unsafe_op_in_unsafe_fn)]
3 #[cfg(all(test, not(target_os = "emscripten")))]
6 use crate::io
::prelude
::*;
9 use crate::io
::{self, Initializer, IoSlice, IoSliceMut}
;
10 use crate::net
::{Shutdown, SocketAddr, ToSocketAddrs}
;
11 use crate::sys_common
::net
as net_imp
;
12 use crate::sys_common
::{AsInner, FromInner, IntoInner}
;
13 use crate::time
::Duration
;
15 /// A TCP stream between a local and a remote socket.
17 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
18 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
19 /// by [reading] and [writing] to it.
21 /// The connection will be closed when the value is dropped. The reading and writing
22 /// portions of the connection can also be shut down individually with the [`shutdown`]
25 /// The Transmission Control Protocol is specified in [IETF RFC 793].
27 /// [`accept`]: TcpListener::accept
28 /// [`connect`]: TcpStream::connect
29 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
31 /// [`shutdown`]: TcpStream::shutdown
37 /// use std::io::prelude::*;
38 /// use std::net::TcpStream;
40 /// fn main() -> std::io::Result<()> {
41 /// let mut stream = TcpStream::connect("127.0.0.1:34254")?;
43 /// stream.write(&[1])?;
44 /// stream.read(&mut [0; 128])?;
46 /// } // the stream is closed here
48 #[stable(feature = "rust1", since = "1.0.0")]
49 pub struct TcpStream(net_imp
::TcpStream
);
51 /// A TCP socket server, listening for connections.
53 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
54 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
55 /// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
57 /// The socket will be closed when the value is dropped.
59 /// The Transmission Control Protocol is specified in [IETF RFC 793].
61 /// [`accept`]: TcpListener::accept
62 /// [`bind`]: TcpListener::bind
63 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
68 /// use std::net::{TcpListener, TcpStream};
70 /// fn handle_client(stream: TcpStream) {
74 /// fn main() -> std::io::Result<()> {
75 /// let listener = TcpListener::bind("127.0.0.1:80")?;
77 /// // accept connections and process them serially
78 /// for stream in listener.incoming() {
79 /// handle_client(stream?);
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct TcpListener(net_imp
::TcpListener
);
87 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
89 /// This `struct` is created by the [`TcpListener::incoming`] method.
90 /// See its documentation for more.
92 /// [`accept`]: TcpListener::accept
93 #[stable(feature = "rust1", since = "1.0.0")]
95 pub struct Incoming
<'a
> {
96 listener
: &'a TcpListener
,
100 /// Opens a TCP connection to a remote host.
102 /// `addr` is an address of the remote host. Anything which implements
103 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
104 /// documentation for concrete examples.
106 /// If `addr` yields multiple addresses, `connect` will be attempted with
107 /// each of the addresses until a connection is successful. If none of
108 /// the addresses result in a successful connection, the error returned from
109 /// the last connection attempt (the last address) is returned.
113 /// Open a TCP connection to `127.0.0.1:8080`:
116 /// use std::net::TcpStream;
118 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
119 /// println!("Connected to the server!");
121 /// println!("Couldn't connect to server...");
125 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
126 /// a TCP connection to `127.0.0.1:8081`:
129 /// use std::net::{SocketAddr, TcpStream};
132 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
133 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
135 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
136 /// println!("Connected to the server!");
138 /// println!("Couldn't connect to server...");
141 #[stable(feature = "rust1", since = "1.0.0")]
142 pub fn connect
<A
: ToSocketAddrs
>(addr
: A
) -> io
::Result
<TcpStream
> {
143 super::each_addr(addr
, net_imp
::TcpStream
::connect
).map(TcpStream
)
146 /// Opens a TCP connection to a remote host with a timeout.
148 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
149 /// timeout must be applied to individual addresses.
151 /// It is an error to pass a zero `Duration` to this function.
153 /// Unlike other methods on `TcpStream`, this does not correspond to a
154 /// single system call. It instead calls `connect` in nonblocking mode and
155 /// then uses an OS-specific mechanism to await the completion of the
156 /// connection request.
157 #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
158 pub fn connect_timeout(addr
: &SocketAddr
, timeout
: Duration
) -> io
::Result
<TcpStream
> {
159 net_imp
::TcpStream
::connect_timeout(addr
, timeout
).map(TcpStream
)
162 /// Returns the socket address of the remote peer of this TCP connection.
167 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
169 /// let stream = TcpStream::connect("127.0.0.1:8080")
170 /// .expect("Couldn't connect to the server...");
171 /// assert_eq!(stream.peer_addr().unwrap(),
172 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
174 #[stable(feature = "rust1", since = "1.0.0")]
175 pub fn peer_addr(&self) -> io
::Result
<SocketAddr
> {
179 /// Returns the socket address of the local half of this TCP connection.
184 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
186 /// let stream = TcpStream::connect("127.0.0.1:8080")
187 /// .expect("Couldn't connect to the server...");
188 /// assert_eq!(stream.local_addr().unwrap().ip(),
189 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn local_addr(&self) -> io
::Result
<SocketAddr
> {
196 /// Shuts down the read, write, or both halves of this connection.
198 /// This function will cause all pending and future I/O on the specified
199 /// portions to return immediately with an appropriate value (see the
200 /// documentation of [`Shutdown`]).
202 /// # Platform-specific behavior
204 /// Calling this function multiple times may result in different behavior,
205 /// depending on the operating system. On Linux, the second call will
206 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
207 /// This may change in the future.
212 /// use std::net::{Shutdown, TcpStream};
214 /// let stream = TcpStream::connect("127.0.0.1:8080")
215 /// .expect("Couldn't connect to the server...");
216 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn shutdown(&self, how
: Shutdown
) -> io
::Result
<()> {
223 /// Creates a new independently owned handle to the underlying socket.
225 /// The returned `TcpStream` is a reference to the same stream that this
226 /// object references. Both handles will read and write the same stream of
227 /// data, and options set on one stream will be propagated to the other
233 /// use std::net::TcpStream;
235 /// let stream = TcpStream::connect("127.0.0.1:8080")
236 /// .expect("Couldn't connect to the server...");
237 /// let stream_clone = stream.try_clone().expect("clone failed...");
239 #[stable(feature = "rust1", since = "1.0.0")]
240 pub fn try_clone(&self) -> io
::Result
<TcpStream
> {
241 self.0.duplicate().map(TcpStream
)
244 /// Sets the read timeout to the timeout specified.
246 /// If the value specified is [`None`], then [`read`] calls will block
247 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
248 /// passed to this method.
250 /// # Platform-specific behavior
252 /// Platforms may return a different error code whenever a read times out as
253 /// a result of setting this option. For example Unix typically returns an
254 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
256 /// [`read`]: Read::read
257 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
258 /// [`TimedOut`]: io::ErrorKind::TimedOut
263 /// use std::net::TcpStream;
265 /// let stream = TcpStream::connect("127.0.0.1:8080")
266 /// .expect("Couldn't connect to the server...");
267 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
270 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
275 /// use std::net::TcpStream;
276 /// use std::time::Duration;
278 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
279 /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
280 /// let err = result.unwrap_err();
281 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
283 #[stable(feature = "socket_timeout", since = "1.4.0")]
284 pub fn set_read_timeout(&self, dur
: Option
<Duration
>) -> io
::Result
<()> {
285 self.0.set_read_timeout(dur
)
288 /// Sets the write timeout to the timeout specified.
290 /// If the value specified is [`None`], then [`write`] calls will block
291 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
292 /// passed to this method.
294 /// # Platform-specific behavior
296 /// Platforms may return a different error code whenever a write times out
297 /// as a result of setting this option. For example Unix typically returns
298 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
300 /// [`write`]: Write::write
301 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
302 /// [`TimedOut`]: io::ErrorKind::TimedOut
307 /// use std::net::TcpStream;
309 /// let stream = TcpStream::connect("127.0.0.1:8080")
310 /// .expect("Couldn't connect to the server...");
311 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
314 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
319 /// use std::net::TcpStream;
320 /// use std::time::Duration;
322 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
323 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
324 /// let err = result.unwrap_err();
325 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
327 #[stable(feature = "socket_timeout", since = "1.4.0")]
328 pub fn set_write_timeout(&self, dur
: Option
<Duration
>) -> io
::Result
<()> {
329 self.0.set_write_timeout(dur
)
332 /// Returns the read timeout of this socket.
334 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
336 /// # Platform-specific behavior
338 /// Some platforms do not provide access to the current timeout.
340 /// [`read`]: Read::read
345 /// use std::net::TcpStream;
347 /// let stream = TcpStream::connect("127.0.0.1:8080")
348 /// .expect("Couldn't connect to the server...");
349 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
350 /// assert_eq!(stream.read_timeout().unwrap(), None);
352 #[stable(feature = "socket_timeout", since = "1.4.0")]
353 pub fn read_timeout(&self) -> io
::Result
<Option
<Duration
>> {
354 self.0.read_timeout()
357 /// Returns the write timeout of this socket.
359 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
361 /// # Platform-specific behavior
363 /// Some platforms do not provide access to the current timeout.
365 /// [`write`]: Write::write
370 /// use std::net::TcpStream;
372 /// let stream = TcpStream::connect("127.0.0.1:8080")
373 /// .expect("Couldn't connect to the server...");
374 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
375 /// assert_eq!(stream.write_timeout().unwrap(), None);
377 #[stable(feature = "socket_timeout", since = "1.4.0")]
378 pub fn write_timeout(&self) -> io
::Result
<Option
<Duration
>> {
379 self.0.write_timeout()
382 /// Receives data on the socket from the remote address to which it is
383 /// connected, without removing that data from the queue. On success,
384 /// returns the number of bytes peeked.
386 /// Successive calls return the same data. This is accomplished by passing
387 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
392 /// use std::net::TcpStream;
394 /// let stream = TcpStream::connect("127.0.0.1:8000")
395 /// .expect("couldn't bind to address");
396 /// let mut buf = [0; 10];
397 /// let len = stream.peek(&mut buf).expect("peek failed");
399 #[stable(feature = "peek", since = "1.18.0")]
400 pub fn peek(&self, buf
: &mut [u8]) -> io
::Result
<usize> {
404 /// Sets the value of the `TCP_NODELAY` option on this socket.
406 /// If set, this option disables the Nagle algorithm. This means that
407 /// segments are always sent as soon as possible, even if there is only a
408 /// small amount of data. When not set, data is buffered until there is a
409 /// sufficient amount to send out, thereby avoiding the frequent sending of
415 /// use std::net::TcpStream;
417 /// let stream = TcpStream::connect("127.0.0.1:8080")
418 /// .expect("Couldn't connect to the server...");
419 /// stream.set_nodelay(true).expect("set_nodelay call failed");
421 #[stable(feature = "net2_mutators", since = "1.9.0")]
422 pub fn set_nodelay(&self, nodelay
: bool
) -> io
::Result
<()> {
423 self.0.set_nodelay(nodelay
)
426 /// Gets the value of the `TCP_NODELAY` option on this socket.
428 /// For more information about this option, see [`TcpStream::set_nodelay`].
433 /// use std::net::TcpStream;
435 /// let stream = TcpStream::connect("127.0.0.1:8080")
436 /// .expect("Couldn't connect to the server...");
437 /// stream.set_nodelay(true).expect("set_nodelay call failed");
438 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
440 #[stable(feature = "net2_mutators", since = "1.9.0")]
441 pub fn nodelay(&self) -> io
::Result
<bool
> {
445 /// Sets the value for the `IP_TTL` option on this socket.
447 /// This value sets the time-to-live field that is used in every packet sent
448 /// from this socket.
453 /// use std::net::TcpStream;
455 /// let stream = TcpStream::connect("127.0.0.1:8080")
456 /// .expect("Couldn't connect to the server...");
457 /// stream.set_ttl(100).expect("set_ttl call failed");
459 #[stable(feature = "net2_mutators", since = "1.9.0")]
460 pub fn set_ttl(&self, ttl
: u32) -> io
::Result
<()> {
464 /// Gets the value of the `IP_TTL` option for this socket.
466 /// For more information about this option, see [`TcpStream::set_ttl`].
471 /// use std::net::TcpStream;
473 /// let stream = TcpStream::connect("127.0.0.1:8080")
474 /// .expect("Couldn't connect to the server...");
475 /// stream.set_ttl(100).expect("set_ttl call failed");
476 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
478 #[stable(feature = "net2_mutators", since = "1.9.0")]
479 pub fn ttl(&self) -> io
::Result
<u32> {
483 /// Gets the value of the `SO_ERROR` option on this socket.
485 /// This will retrieve the stored error in the underlying socket, clearing
486 /// the field in the process. This can be useful for checking errors between
492 /// use std::net::TcpStream;
494 /// let stream = TcpStream::connect("127.0.0.1:8080")
495 /// .expect("Couldn't connect to the server...");
496 /// stream.take_error().expect("No error was expected...");
498 #[stable(feature = "net2_mutators", since = "1.9.0")]
499 pub fn take_error(&self) -> io
::Result
<Option
<io
::Error
>> {
503 /// Moves this TCP stream into or out of nonblocking mode.
505 /// This will result in `read`, `write`, `recv` and `send` operations
506 /// becoming nonblocking, i.e., immediately returning from their calls.
507 /// If the IO operation is successful, `Ok` is returned and no further
508 /// action is required. If the IO operation could not be completed and needs
509 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
512 /// On Unix platforms, calling this method corresponds to calling `fcntl`
513 /// `FIONBIO`. On Windows calling this method corresponds to calling
514 /// `ioctlsocket` `FIONBIO`.
518 /// Reading bytes from a TCP stream in non-blocking mode:
521 /// use std::io::{self, Read};
522 /// use std::net::TcpStream;
524 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
525 /// .expect("Couldn't connect to the server...");
526 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
528 /// # fn wait_for_fd() { unimplemented!() }
529 /// let mut buf = vec![];
531 /// match stream.read_to_end(&mut buf) {
533 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
534 /// // wait until network socket is ready, typically implemented
535 /// // via platform-specific APIs such as epoll or IOCP
538 /// Err(e) => panic!("encountered IO error: {}", e),
541 /// println!("bytes: {:?}", buf);
543 #[stable(feature = "net2_mutators", since = "1.9.0")]
544 pub fn set_nonblocking(&self, nonblocking
: bool
) -> io
::Result
<()> {
545 self.0.set_nonblocking(nonblocking
)
549 #[stable(feature = "rust1", since = "1.0.0")]
550 impl Read
for TcpStream
{
551 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
555 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> io
::Result
<usize> {
556 self.0.read_vectored(bufs
)
560 fn is_read_vectored(&self) -> bool
{
561 self.0.is_read_vectored
()
565 unsafe fn initializer(&self) -> Initializer
{
566 // SAFETY: Read is guaranteed to work on uninitialized memory
567 unsafe { Initializer::nop() }
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl Write
for TcpStream
{
572 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
576 fn write_vectored(&mut self, bufs
: &[IoSlice
<'_
>]) -> io
::Result
<usize> {
577 self.0.write_vectored(bufs
)
581 fn is_write_vectored(&self) -> bool
{
582 self.0.is_write_vectored
()
585 fn flush(&mut self) -> io
::Result
<()> {
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl Read
for &TcpStream
{
591 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
595 fn read_vectored(&mut self, bufs
: &mut [IoSliceMut
<'_
>]) -> io
::Result
<usize> {
596 self.0.read_vectored(bufs
)
600 fn is_read_vectored(&self) -> bool
{
601 self.0.is_read_vectored
()
605 unsafe fn initializer(&self) -> Initializer
{
606 // SAFETY: Read is guaranteed to work on uninitialized memory
607 unsafe { Initializer::nop() }
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl Write
for &TcpStream
{
612 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
616 fn write_vectored(&mut self, bufs
: &[IoSlice
<'_
>]) -> io
::Result
<usize> {
617 self.0.write_vectored(bufs
)
621 fn is_write_vectored(&self) -> bool
{
622 self.0.is_write_vectored
()
625 fn flush(&mut self) -> io
::Result
<()> {
630 impl AsInner
<net_imp
::TcpStream
> for TcpStream
{
631 fn as_inner(&self) -> &net_imp
::TcpStream
{
636 impl FromInner
<net_imp
::TcpStream
> for TcpStream
{
637 fn from_inner(inner
: net_imp
::TcpStream
) -> TcpStream
{
642 impl IntoInner
<net_imp
::TcpStream
> for TcpStream
{
643 fn into_inner(self) -> net_imp
::TcpStream
{
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl fmt
::Debug
for TcpStream
{
650 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
656 /// Creates a new `TcpListener` which will be bound to the specified
659 /// The returned listener is ready for accepting connections.
661 /// Binding with a port number of 0 will request that the OS assigns a port
662 /// to this listener. The port allocated can be queried via the
663 /// [`TcpListener::local_addr`] method.
665 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
666 /// its documentation for concrete examples.
668 /// If `addr` yields multiple addresses, `bind` will be attempted with
669 /// each of the addresses until one succeeds and returns the listener. If
670 /// none of the addresses succeed in creating a listener, the error returned
671 /// from the last attempt (the last address) is returned.
675 /// Creates a TCP listener bound to `127.0.0.1:80`:
678 /// use std::net::TcpListener;
680 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
683 /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
684 /// TCP listener bound to `127.0.0.1:443`:
687 /// use std::net::{SocketAddr, TcpListener};
690 /// SocketAddr::from(([127, 0, 0, 1], 80)),
691 /// SocketAddr::from(([127, 0, 0, 1], 443)),
693 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
695 #[stable(feature = "rust1", since = "1.0.0")]
696 pub fn bind
<A
: ToSocketAddrs
>(addr
: A
) -> io
::Result
<TcpListener
> {
697 super::each_addr(addr
, net_imp
::TcpListener
::bind
).map(TcpListener
)
700 /// Returns the local socket address of this listener.
705 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
707 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
708 /// assert_eq!(listener.local_addr().unwrap(),
709 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
711 #[stable(feature = "rust1", since = "1.0.0")]
712 pub fn local_addr(&self) -> io
::Result
<SocketAddr
> {
716 /// Creates a new independently owned handle to the underlying socket.
718 /// The returned [`TcpListener`] is a reference to the same socket that this
719 /// object references. Both handles can be used to accept incoming
720 /// connections and options set on one listener will affect the other.
725 /// use std::net::TcpListener;
727 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
728 /// let listener_clone = listener.try_clone().unwrap();
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub fn try_clone(&self) -> io
::Result
<TcpListener
> {
732 self.0.duplicate().map(TcpListener
)
735 /// Accept a new incoming connection from this listener.
737 /// This function will block the calling thread until a new TCP connection
738 /// is established. When established, the corresponding [`TcpStream`] and the
739 /// remote peer's address will be returned.
744 /// use std::net::TcpListener;
746 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
747 /// match listener.accept() {
748 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
749 /// Err(e) => println!("couldn't get client: {:?}", e),
752 #[stable(feature = "rust1", since = "1.0.0")]
753 pub fn accept(&self) -> io
::Result
<(TcpStream
, SocketAddr
)> {
754 // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
755 // the `a` variable here is technically unused.
756 #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
757 self.0.accept().map(|(a
, b
)| (TcpStream(a
), b
))
760 /// Returns an iterator over the connections being received on this
763 /// The returned iterator will never return [`None`] and will also not yield
764 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
765 /// calling [`TcpListener::accept`] in a loop.
770 /// use std::net::TcpListener;
772 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
774 /// for stream in listener.incoming() {
777 /// println!("new client!");
779 /// Err(e) => { /* connection failed */ }
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn incoming(&self) -> Incoming
<'_
> {
785 Incoming { listener: self }
788 /// Sets the value for the `IP_TTL` option on this socket.
790 /// This value sets the time-to-live field that is used in every packet sent
791 /// from this socket.
796 /// use std::net::TcpListener;
798 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
799 /// listener.set_ttl(100).expect("could not set TTL");
801 #[stable(feature = "net2_mutators", since = "1.9.0")]
802 pub fn set_ttl(&self, ttl
: u32) -> io
::Result
<()> {
806 /// Gets the value of the `IP_TTL` option for this socket.
808 /// For more information about this option, see [`TcpListener::set_ttl`].
813 /// use std::net::TcpListener;
815 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
816 /// listener.set_ttl(100).expect("could not set TTL");
817 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
819 #[stable(feature = "net2_mutators", since = "1.9.0")]
820 pub fn ttl(&self) -> io
::Result
<u32> {
824 #[stable(feature = "net2_mutators", since = "1.9.0")]
827 reason
= "this option can only be set before the socket is bound"
829 #[allow(missing_docs)]
830 pub fn set_only_v6(&self, only_v6
: bool
) -> io
::Result
<()> {
831 self.0.set_only_v6(only_v6
)
834 #[stable(feature = "net2_mutators", since = "1.9.0")]
837 reason
= "this option can only be set before the socket is bound"
839 #[allow(missing_docs)]
840 pub fn only_v6(&self) -> io
::Result
<bool
> {
844 /// Gets the value of the `SO_ERROR` option on this socket.
846 /// This will retrieve the stored error in the underlying socket, clearing
847 /// the field in the process. This can be useful for checking errors between
853 /// use std::net::TcpListener;
855 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
856 /// listener.take_error().expect("No error was expected");
858 #[stable(feature = "net2_mutators", since = "1.9.0")]
859 pub fn take_error(&self) -> io
::Result
<Option
<io
::Error
>> {
863 /// Moves this TCP stream into or out of nonblocking mode.
865 /// This will result in the `accept` operation becoming nonblocking,
866 /// i.e., immediately returning from their calls. If the IO operation is
867 /// successful, `Ok` is returned and no further action is required. If the
868 /// IO operation could not be completed and needs to be retried, an error
869 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
871 /// On Unix platforms, calling this method corresponds to calling `fcntl`
872 /// `FIONBIO`. On Windows calling this method corresponds to calling
873 /// `ioctlsocket` `FIONBIO`.
877 /// Bind a TCP listener to an address, listen for connections, and read
878 /// bytes in nonblocking mode:
882 /// use std::net::TcpListener;
884 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
885 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
887 /// # fn wait_for_fd() { unimplemented!() }
888 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
889 /// for stream in listener.incoming() {
892 /// // do something with the TcpStream
893 /// handle_connection(s);
895 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
896 /// // wait until network socket is ready, typically implemented
897 /// // via platform-specific APIs such as epoll or IOCP
901 /// Err(e) => panic!("encountered IO error: {}", e),
905 #[stable(feature = "net2_mutators", since = "1.9.0")]
906 pub fn set_nonblocking(&self, nonblocking
: bool
) -> io
::Result
<()> {
907 self.0.set_nonblocking(nonblocking
)
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl<'a
> Iterator
for Incoming
<'a
> {
913 type Item
= io
::Result
<TcpStream
>;
914 fn next(&mut self) -> Option
<io
::Result
<TcpStream
>> {
915 Some(self.listener
.accept().map(|p
| p
.0))
919 impl AsInner
<net_imp
::TcpListener
> for TcpListener
{
920 fn as_inner(&self) -> &net_imp
::TcpListener
{
925 impl FromInner
<net_imp
::TcpListener
> for TcpListener
{
926 fn from_inner(inner
: net_imp
::TcpListener
) -> TcpListener
{
931 impl IntoInner
<net_imp
::TcpListener
> for TcpListener
{
932 fn into_inner(self) -> net_imp
::TcpListener
{
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl fmt
::Debug
for TcpListener
{
939 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{