1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 use io::{self, Initializer};
15 use net::{ToSocketAddrs, SocketAddr, Shutdown};
16 use sys_common::net as net_imp;
17 use sys_common::{AsInner, FromInner, IntoInner};
20 /// A TCP stream between a local and a remote socket.
22 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
23 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
24 /// by [reading] and [writing] to it.
26 /// The connection will be closed when the value is dropped. The reading and writing
27 /// portions of the connection can also be shut down individually with the [`shutdown`]
30 /// The Transmission Control Protocol is specified in [IETF RFC 793].
32 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
33 /// [`connect`]: #method.connect
34 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
35 /// [reading]: ../../std/io/trait.Read.html
36 /// [`shutdown`]: #method.shutdown
37 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
38 /// [writing]: ../../std/io/trait.Write.html
43 /// use std::io::prelude::*;
44 /// use std::net::TcpStream;
47 /// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
49 /// // ignore the Result
50 /// let _ = stream.write(&[1]);
51 /// let _ = stream.read(&mut [0; 128]); // ignore here too
52 /// } // the stream is closed here
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub struct TcpStream(net_imp::TcpStream);
57 /// A TCP socket server, listening for connections.
59 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
60 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
61 /// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
63 /// The socket will be closed when the value is dropped.
65 /// The Transmission Control Protocol is specified in [IETF RFC 793].
67 /// [`accept`]: #method.accept
68 /// [`bind`]: #method.bind
69 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
70 /// [`Incoming`]: ../../std/net/struct.Incoming.html
71 /// [`TcpListener::incoming`]: #method.incoming
77 /// use std::net::{TcpListener, TcpStream};
79 /// fn handle_client(stream: TcpStream) {
83 /// # fn process() -> io::Result<()> {
84 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
86 /// // accept connections and process them serially
87 /// for stream in listener.incoming() {
88 /// handle_client(stream?);
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub struct TcpListener(net_imp::TcpListener);
96 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
98 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
99 /// See its documentation for more.
101 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
102 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
103 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
104 #[stable(feature = "rust1", since = "1.0.0")]
106 pub struct Incoming<'a> { listener: &'a TcpListener }
109 /// Opens a TCP connection to a remote host.
111 /// `addr` is an address of the remote host. Anything which implements
112 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
113 /// documentation for concrete examples.
114 /// In case [`ToSocketAddrs::to_socket_addrs()`] returns more than one entry,
115 /// then the first valid and reachable address is used.
117 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
118 /// [`ToSocketAddrs::to_socket_addrs()`]:
119 /// ../../std/net/trait.ToSocketAddrs.html#tymethod.to_socket_addrs
124 /// use std::net::TcpStream;
126 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
127 /// println!("Connected to the server!");
129 /// println!("Couldn't connect to server...");
132 #[stable(feature = "rust1", since = "1.0.0")]
133 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
134 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
137 /// Opens a TCP connection to a remote host with a timeout.
139 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
140 /// timeout must be applied to individual addresses.
142 /// It is an error to pass a zero `Duration` to this function.
144 /// Unlike other methods on `TcpStream`, this does not correspond to a
145 /// single system call. It instead calls `connect` in nonblocking mode and
146 /// then uses an OS-specific mechanism to await the completion of the
147 /// connection request.
149 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
150 #[unstable(feature = "tcpstream_connect_timeout", issue = "43079")]
151 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
152 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
155 /// Returns the socket address of the remote peer of this TCP connection.
160 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
162 /// let stream = TcpStream::connect("127.0.0.1:8080")
163 /// .expect("Couldn't connect to the server...");
164 /// assert_eq!(stream.peer_addr().unwrap(),
165 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
172 /// Returns the socket address of the local half of this TCP connection.
177 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
179 /// let stream = TcpStream::connect("127.0.0.1:8080")
180 /// .expect("Couldn't connect to the server...");
181 /// assert_eq!(stream.local_addr().unwrap(),
182 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub fn local_addr(&self) -> io::Result<SocketAddr> {
189 /// Shuts down the read, write, or both halves of this connection.
191 /// This function will cause all pending and future I/O on the specified
192 /// portions to return immediately with an appropriate value (see the
193 /// documentation of [`Shutdown`]).
195 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
197 /// # Platform-specific behavior
199 /// Calling this function multiple times may result in different behavior,
200 /// depending on the operating system. On Linux, the second call will
201 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
202 /// This may change in the future.
207 /// use std::net::{Shutdown, TcpStream};
209 /// let stream = TcpStream::connect("127.0.0.1:8080")
210 /// .expect("Couldn't connect to the server...");
211 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
213 #[stable(feature = "rust1", since = "1.0.0")]
214 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
218 /// Creates a new independently owned handle to the underlying socket.
220 /// The returned `TcpStream` is a reference to the same stream that this
221 /// object references. Both handles will read and write the same stream of
222 /// data, and options set on one stream will be propagated to the other
228 /// use std::net::TcpStream;
230 /// let stream = TcpStream::connect("127.0.0.1:8080")
231 /// .expect("Couldn't connect to the server...");
232 /// let stream_clone = stream.try_clone().expect("clone failed...");
234 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn try_clone(&self) -> io::Result<TcpStream> {
236 self.0.duplicate().map(TcpStream)
239 /// Sets the read timeout to the timeout specified.
241 /// If the value specified is [`None`], then [`read`] calls will block
242 /// indefinitely. It is an error to pass the zero `Duration` to this
247 /// Platforms may return a different error code whenever a read times out as
248 /// a result of setting this option. For example Unix typically returns an
249 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
251 /// [`None`]: ../../std/option/enum.Option.html#variant.None
252 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
253 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
254 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
259 /// use std::net::TcpStream;
261 /// let stream = TcpStream::connect("127.0.0.1:8080")
262 /// .expect("Couldn't connect to the server...");
263 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
265 #[stable(feature = "socket_timeout", since = "1.4.0")]
266 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
267 self.0.set_read_timeout(dur)
270 /// Sets the write timeout to the timeout specified.
272 /// If the value specified is [`None`], then [`write`] calls will block
273 /// indefinitely. It is an error to pass the zero [`Duration`] to this
278 /// Platforms may return a different error code whenever a write times out
279 /// as a result of setting this option. For example Unix typically returns
280 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
282 /// [`None`]: ../../std/option/enum.Option.html#variant.None
283 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
284 /// [`Duration`]: ../../std/time/struct.Duration.html
285 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
286 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
291 /// use std::net::TcpStream;
293 /// let stream = TcpStream::connect("127.0.0.1:8080")
294 /// .expect("Couldn't connect to the server...");
295 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
297 #[stable(feature = "socket_timeout", since = "1.4.0")]
298 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
299 self.0.set_write_timeout(dur)
302 /// Returns the read timeout of this socket.
304 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
308 /// Some platforms do not provide access to the current timeout.
310 /// [`None`]: ../../std/option/enum.Option.html#variant.None
311 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
316 /// use std::net::TcpStream;
318 /// let stream = TcpStream::connect("127.0.0.1:8080")
319 /// .expect("Couldn't connect to the server...");
320 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
321 /// assert_eq!(stream.read_timeout().unwrap(), None);
323 #[stable(feature = "socket_timeout", since = "1.4.0")]
324 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
325 self.0.read_timeout()
328 /// Returns the write timeout of this socket.
330 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
334 /// Some platforms do not provide access to the current timeout.
336 /// [`None`]: ../../std/option/enum.Option.html#variant.None
337 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
342 /// use std::net::TcpStream;
344 /// let stream = TcpStream::connect("127.0.0.1:8080")
345 /// .expect("Couldn't connect to the server...");
346 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
347 /// assert_eq!(stream.write_timeout().unwrap(), None);
349 #[stable(feature = "socket_timeout", since = "1.4.0")]
350 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
351 self.0.write_timeout()
354 /// Receives data on the socket from the remote address to which it is
355 /// connected, without removing that data from the queue. On success,
356 /// returns the number of bytes peeked.
358 /// Successive calls return the same data. This is accomplished by passing
359 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
364 /// use std::net::TcpStream;
366 /// let stream = TcpStream::connect("127.0.0.1:8000")
367 /// .expect("couldn't bind to address");
368 /// let mut buf = [0; 10];
369 /// let len = stream.peek(&mut buf).expect("peek failed");
371 #[stable(feature = "peek", since = "1.18.0")]
372 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
376 /// Sets the value of the `TCP_NODELAY` option on this socket.
378 /// If set, this option disables the Nagle algorithm. This means that
379 /// segments are always sent as soon as possible, even if there is only a
380 /// small amount of data. When not set, data is buffered until there is a
381 /// sufficient amount to send out, thereby avoiding the frequent sending of
387 /// use std::net::TcpStream;
389 /// let stream = TcpStream::connect("127.0.0.1:8080")
390 /// .expect("Couldn't connect to the server...");
391 /// stream.set_nodelay(true).expect("set_nodelay call failed");
393 #[stable(feature = "net2_mutators", since = "1.9.0")]
394 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
395 self.0.set_nodelay(nodelay)
398 /// Gets the value of the `TCP_NODELAY` option on this socket.
400 /// For more information about this option, see [`set_nodelay`][link].
402 /// [link]: #method.set_nodelay
407 /// use std::net::TcpStream;
409 /// let stream = TcpStream::connect("127.0.0.1:8080")
410 /// .expect("Couldn't connect to the server...");
411 /// stream.set_nodelay(true).expect("set_nodelay call failed");
412 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
414 #[stable(feature = "net2_mutators", since = "1.9.0")]
415 pub fn nodelay(&self) -> io::Result<bool> {
419 /// Sets the value for the `IP_TTL` option on this socket.
421 /// This value sets the time-to-live field that is used in every packet sent
422 /// from this socket.
427 /// use std::net::TcpStream;
429 /// let stream = TcpStream::connect("127.0.0.1:8080")
430 /// .expect("Couldn't connect to the server...");
431 /// stream.set_ttl(100).expect("set_ttl call failed");
433 #[stable(feature = "net2_mutators", since = "1.9.0")]
434 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
438 /// Gets the value of the `IP_TTL` option for this socket.
440 /// For more information about this option, see [`set_ttl`][link].
442 /// [link]: #method.set_ttl
447 /// use std::net::TcpStream;
449 /// let stream = TcpStream::connect("127.0.0.1:8080")
450 /// .expect("Couldn't connect to the server...");
451 /// stream.set_ttl(100).expect("set_ttl call failed");
452 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
454 #[stable(feature = "net2_mutators", since = "1.9.0")]
455 pub fn ttl(&self) -> io::Result<u32> {
459 /// Get the value of the `SO_ERROR` option on this socket.
461 /// This will retrieve the stored error in the underlying socket, clearing
462 /// the field in the process. This can be useful for checking errors between
468 /// use std::net::TcpStream;
470 /// let stream = TcpStream::connect("127.0.0.1:8080")
471 /// .expect("Couldn't connect to the server...");
472 /// stream.take_error().expect("No error was expected...");
474 #[stable(feature = "net2_mutators", since = "1.9.0")]
475 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
479 /// Moves this TCP stream into or out of nonblocking mode.
481 /// On Unix this corresponds to calling fcntl, and on Windows this
482 /// corresponds to calling ioctlsocket.
487 /// use std::net::TcpStream;
489 /// let stream = TcpStream::connect("127.0.0.1:8080")
490 /// .expect("Couldn't connect to the server...");
491 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
493 #[stable(feature = "net2_mutators", since = "1.9.0")]
494 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
495 self.0.set_nonblocking(nonblocking)
499 #[stable(feature = "rust1", since = "1.0.0")]
500 impl Read for TcpStream {
501 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
504 unsafe fn initializer(&self) -> Initializer {
508 #[stable(feature = "rust1", since = "1.0.0")]
509 impl Write for TcpStream {
510 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
511 fn flush(&mut self) -> io::Result<()> { Ok(()) }
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl<'a> Read for &'a TcpStream {
515 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
518 unsafe fn initializer(&self) -> Initializer {
522 #[stable(feature = "rust1", since = "1.0.0")]
523 impl<'a> Write for &'a TcpStream {
524 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
525 fn flush(&mut self) -> io::Result<()> { Ok(()) }
528 impl AsInner<net_imp::TcpStream> for TcpStream {
529 fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
532 impl FromInner<net_imp::TcpStream> for TcpStream {
533 fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
536 impl IntoInner<net_imp::TcpStream> for TcpStream {
537 fn into_inner(self) -> net_imp::TcpStream { self.0 }
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl fmt::Debug for TcpStream {
542 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
548 /// Creates a new `TcpListener` which will be bound to the specified
551 /// The returned listener is ready for accepting connections.
553 /// Binding with a port number of 0 will request that the OS assigns a port
554 /// to this listener. The port allocated can be queried via the
555 /// [`local_addr`] method.
557 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
558 /// its documentation for concrete examples.
560 /// [`local_addr`]: #method.local_addr
561 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
566 /// use std::net::TcpListener;
568 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
570 #[stable(feature = "rust1", since = "1.0.0")]
571 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
572 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
575 /// Returns the local socket address of this listener.
580 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
582 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
583 /// assert_eq!(listener.local_addr().unwrap(),
584 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub fn local_addr(&self) -> io::Result<SocketAddr> {
591 /// Creates a new independently owned handle to the underlying socket.
593 /// The returned [`TcpListener`] is a reference to the same socket that this
594 /// object references. Both handles can be used to accept incoming
595 /// connections and options set on one listener will affect the other.
597 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
602 /// use std::net::TcpListener;
604 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
605 /// let listener_clone = listener.try_clone().unwrap();
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn try_clone(&self) -> io::Result<TcpListener> {
609 self.0.duplicate().map(TcpListener)
612 /// Accept a new incoming connection from this listener.
614 /// This function will block the calling thread until a new TCP connection
615 /// is established. When established, the corresponding [`TcpStream`] and the
616 /// remote peer's address will be returned.
618 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
623 /// use std::net::TcpListener;
625 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
626 /// match listener.accept() {
627 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
628 /// Err(e) => println!("couldn't get client: {:?}", e),
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
633 self.0.accept().map(|(a, b)| (TcpStream(a), b))
636 /// Returns an iterator over the connections being received on this
639 /// The returned iterator will never return [`None`] and will also not yield
640 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
641 /// calling [`accept`] in a loop.
643 /// [`None`]: ../../std/option/enum.Option.html#variant.None
644 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
645 /// [`accept`]: #method.accept
650 /// use std::net::TcpListener;
652 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
654 /// for stream in listener.incoming() {
657 /// println!("new client!");
659 /// Err(e) => { /* connection failed */ }
663 #[stable(feature = "rust1", since = "1.0.0")]
664 pub fn incoming(&self) -> Incoming {
665 Incoming { listener: self }
668 /// Sets the value for the `IP_TTL` option on this socket.
670 /// This value sets the time-to-live field that is used in every packet sent
671 /// from this socket.
676 /// use std::net::TcpListener;
678 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
679 /// listener.set_ttl(100).expect("could not set TTL");
681 #[stable(feature = "net2_mutators", since = "1.9.0")]
682 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
686 /// Gets the value of the `IP_TTL` option for this socket.
688 /// For more information about this option, see [`set_ttl`][link].
690 /// [link]: #method.set_ttl
695 /// use std::net::TcpListener;
697 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
698 /// listener.set_ttl(100).expect("could not set TTL");
699 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
701 #[stable(feature = "net2_mutators", since = "1.9.0")]
702 pub fn ttl(&self) -> io::Result<u32> {
706 #[stable(feature = "net2_mutators", since = "1.9.0")]
707 #[rustc_deprecated(since = "1.16.0",
708 reason = "this option can only be set before the socket is bound")]
709 #[allow(missing_docs)]
710 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
711 self.0.set_only_v6(only_v6)
714 #[stable(feature = "net2_mutators", since = "1.9.0")]
715 #[rustc_deprecated(since = "1.16.0",
716 reason = "this option can only be set before the socket is bound")]
717 #[allow(missing_docs)]
718 pub fn only_v6(&self) -> io::Result<bool> {
722 /// Get the value of the `SO_ERROR` option on this socket.
724 /// This will retrieve the stored error in the underlying socket, clearing
725 /// the field in the process. This can be useful for checking errors between
731 /// use std::net::TcpListener;
733 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
734 /// listener.take_error().expect("No error was expected");
736 #[stable(feature = "net2_mutators", since = "1.9.0")]
737 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
741 /// Moves this TCP stream into or out of nonblocking mode.
743 /// On Unix this corresponds to calling fcntl, and on Windows this
744 /// corresponds to calling ioctlsocket.
749 /// use std::net::TcpListener;
751 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
752 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
754 #[stable(feature = "net2_mutators", since = "1.9.0")]
755 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
756 self.0.set_nonblocking(nonblocking)
760 #[stable(feature = "rust1", since = "1.0.0")]
761 impl<'a> Iterator for Incoming<'a> {
762 type Item = io::Result<TcpStream>;
763 fn next(&mut self) -> Option<io::Result<TcpStream>> {
764 Some(self.listener.accept().map(|p| p.0))
768 impl AsInner<net_imp::TcpListener> for TcpListener {
769 fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
772 impl FromInner<net_imp::TcpListener> for TcpListener {
773 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
778 impl IntoInner<net_imp::TcpListener> for TcpListener {
779 fn into_inner(self) -> net_imp::TcpListener { self.0 }
782 #[stable(feature = "rust1", since = "1.0.0")]
783 impl fmt::Debug for TcpListener {
784 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
789 #[cfg(all(test, not(target_os = "emscripten")))]
794 use net::test::{next_test_ip4, next_test_ip6};
795 use sync::mpsc::channel;
796 use sys_common::AsInner;
797 use time::{Instant, Duration};
800 fn each_ip(f: &mut FnMut(SocketAddr)) {
809 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
816 match TcpListener::bind("1.1.1.1:9999") {
819 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
825 match TcpStream::connect("0.0.0.0:1") {
827 Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
828 e.kind() == ErrorKind::InvalidInput ||
829 e.kind() == ErrorKind::AddrInUse ||
830 e.kind() == ErrorKind::AddrNotAvailable,
831 "bad error: {} {:?}", e, e.kind()),
836 fn listen_localhost() {
837 let socket_addr = next_test_ip4();
838 let listener = t!(TcpListener::bind(&socket_addr));
840 let _t = thread::spawn(move || {
841 let mut stream = t!(TcpStream::connect(&("localhost",
842 socket_addr.port())));
843 t!(stream.write(&[144]));
846 let mut stream = t!(listener.accept()).0;
848 t!(stream.read(&mut buf));
849 assert!(buf[0] == 144);
853 fn connect_loopback() {
854 each_ip(&mut |addr| {
855 let acceptor = t!(TcpListener::bind(&addr));
857 let _t = thread::spawn(move|| {
858 let host = match addr {
859 SocketAddr::V4(..) => "127.0.0.1",
860 SocketAddr::V6(..) => "::1",
862 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
863 t!(stream.write(&[66]));
866 let mut stream = t!(acceptor.accept()).0;
868 t!(stream.read(&mut buf));
869 assert!(buf[0] == 66);
875 each_ip(&mut |addr| {
876 let acceptor = t!(TcpListener::bind(&addr));
878 let (tx, rx) = channel();
879 let _t = thread::spawn(move|| {
880 let mut stream = t!(TcpStream::connect(&addr));
881 t!(stream.write(&[99]));
882 tx.send(t!(stream.local_addr())).unwrap();
885 let (mut stream, addr) = t!(acceptor.accept());
887 t!(stream.read(&mut buf));
888 assert!(buf[0] == 99);
889 assert_eq!(addr, t!(rx.recv()));
895 each_ip(&mut |addr| {
896 let acceptor = t!(TcpListener::bind(&addr));
898 let _t = thread::spawn(move|| {
899 let _stream = t!(TcpStream::connect(&addr));
903 let mut stream = t!(acceptor.accept()).0;
905 let nread = t!(stream.read(&mut buf));
906 assert_eq!(nread, 0);
907 let nread = t!(stream.read(&mut buf));
908 assert_eq!(nread, 0);
914 each_ip(&mut |addr| {
915 let acceptor = t!(TcpListener::bind(&addr));
917 let (tx, rx) = channel();
918 let _t = thread::spawn(move|| {
919 drop(t!(TcpStream::connect(&addr)));
920 tx.send(()).unwrap();
923 let mut stream = t!(acceptor.accept()).0;
926 match stream.write(&buf) {
929 assert!(e.kind() == ErrorKind::ConnectionReset ||
930 e.kind() == ErrorKind::BrokenPipe ||
931 e.kind() == ErrorKind::ConnectionAborted,
932 "unknown error: {}", e);
939 fn multiple_connect_serial() {
940 each_ip(&mut |addr| {
942 let acceptor = t!(TcpListener::bind(&addr));
944 let _t = thread::spawn(move|| {
946 let mut stream = t!(TcpStream::connect(&addr));
947 t!(stream.write(&[99]));
951 for stream in acceptor.incoming().take(max) {
952 let mut stream = t!(stream);
954 t!(stream.read(&mut buf));
955 assert_eq!(buf[0], 99);
961 fn multiple_connect_interleaved_greedy_schedule() {
962 const MAX: usize = 10;
963 each_ip(&mut |addr| {
964 let acceptor = t!(TcpListener::bind(&addr));
966 let _t = thread::spawn(move|| {
967 let acceptor = acceptor;
968 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
969 // Start another thread to handle the connection
970 let _t = thread::spawn(move|| {
971 let mut stream = t!(stream);
973 t!(stream.read(&mut buf));
974 assert!(buf[0] == i as u8);
982 fn connect(i: usize, addr: SocketAddr) {
983 if i == MAX { return }
985 let t = thread::spawn(move|| {
986 let mut stream = t!(TcpStream::connect(&addr));
987 // Connect again before writing
988 connect(i + 1, addr);
989 t!(stream.write(&[i as u8]));
991 t.join().ok().unwrap();
996 fn multiple_connect_interleaved_lazy_schedule() {
997 const MAX: usize = 10;
998 each_ip(&mut |addr| {
999 let acceptor = t!(TcpListener::bind(&addr));
1001 let _t = thread::spawn(move|| {
1002 for stream in acceptor.incoming().take(MAX) {
1003 // Start another thread to handle the connection
1004 let _t = thread::spawn(move|| {
1005 let mut stream = t!(stream);
1007 t!(stream.read(&mut buf));
1008 assert!(buf[0] == 99);
1016 fn connect(i: usize, addr: SocketAddr) {
1017 if i == MAX { return }
1019 let t = thread::spawn(move|| {
1020 let mut stream = t!(TcpStream::connect(&addr));
1021 connect(i + 1, addr);
1022 t!(stream.write(&[99]));
1024 t.join().ok().unwrap();
1029 fn socket_and_peer_name() {
1030 each_ip(&mut |addr| {
1031 let listener = t!(TcpListener::bind(&addr));
1032 let so_name = t!(listener.local_addr());
1033 assert_eq!(addr, so_name);
1034 let _t = thread::spawn(move|| {
1035 t!(listener.accept());
1038 let stream = t!(TcpStream::connect(&addr));
1039 assert_eq!(addr, t!(stream.peer_addr()));
1045 each_ip(&mut |addr| {
1046 let (tx, rx) = channel();
1047 let srv = t!(TcpListener::bind(&addr));
1048 let _t = thread::spawn(move|| {
1049 let mut cl = t!(srv.accept()).0;
1050 cl.write(&[10]).unwrap();
1052 t!(cl.read(&mut b));
1053 tx.send(()).unwrap();
1056 let mut c = t!(TcpStream::connect(&addr));
1057 let mut b = [0; 10];
1058 assert_eq!(c.read(&mut b).unwrap(), 1);
1066 each_ip(&mut |addr| {
1067 let _listener = t!(TcpListener::bind(&addr));
1068 match TcpListener::bind(&addr) {
1071 assert!(e.kind() == ErrorKind::ConnectionRefused ||
1072 e.kind() == ErrorKind::Other ||
1073 e.kind() == ErrorKind::AddrInUse,
1074 "unknown error: {} {:?}", e, e.kind());
1082 each_ip(&mut |addr| {
1083 let acceptor = t!(TcpListener::bind(&addr));
1085 let _t = thread::spawn(move|| {
1086 t!(TcpStream::connect(&addr));
1089 t!(acceptor.accept());
1091 t!(TcpListener::bind(&addr));
1096 fn tcp_clone_smoke() {
1097 each_ip(&mut |addr| {
1098 let acceptor = t!(TcpListener::bind(&addr));
1100 let _t = thread::spawn(move|| {
1101 let mut s = t!(TcpStream::connect(&addr));
1102 let mut buf = [0, 0];
1103 assert_eq!(s.read(&mut buf).unwrap(), 1);
1104 assert_eq!(buf[0], 1);
1108 let mut s1 = t!(acceptor.accept()).0;
1109 let s2 = t!(s1.try_clone());
1111 let (tx1, rx1) = channel();
1112 let (tx2, rx2) = channel();
1113 let _t = thread::spawn(move|| {
1115 rx1.recv().unwrap();
1117 tx2.send(()).unwrap();
1119 tx1.send(()).unwrap();
1120 let mut buf = [0, 0];
1121 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1122 rx2.recv().unwrap();
1127 fn tcp_clone_two_read() {
1128 each_ip(&mut |addr| {
1129 let acceptor = t!(TcpListener::bind(&addr));
1130 let (tx1, rx) = channel();
1131 let tx2 = tx1.clone();
1133 let _t = thread::spawn(move|| {
1134 let mut s = t!(TcpStream::connect(&addr));
1141 let mut s1 = t!(acceptor.accept()).0;
1142 let s2 = t!(s1.try_clone());
1144 let (done, rx) = channel();
1145 let _t = thread::spawn(move|| {
1147 let mut buf = [0, 0];
1148 t!(s2.read(&mut buf));
1149 tx2.send(()).unwrap();
1150 done.send(()).unwrap();
1152 let mut buf = [0, 0];
1153 t!(s1.read(&mut buf));
1154 tx1.send(()).unwrap();
1161 fn tcp_clone_two_write() {
1162 each_ip(&mut |addr| {
1163 let acceptor = t!(TcpListener::bind(&addr));
1165 let _t = thread::spawn(move|| {
1166 let mut s = t!(TcpStream::connect(&addr));
1167 let mut buf = [0, 1];
1168 t!(s.read(&mut buf));
1169 t!(s.read(&mut buf));
1172 let mut s1 = t!(acceptor.accept()).0;
1173 let s2 = t!(s1.try_clone());
1175 let (done, rx) = channel();
1176 let _t = thread::spawn(move|| {
1179 done.send(()).unwrap();
1188 fn shutdown_smoke() {
1189 each_ip(&mut |addr| {
1190 let a = t!(TcpListener::bind(&addr));
1191 let _t = thread::spawn(move|| {
1192 let mut c = t!(a.accept()).0;
1194 assert_eq!(c.read(&mut b).unwrap(), 0);
1198 let mut s = t!(TcpStream::connect(&addr));
1199 t!(s.shutdown(Shutdown::Write));
1200 assert!(s.write(&[1]).is_err());
1202 assert_eq!(t!(s.read(&mut b)), 1);
1203 assert_eq!(b[0], 1);
1208 fn close_readwrite_smoke() {
1209 each_ip(&mut |addr| {
1210 let a = t!(TcpListener::bind(&addr));
1211 let (tx, rx) = channel::<()>();
1212 let _t = thread::spawn(move|| {
1213 let _s = t!(a.accept());
1218 let mut s = t!(TcpStream::connect(&addr));
1219 let mut s2 = t!(s.try_clone());
1221 // closing should prevent reads/writes
1222 t!(s.shutdown(Shutdown::Write));
1223 assert!(s.write(&[0]).is_err());
1224 t!(s.shutdown(Shutdown::Read));
1225 assert_eq!(s.read(&mut b).unwrap(), 0);
1227 // closing should affect previous handles
1228 assert!(s2.write(&[0]).is_err());
1229 assert_eq!(s2.read(&mut b).unwrap(), 0);
1231 // closing should affect new handles
1232 let mut s3 = t!(s.try_clone());
1233 assert!(s3.write(&[0]).is_err());
1234 assert_eq!(s3.read(&mut b).unwrap(), 0);
1236 // make sure these don't die
1237 let _ = s2.shutdown(Shutdown::Read);
1238 let _ = s2.shutdown(Shutdown::Write);
1239 let _ = s3.shutdown(Shutdown::Read);
1240 let _ = s3.shutdown(Shutdown::Write);
1246 #[cfg(unix)] // test doesn't work on Windows, see #31657
1247 fn close_read_wakes_up() {
1248 each_ip(&mut |addr| {
1249 let a = t!(TcpListener::bind(&addr));
1250 let (tx1, rx) = channel::<()>();
1251 let _t = thread::spawn(move|| {
1252 let _s = t!(a.accept());
1256 let s = t!(TcpStream::connect(&addr));
1257 let s2 = t!(s.try_clone());
1258 let (tx, rx) = channel();
1259 let _t = thread::spawn(move|| {
1261 assert_eq!(t!(s2.read(&mut [0])), 0);
1262 tx.send(()).unwrap();
1264 // this should wake up the child thread
1265 t!(s.shutdown(Shutdown::Read));
1267 // this test will never finish if the child doesn't wake up
1274 fn clone_while_reading() {
1275 each_ip(&mut |addr| {
1276 let accept = t!(TcpListener::bind(&addr));
1278 // Enqueue a thread to write to a socket
1279 let (tx, rx) = channel();
1280 let (txdone, rxdone) = channel();
1281 let txdone2 = txdone.clone();
1282 let _t = thread::spawn(move|| {
1283 let mut tcp = t!(TcpStream::connect(&addr));
1285 t!(tcp.write(&[0]));
1286 txdone2.send(()).unwrap();
1289 // Spawn off a reading clone
1290 let tcp = t!(accept.accept()).0;
1291 let tcp2 = t!(tcp.try_clone());
1292 let txdone3 = txdone.clone();
1293 let _t = thread::spawn(move|| {
1294 let mut tcp2 = tcp2;
1295 t!(tcp2.read(&mut [0]));
1296 txdone3.send(()).unwrap();
1299 // Try to ensure that the reading clone is indeed reading
1301 thread::yield_now();
1304 // clone the handle again while it's reading, then let it finish the
1306 let _ = t!(tcp.try_clone());
1307 tx.send(()).unwrap();
1308 rxdone.recv().unwrap();
1309 rxdone.recv().unwrap();
1314 fn clone_accept_smoke() {
1315 each_ip(&mut |addr| {
1316 let a = t!(TcpListener::bind(&addr));
1317 let a2 = t!(a.try_clone());
1319 let _t = thread::spawn(move|| {
1320 let _ = TcpStream::connect(&addr);
1322 let _t = thread::spawn(move|| {
1323 let _ = TcpStream::connect(&addr);
1332 fn clone_accept_concurrent() {
1333 each_ip(&mut |addr| {
1334 let a = t!(TcpListener::bind(&addr));
1335 let a2 = t!(a.try_clone());
1337 let (tx, rx) = channel();
1338 let tx2 = tx.clone();
1340 let _t = thread::spawn(move|| {
1341 tx.send(t!(a.accept())).unwrap();
1343 let _t = thread::spawn(move|| {
1344 tx2.send(t!(a2.accept())).unwrap();
1347 let _t = thread::spawn(move|| {
1348 let _ = TcpStream::connect(&addr);
1350 let _t = thread::spawn(move|| {
1351 let _ = TcpStream::connect(&addr);
1361 let name = if cfg!(windows) {"socket"} else {"fd"};
1362 let socket_addr = next_test_ip4();
1364 let listener = t!(TcpListener::bind(&socket_addr));
1365 let listener_inner = listener.0.socket().as_inner();
1366 let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
1367 socket_addr, name, listener_inner);
1368 assert_eq!(format!("{:?}", listener), compare);
1370 let stream = t!(TcpStream::connect(&("localhost",
1371 socket_addr.port())));
1372 let stream_inner = stream.0.socket().as_inner();
1373 let compare = format!("TcpStream {{ addr: {:?}, \
1374 peer: {:?}, {}: {:?} }}",
1375 stream.local_addr().unwrap(),
1376 stream.peer_addr().unwrap(),
1379 assert_eq!(format!("{:?}", stream), compare);
1382 // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
1383 // no longer has rounding errors.
1384 #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1387 let addr = next_test_ip4();
1388 let listener = t!(TcpListener::bind(&addr));
1390 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1391 let dur = Duration::new(15410, 0);
1393 assert_eq!(None, t!(stream.read_timeout()));
1395 t!(stream.set_read_timeout(Some(dur)));
1396 assert_eq!(Some(dur), t!(stream.read_timeout()));
1398 assert_eq!(None, t!(stream.write_timeout()));
1400 t!(stream.set_write_timeout(Some(dur)));
1401 assert_eq!(Some(dur), t!(stream.write_timeout()));
1403 t!(stream.set_read_timeout(None));
1404 assert_eq!(None, t!(stream.read_timeout()));
1406 t!(stream.set_write_timeout(None));
1407 assert_eq!(None, t!(stream.write_timeout()));
1412 fn test_read_timeout() {
1413 let addr = next_test_ip4();
1414 let listener = t!(TcpListener::bind(&addr));
1416 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1417 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1419 let mut buf = [0; 10];
1420 let start = Instant::now();
1421 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1422 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1423 assert!(start.elapsed() > Duration::from_millis(400));
1428 fn test_read_with_timeout() {
1429 let addr = next_test_ip4();
1430 let listener = t!(TcpListener::bind(&addr));
1432 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1433 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1435 let mut other_end = t!(listener.accept()).0;
1436 t!(other_end.write_all(b"hello world"));
1438 let mut buf = [0; 11];
1439 t!(stream.read(&mut buf));
1440 assert_eq!(b"hello world", &buf[..]);
1442 let start = Instant::now();
1443 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1444 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1445 assert!(start.elapsed() > Duration::from_millis(400));
1451 let addr = next_test_ip4();
1452 let _listener = t!(TcpListener::bind(&addr));
1454 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1456 assert_eq!(false, t!(stream.nodelay()));
1457 t!(stream.set_nodelay(true));
1458 assert_eq!(true, t!(stream.nodelay()));
1459 t!(stream.set_nodelay(false));
1460 assert_eq!(false, t!(stream.nodelay()));
1467 let addr = next_test_ip4();
1468 let listener = t!(TcpListener::bind(&addr));
1470 t!(listener.set_ttl(ttl));
1471 assert_eq!(ttl, t!(listener.ttl()));
1473 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1475 t!(stream.set_ttl(ttl));
1476 assert_eq!(ttl, t!(stream.ttl()));
1480 fn set_nonblocking() {
1481 let addr = next_test_ip4();
1482 let listener = t!(TcpListener::bind(&addr));
1484 t!(listener.set_nonblocking(true));
1485 t!(listener.set_nonblocking(false));
1487 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1489 t!(stream.set_nonblocking(false));
1490 t!(stream.set_nonblocking(true));
1493 match stream.read(&mut buf) {
1494 Ok(_) => panic!("expected error"),
1495 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1496 Err(e) => panic!("unexpected error {}", e),
1502 each_ip(&mut |addr| {
1503 let (txdone, rxdone) = channel();
1505 let srv = t!(TcpListener::bind(&addr));
1506 let _t = thread::spawn(move|| {
1507 let mut cl = t!(srv.accept()).0;
1508 cl.write(&[1,3,3,7]).unwrap();
1512 let mut c = t!(TcpStream::connect(&addr));
1513 let mut b = [0; 10];
1515 let len = c.peek(&mut b).unwrap();
1518 let len = c.read(&mut b).unwrap();
1521 t!(c.set_nonblocking(true));
1522 match c.peek(&mut b) {
1523 Ok(_) => panic!("expected error"),
1524 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1525 Err(e) => panic!("unexpected error {}", e),
1527 t!(txdone.send(()));
1532 fn connect_timeout_unroutable() {
1533 // this IP is unroutable, so connections should always time out.
1534 let addr = "10.255.255.1:80".parse().unwrap();
1535 let e = TcpStream::connect_timeout(&addr, Duration::from_millis(250)).unwrap_err();
1536 assert_eq!(e.kind(), io::ErrorKind::TimedOut);
1540 fn connect_timeout_valid() {
1541 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1542 let addr = listener.local_addr().unwrap();
1543 TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();