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.
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
76 /// use std::net::{TcpListener, TcpStream};
78 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
80 /// fn handle_client(stream: TcpStream) {
84 /// // accept connections and process them serially
85 /// for stream in listener.incoming() {
88 /// handle_client(stream);
90 /// Err(e) => { /* connection failed */ }
94 #[stable(feature = "rust1", since = "1.0.0")]
95 pub struct TcpListener(net_imp::TcpListener);
97 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
99 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
100 /// See its documentation for more.
102 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
103 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
104 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
105 #[stable(feature = "rust1", since = "1.0.0")]
107 pub struct Incoming<'a> { listener: &'a TcpListener }
110 /// Opens a TCP connection to a remote host.
112 /// `addr` is an address of the remote host. Anything which implements
113 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
114 /// documentation for concrete examples.
115 /// In case [`ToSocketAddrs::to_socket_addrs()`] returns more than one entry,
116 /// then the first valid and reachable address is used.
118 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
119 /// [`ToSocketAddrs::to_socket_addrs()`]:
120 /// ../../std/net/trait.ToSocketAddrs.html#tymethod.to_socket_addrs
125 /// use std::net::TcpStream;
127 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
128 /// println!("Connected to the server!");
130 /// println!("Couldn't connect to server...");
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
135 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
138 /// Returns the socket address of the remote peer of this TCP connection.
143 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
145 /// let stream = TcpStream::connect("127.0.0.1:8080")
146 /// .expect("Couldn't connect to the server...");
147 /// assert_eq!(stream.peer_addr().unwrap(),
148 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
150 #[stable(feature = "rust1", since = "1.0.0")]
151 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
155 /// Returns the socket address of the local half 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.local_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 local_addr(&self) -> io::Result<SocketAddr> {
172 /// Shuts down the read, write, or both halves of this connection.
174 /// This function will cause all pending and future I/O on the specified
175 /// portions to return immediately with an appropriate value (see the
176 /// documentation of [`Shutdown`]).
178 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
183 /// use std::net::{Shutdown, TcpStream};
185 /// let stream = TcpStream::connect("127.0.0.1:8080")
186 /// .expect("Couldn't connect to the server...");
187 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
189 #[stable(feature = "rust1", since = "1.0.0")]
190 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
194 /// Creates a new independently owned handle to the underlying socket.
196 /// The returned `TcpStream` is a reference to the same stream that this
197 /// object references. Both handles will read and write the same stream of
198 /// data, and options set on one stream will be propagated to the other
204 /// use std::net::TcpStream;
206 /// let stream = TcpStream::connect("127.0.0.1:8080")
207 /// .expect("Couldn't connect to the server...");
208 /// let stream_clone = stream.try_clone().expect("clone failed...");
210 #[stable(feature = "rust1", since = "1.0.0")]
211 pub fn try_clone(&self) -> io::Result<TcpStream> {
212 self.0.duplicate().map(TcpStream)
215 /// Sets the read timeout to the timeout specified.
217 /// If the value specified is [`None`], then [`read`] calls will block
218 /// indefinitely. It is an error to pass the zero `Duration` to this
223 /// Platforms may return a different error code whenever a read times out as
224 /// a result of setting this option. For example Unix typically returns an
225 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
227 /// [`None`]: ../../std/option/enum.Option.html#variant.None
228 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
229 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
230 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
235 /// use std::net::TcpStream;
237 /// let stream = TcpStream::connect("127.0.0.1:8080")
238 /// .expect("Couldn't connect to the server...");
239 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
241 #[stable(feature = "socket_timeout", since = "1.4.0")]
242 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
243 self.0.set_read_timeout(dur)
246 /// Sets the write timeout to the timeout specified.
248 /// If the value specified is [`None`], then [`write`] calls will block
249 /// indefinitely. It is an error to pass the zero [`Duration`] to this
254 /// Platforms may return a different error code whenever a write times out
255 /// as a result of setting this option. For example Unix typically returns
256 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
258 /// [`None`]: ../../std/option/enum.Option.html#variant.None
259 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
260 /// [`Duration`]: ../../std/time/struct.Duration.html
261 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
262 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
267 /// use std::net::TcpStream;
269 /// let stream = TcpStream::connect("127.0.0.1:8080")
270 /// .expect("Couldn't connect to the server...");
271 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
273 #[stable(feature = "socket_timeout", since = "1.4.0")]
274 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
275 self.0.set_write_timeout(dur)
278 /// Returns the read timeout of this socket.
280 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
284 /// Some platforms do not provide access to the current timeout.
286 /// [`None`]: ../../std/option/enum.Option.html#variant.None
287 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
292 /// use std::net::TcpStream;
294 /// let stream = TcpStream::connect("127.0.0.1:8080")
295 /// .expect("Couldn't connect to the server...");
296 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
297 /// assert_eq!(stream.read_timeout().unwrap(), None);
299 #[stable(feature = "socket_timeout", since = "1.4.0")]
300 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
301 self.0.read_timeout()
304 /// Returns the write timeout of this socket.
306 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
310 /// Some platforms do not provide access to the current timeout.
312 /// [`None`]: ../../std/option/enum.Option.html#variant.None
313 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
318 /// use std::net::TcpStream;
320 /// let stream = TcpStream::connect("127.0.0.1:8080")
321 /// .expect("Couldn't connect to the server...");
322 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
323 /// assert_eq!(stream.write_timeout().unwrap(), None);
325 #[stable(feature = "socket_timeout", since = "1.4.0")]
326 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
327 self.0.write_timeout()
330 /// Receives data on the socket from the remote adress to which it is
331 /// connected, without removing that data from the queue. On success,
332 /// returns the number of bytes peeked.
334 /// Successive calls return the same data. This is accomplished by passing
335 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
340 /// #![feature(peek)]
341 /// use std::net::TcpStream;
343 /// let stream = TcpStream::connect("127.0.0.1:8000")
344 /// .expect("couldn't bind to address");
345 /// let mut buf = [0; 10];
346 /// let len = stream.peek(&mut buf).expect("peek failed");
348 #[unstable(feature = "peek", issue = "38980")]
349 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
353 /// Sets the value of the `TCP_NODELAY` option on this socket.
355 /// If set, this option disables the Nagle algorithm. This means that
356 /// segments are always sent as soon as possible, even if there is only a
357 /// small amount of data. When not set, data is buffered until there is a
358 /// sufficient amount to send out, thereby avoiding the frequent sending of
364 /// use std::net::TcpStream;
366 /// let stream = TcpStream::connect("127.0.0.1:8080")
367 /// .expect("Couldn't connect to the server...");
368 /// stream.set_nodelay(true).expect("set_nodelay call failed");
370 #[stable(feature = "net2_mutators", since = "1.9.0")]
371 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
372 self.0.set_nodelay(nodelay)
375 /// Gets the value of the `TCP_NODELAY` option on this socket.
377 /// For more information about this option, see [`set_nodelay`][link].
379 /// [link]: #method.set_nodelay
384 /// use std::net::TcpStream;
386 /// let stream = TcpStream::connect("127.0.0.1:8080")
387 /// .expect("Couldn't connect to the server...");
388 /// stream.set_nodelay(true).expect("set_nodelay call failed");
389 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
391 #[stable(feature = "net2_mutators", since = "1.9.0")]
392 pub fn nodelay(&self) -> io::Result<bool> {
396 /// Sets the value for the `IP_TTL` option on this socket.
398 /// This value sets the time-to-live field that is used in every packet sent
399 /// from this socket.
404 /// use std::net::TcpStream;
406 /// let stream = TcpStream::connect("127.0.0.1:8080")
407 /// .expect("Couldn't connect to the server...");
408 /// stream.set_ttl(100).expect("set_ttl call failed");
410 #[stable(feature = "net2_mutators", since = "1.9.0")]
411 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
415 /// Gets the value of the `IP_TTL` option for this socket.
417 /// For more information about this option, see [`set_ttl`][link].
419 /// [link]: #method.set_ttl
424 /// use std::net::TcpStream;
426 /// let stream = TcpStream::connect("127.0.0.1:8080")
427 /// .expect("Couldn't connect to the server...");
428 /// stream.set_ttl(100).expect("set_ttl call failed");
429 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
431 #[stable(feature = "net2_mutators", since = "1.9.0")]
432 pub fn ttl(&self) -> io::Result<u32> {
436 /// Get the value of the `SO_ERROR` option on this socket.
438 /// This will retrieve the stored error in the underlying socket, clearing
439 /// the field in the process. This can be useful for checking errors between
445 /// use std::net::TcpStream;
447 /// let stream = TcpStream::connect("127.0.0.1:8080")
448 /// .expect("Couldn't connect to the server...");
449 /// stream.take_error().expect("No error was expected...");
451 #[stable(feature = "net2_mutators", since = "1.9.0")]
452 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
456 /// Moves this TCP stream into or out of nonblocking mode.
458 /// On Unix this corresponds to calling fcntl, and on Windows this
459 /// corresponds to calling ioctlsocket.
464 /// use std::net::TcpStream;
466 /// let stream = TcpStream::connect("127.0.0.1:8080")
467 /// .expect("Couldn't connect to the server...");
468 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
470 #[stable(feature = "net2_mutators", since = "1.9.0")]
471 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
472 self.0.set_nonblocking(nonblocking)
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl Read for TcpStream {
478 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
479 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
480 self.0.read_to_end(buf)
483 #[stable(feature = "rust1", since = "1.0.0")]
484 impl Write for TcpStream {
485 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
486 fn flush(&mut self) -> io::Result<()> { Ok(()) }
488 #[stable(feature = "rust1", since = "1.0.0")]
489 impl<'a> Read for &'a TcpStream {
490 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
491 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
492 self.0.read_to_end(buf)
495 #[stable(feature = "rust1", since = "1.0.0")]
496 impl<'a> Write for &'a TcpStream {
497 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
498 fn flush(&mut self) -> io::Result<()> { Ok(()) }
501 impl AsInner<net_imp::TcpStream> for TcpStream {
502 fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
505 impl FromInner<net_imp::TcpStream> for TcpStream {
506 fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
509 impl IntoInner<net_imp::TcpStream> for TcpStream {
510 fn into_inner(self) -> net_imp::TcpStream { self.0 }
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl fmt::Debug for TcpStream {
515 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
521 /// Creates a new `TcpListener` which will be bound to the specified
524 /// The returned listener is ready for accepting connections.
526 /// Binding with a port number of 0 will request that the OS assigns a port
527 /// to this listener. The port allocated can be queried via the
528 /// [`local_addr`] method.
530 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
531 /// its documentation for concrete examples.
533 /// [`local_addr`]: #method.local_addr
534 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
539 /// use std::net::TcpListener;
541 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
543 #[stable(feature = "rust1", since = "1.0.0")]
544 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
545 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
548 /// Returns the local socket address of this listener.
553 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
555 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
556 /// assert_eq!(listener.local_addr().unwrap(),
557 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
559 #[stable(feature = "rust1", since = "1.0.0")]
560 pub fn local_addr(&self) -> io::Result<SocketAddr> {
564 /// Creates a new independently owned handle to the underlying socket.
566 /// The returned [`TcpListener`] is a reference to the same socket that this
567 /// object references. Both handles can be used to accept incoming
568 /// connections and options set on one listener will affect the other.
570 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
575 /// use std::net::TcpListener;
577 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
578 /// let listener_clone = listener.try_clone().unwrap();
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn try_clone(&self) -> io::Result<TcpListener> {
582 self.0.duplicate().map(TcpListener)
585 /// Accept a new incoming connection from this listener.
587 /// This function will block the calling thread until a new TCP connection
588 /// is established. When established, the corresponding [`TcpStream`] and the
589 /// remote peer's address will be returned.
591 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
596 /// use std::net::TcpListener;
598 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
599 /// match listener.accept() {
600 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
601 /// Err(e) => println!("couldn't get client: {:?}", e),
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
606 self.0.accept().map(|(a, b)| (TcpStream(a), b))
609 /// Returns an iterator over the connections being received on this
612 /// The returned iterator will never return [`None`] and will also not yield
613 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
614 /// calling [`accept`] in a loop.
616 /// [`None`]: ../../std/option/enum.Option.html#variant.None
617 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
618 /// [`accept`]: #method.accept
623 /// use std::net::TcpListener;
625 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
627 /// for stream in listener.incoming() {
630 /// println!("new client!");
632 /// Err(e) => { /* connection failed */ }
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn incoming(&self) -> Incoming {
638 Incoming { listener: self }
641 /// Sets the value for the `IP_TTL` option on this socket.
643 /// This value sets the time-to-live field that is used in every packet sent
644 /// from this socket.
649 /// use std::net::TcpListener;
651 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
652 /// listener.set_ttl(100).expect("could not set TTL");
654 #[stable(feature = "net2_mutators", since = "1.9.0")]
655 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
659 /// Gets the value of the `IP_TTL` option for this socket.
661 /// For more information about this option, see [`set_ttl`][link].
663 /// [link]: #method.set_ttl
668 /// use std::net::TcpListener;
670 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
671 /// listener.set_ttl(100).expect("could not set TTL");
672 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
674 #[stable(feature = "net2_mutators", since = "1.9.0")]
675 pub fn ttl(&self) -> io::Result<u32> {
679 #[stable(feature = "net2_mutators", since = "1.9.0")]
680 #[rustc_deprecated(since = "1.16.0",
681 reason = "this option can only be set before the socket is bound")]
682 #[allow(missing_docs)]
683 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
684 self.0.set_only_v6(only_v6)
687 #[stable(feature = "net2_mutators", since = "1.9.0")]
688 #[rustc_deprecated(since = "1.16.0",
689 reason = "this option can only be set before the socket is bound")]
690 #[allow(missing_docs)]
691 pub fn only_v6(&self) -> io::Result<bool> {
695 /// Get the value of the `SO_ERROR` option on this socket.
697 /// This will retrieve the stored error in the underlying socket, clearing
698 /// the field in the process. This can be useful for checking errors between
704 /// use std::net::TcpListener;
706 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
707 /// listener.take_error().expect("No error was expected");
709 #[stable(feature = "net2_mutators", since = "1.9.0")]
710 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
714 /// Moves this TCP stream into or out of nonblocking mode.
716 /// On Unix this corresponds to calling fcntl, and on Windows this
717 /// corresponds to calling ioctlsocket.
722 /// use std::net::TcpListener;
724 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
725 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
727 #[stable(feature = "net2_mutators", since = "1.9.0")]
728 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
729 self.0.set_nonblocking(nonblocking)
733 #[stable(feature = "rust1", since = "1.0.0")]
734 impl<'a> Iterator for Incoming<'a> {
735 type Item = io::Result<TcpStream>;
736 fn next(&mut self) -> Option<io::Result<TcpStream>> {
737 Some(self.listener.accept().map(|p| p.0))
741 impl AsInner<net_imp::TcpListener> for TcpListener {
742 fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
745 impl FromInner<net_imp::TcpListener> for TcpListener {
746 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
751 impl IntoInner<net_imp::TcpListener> for TcpListener {
752 fn into_inner(self) -> net_imp::TcpListener { self.0 }
755 #[stable(feature = "rust1", since = "1.0.0")]
756 impl fmt::Debug for TcpListener {
757 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
762 #[cfg(all(test, not(target_os = "emscripten")))]
767 use net::test::{next_test_ip4, next_test_ip6};
768 use sync::mpsc::channel;
769 use sys_common::AsInner;
770 use time::{Instant, Duration};
773 fn each_ip(f: &mut FnMut(SocketAddr)) {
782 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
789 match TcpListener::bind("1.1.1.1:9999") {
792 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
798 match TcpStream::connect("0.0.0.0:1") {
800 Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
801 e.kind() == ErrorKind::InvalidInput ||
802 e.kind() == ErrorKind::AddrInUse ||
803 e.kind() == ErrorKind::AddrNotAvailable,
804 "bad error: {} {:?}", e, e.kind()),
809 fn listen_localhost() {
810 let socket_addr = next_test_ip4();
811 let listener = t!(TcpListener::bind(&socket_addr));
813 let _t = thread::spawn(move || {
814 let mut stream = t!(TcpStream::connect(&("localhost",
815 socket_addr.port())));
816 t!(stream.write(&[144]));
819 let mut stream = t!(listener.accept()).0;
821 t!(stream.read(&mut buf));
822 assert!(buf[0] == 144);
826 fn connect_loopback() {
827 each_ip(&mut |addr| {
828 let acceptor = t!(TcpListener::bind(&addr));
830 let _t = thread::spawn(move|| {
831 let host = match addr {
832 SocketAddr::V4(..) => "127.0.0.1",
833 SocketAddr::V6(..) => "::1",
835 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
836 t!(stream.write(&[66]));
839 let mut stream = t!(acceptor.accept()).0;
841 t!(stream.read(&mut buf));
842 assert!(buf[0] == 66);
848 each_ip(&mut |addr| {
849 let acceptor = t!(TcpListener::bind(&addr));
851 let (tx, rx) = channel();
852 let _t = thread::spawn(move|| {
853 let mut stream = t!(TcpStream::connect(&addr));
854 t!(stream.write(&[99]));
855 tx.send(t!(stream.local_addr())).unwrap();
858 let (mut stream, addr) = t!(acceptor.accept());
860 t!(stream.read(&mut buf));
861 assert!(buf[0] == 99);
862 assert_eq!(addr, t!(rx.recv()));
868 each_ip(&mut |addr| {
869 let acceptor = t!(TcpListener::bind(&addr));
871 let _t = thread::spawn(move|| {
872 let _stream = t!(TcpStream::connect(&addr));
876 let mut stream = t!(acceptor.accept()).0;
878 let nread = t!(stream.read(&mut buf));
879 assert_eq!(nread, 0);
880 let nread = t!(stream.read(&mut buf));
881 assert_eq!(nread, 0);
887 each_ip(&mut |addr| {
888 let acceptor = t!(TcpListener::bind(&addr));
890 let (tx, rx) = channel();
891 let _t = thread::spawn(move|| {
892 drop(t!(TcpStream::connect(&addr)));
893 tx.send(()).unwrap();
896 let mut stream = t!(acceptor.accept()).0;
899 match stream.write(&buf) {
902 assert!(e.kind() == ErrorKind::ConnectionReset ||
903 e.kind() == ErrorKind::BrokenPipe ||
904 e.kind() == ErrorKind::ConnectionAborted,
905 "unknown error: {}", e);
912 fn multiple_connect_serial() {
913 each_ip(&mut |addr| {
915 let acceptor = t!(TcpListener::bind(&addr));
917 let _t = thread::spawn(move|| {
919 let mut stream = t!(TcpStream::connect(&addr));
920 t!(stream.write(&[99]));
924 for stream in acceptor.incoming().take(max) {
925 let mut stream = t!(stream);
927 t!(stream.read(&mut buf));
928 assert_eq!(buf[0], 99);
934 fn multiple_connect_interleaved_greedy_schedule() {
935 const MAX: usize = 10;
936 each_ip(&mut |addr| {
937 let acceptor = t!(TcpListener::bind(&addr));
939 let _t = thread::spawn(move|| {
940 let acceptor = acceptor;
941 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
942 // Start another thread to handle the connection
943 let _t = thread::spawn(move|| {
944 let mut stream = t!(stream);
946 t!(stream.read(&mut buf));
947 assert!(buf[0] == i as u8);
955 fn connect(i: usize, addr: SocketAddr) {
956 if i == MAX { return }
958 let t = thread::spawn(move|| {
959 let mut stream = t!(TcpStream::connect(&addr));
960 // Connect again before writing
961 connect(i + 1, addr);
962 t!(stream.write(&[i as u8]));
964 t.join().ok().unwrap();
969 fn multiple_connect_interleaved_lazy_schedule() {
970 const MAX: usize = 10;
971 each_ip(&mut |addr| {
972 let acceptor = t!(TcpListener::bind(&addr));
974 let _t = thread::spawn(move|| {
975 for stream in acceptor.incoming().take(MAX) {
976 // Start another thread to handle the connection
977 let _t = thread::spawn(move|| {
978 let mut stream = t!(stream);
980 t!(stream.read(&mut buf));
981 assert!(buf[0] == 99);
989 fn connect(i: usize, addr: SocketAddr) {
990 if i == MAX { return }
992 let t = thread::spawn(move|| {
993 let mut stream = t!(TcpStream::connect(&addr));
994 connect(i + 1, addr);
995 t!(stream.write(&[99]));
997 t.join().ok().unwrap();
1002 fn socket_and_peer_name() {
1003 each_ip(&mut |addr| {
1004 let listener = t!(TcpListener::bind(&addr));
1005 let so_name = t!(listener.local_addr());
1006 assert_eq!(addr, so_name);
1007 let _t = thread::spawn(move|| {
1008 t!(listener.accept());
1011 let stream = t!(TcpStream::connect(&addr));
1012 assert_eq!(addr, t!(stream.peer_addr()));
1018 each_ip(&mut |addr| {
1019 let (tx, rx) = channel();
1020 let srv = t!(TcpListener::bind(&addr));
1021 let _t = thread::spawn(move|| {
1022 let mut cl = t!(srv.accept()).0;
1023 cl.write(&[10]).unwrap();
1025 t!(cl.read(&mut b));
1026 tx.send(()).unwrap();
1029 let mut c = t!(TcpStream::connect(&addr));
1030 let mut b = [0; 10];
1031 assert_eq!(c.read(&mut b).unwrap(), 1);
1039 each_ip(&mut |addr| {
1040 let _listener = t!(TcpListener::bind(&addr));
1041 match TcpListener::bind(&addr) {
1044 assert!(e.kind() == ErrorKind::ConnectionRefused ||
1045 e.kind() == ErrorKind::Other ||
1046 e.kind() == ErrorKind::AddrInUse,
1047 "unknown error: {} {:?}", e, e.kind());
1055 each_ip(&mut |addr| {
1056 let acceptor = t!(TcpListener::bind(&addr));
1058 let _t = thread::spawn(move|| {
1059 t!(TcpStream::connect(&addr));
1062 t!(acceptor.accept());
1064 t!(TcpListener::bind(&addr));
1069 fn tcp_clone_smoke() {
1070 each_ip(&mut |addr| {
1071 let acceptor = t!(TcpListener::bind(&addr));
1073 let _t = thread::spawn(move|| {
1074 let mut s = t!(TcpStream::connect(&addr));
1075 let mut buf = [0, 0];
1076 assert_eq!(s.read(&mut buf).unwrap(), 1);
1077 assert_eq!(buf[0], 1);
1081 let mut s1 = t!(acceptor.accept()).0;
1082 let s2 = t!(s1.try_clone());
1084 let (tx1, rx1) = channel();
1085 let (tx2, rx2) = channel();
1086 let _t = thread::spawn(move|| {
1088 rx1.recv().unwrap();
1090 tx2.send(()).unwrap();
1092 tx1.send(()).unwrap();
1093 let mut buf = [0, 0];
1094 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1095 rx2.recv().unwrap();
1100 fn tcp_clone_two_read() {
1101 each_ip(&mut |addr| {
1102 let acceptor = t!(TcpListener::bind(&addr));
1103 let (tx1, rx) = channel();
1104 let tx2 = tx1.clone();
1106 let _t = thread::spawn(move|| {
1107 let mut s = t!(TcpStream::connect(&addr));
1114 let mut s1 = t!(acceptor.accept()).0;
1115 let s2 = t!(s1.try_clone());
1117 let (done, rx) = channel();
1118 let _t = thread::spawn(move|| {
1120 let mut buf = [0, 0];
1121 t!(s2.read(&mut buf));
1122 tx2.send(()).unwrap();
1123 done.send(()).unwrap();
1125 let mut buf = [0, 0];
1126 t!(s1.read(&mut buf));
1127 tx1.send(()).unwrap();
1134 fn tcp_clone_two_write() {
1135 each_ip(&mut |addr| {
1136 let acceptor = t!(TcpListener::bind(&addr));
1138 let _t = thread::spawn(move|| {
1139 let mut s = t!(TcpStream::connect(&addr));
1140 let mut buf = [0, 1];
1141 t!(s.read(&mut buf));
1142 t!(s.read(&mut buf));
1145 let mut s1 = t!(acceptor.accept()).0;
1146 let s2 = t!(s1.try_clone());
1148 let (done, rx) = channel();
1149 let _t = thread::spawn(move|| {
1152 done.send(()).unwrap();
1161 fn shutdown_smoke() {
1162 each_ip(&mut |addr| {
1163 let a = t!(TcpListener::bind(&addr));
1164 let _t = thread::spawn(move|| {
1165 let mut c = t!(a.accept()).0;
1167 assert_eq!(c.read(&mut b).unwrap(), 0);
1171 let mut s = t!(TcpStream::connect(&addr));
1172 t!(s.shutdown(Shutdown::Write));
1173 assert!(s.write(&[1]).is_err());
1175 assert_eq!(t!(s.read(&mut b)), 1);
1176 assert_eq!(b[0], 1);
1181 fn close_readwrite_smoke() {
1182 each_ip(&mut |addr| {
1183 let a = t!(TcpListener::bind(&addr));
1184 let (tx, rx) = channel::<()>();
1185 let _t = thread::spawn(move|| {
1186 let _s = t!(a.accept());
1191 let mut s = t!(TcpStream::connect(&addr));
1192 let mut s2 = t!(s.try_clone());
1194 // closing should prevent reads/writes
1195 t!(s.shutdown(Shutdown::Write));
1196 assert!(s.write(&[0]).is_err());
1197 t!(s.shutdown(Shutdown::Read));
1198 assert_eq!(s.read(&mut b).unwrap(), 0);
1200 // closing should affect previous handles
1201 assert!(s2.write(&[0]).is_err());
1202 assert_eq!(s2.read(&mut b).unwrap(), 0);
1204 // closing should affect new handles
1205 let mut s3 = t!(s.try_clone());
1206 assert!(s3.write(&[0]).is_err());
1207 assert_eq!(s3.read(&mut b).unwrap(), 0);
1209 // make sure these don't die
1210 let _ = s2.shutdown(Shutdown::Read);
1211 let _ = s2.shutdown(Shutdown::Write);
1212 let _ = s3.shutdown(Shutdown::Read);
1213 let _ = s3.shutdown(Shutdown::Write);
1219 #[cfg(unix)] // test doesn't work on Windows, see #31657
1220 fn close_read_wakes_up() {
1221 each_ip(&mut |addr| {
1222 let a = t!(TcpListener::bind(&addr));
1223 let (tx1, rx) = channel::<()>();
1224 let _t = thread::spawn(move|| {
1225 let _s = t!(a.accept());
1229 let s = t!(TcpStream::connect(&addr));
1230 let s2 = t!(s.try_clone());
1231 let (tx, rx) = channel();
1232 let _t = thread::spawn(move|| {
1234 assert_eq!(t!(s2.read(&mut [0])), 0);
1235 tx.send(()).unwrap();
1237 // this should wake up the child thread
1238 t!(s.shutdown(Shutdown::Read));
1240 // this test will never finish if the child doesn't wake up
1247 fn clone_while_reading() {
1248 each_ip(&mut |addr| {
1249 let accept = t!(TcpListener::bind(&addr));
1251 // Enqueue a thread to write to a socket
1252 let (tx, rx) = channel();
1253 let (txdone, rxdone) = channel();
1254 let txdone2 = txdone.clone();
1255 let _t = thread::spawn(move|| {
1256 let mut tcp = t!(TcpStream::connect(&addr));
1258 t!(tcp.write(&[0]));
1259 txdone2.send(()).unwrap();
1262 // Spawn off a reading clone
1263 let tcp = t!(accept.accept()).0;
1264 let tcp2 = t!(tcp.try_clone());
1265 let txdone3 = txdone.clone();
1266 let _t = thread::spawn(move|| {
1267 let mut tcp2 = tcp2;
1268 t!(tcp2.read(&mut [0]));
1269 txdone3.send(()).unwrap();
1272 // Try to ensure that the reading clone is indeed reading
1274 thread::yield_now();
1277 // clone the handle again while it's reading, then let it finish the
1279 let _ = t!(tcp.try_clone());
1280 tx.send(()).unwrap();
1281 rxdone.recv().unwrap();
1282 rxdone.recv().unwrap();
1287 fn clone_accept_smoke() {
1288 each_ip(&mut |addr| {
1289 let a = t!(TcpListener::bind(&addr));
1290 let a2 = t!(a.try_clone());
1292 let _t = thread::spawn(move|| {
1293 let _ = TcpStream::connect(&addr);
1295 let _t = thread::spawn(move|| {
1296 let _ = TcpStream::connect(&addr);
1305 fn clone_accept_concurrent() {
1306 each_ip(&mut |addr| {
1307 let a = t!(TcpListener::bind(&addr));
1308 let a2 = t!(a.try_clone());
1310 let (tx, rx) = channel();
1311 let tx2 = tx.clone();
1313 let _t = thread::spawn(move|| {
1314 tx.send(t!(a.accept())).unwrap();
1316 let _t = thread::spawn(move|| {
1317 tx2.send(t!(a2.accept())).unwrap();
1320 let _t = thread::spawn(move|| {
1321 let _ = TcpStream::connect(&addr);
1323 let _t = thread::spawn(move|| {
1324 let _ = TcpStream::connect(&addr);
1334 let name = if cfg!(windows) {"socket"} else {"fd"};
1335 let socket_addr = next_test_ip4();
1337 let listener = t!(TcpListener::bind(&socket_addr));
1338 let listener_inner = listener.0.socket().as_inner();
1339 let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
1340 socket_addr, name, listener_inner);
1341 assert_eq!(format!("{:?}", listener), compare);
1343 let stream = t!(TcpStream::connect(&("localhost",
1344 socket_addr.port())));
1345 let stream_inner = stream.0.socket().as_inner();
1346 let compare = format!("TcpStream {{ addr: {:?}, \
1347 peer: {:?}, {}: {:?} }}",
1348 stream.local_addr().unwrap(),
1349 stream.peer_addr().unwrap(),
1352 assert_eq!(format!("{:?}", stream), compare);
1355 // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
1356 // no longer has rounding errors.
1357 #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1360 let addr = next_test_ip4();
1361 let listener = t!(TcpListener::bind(&addr));
1363 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1364 let dur = Duration::new(15410, 0);
1366 assert_eq!(None, t!(stream.read_timeout()));
1368 t!(stream.set_read_timeout(Some(dur)));
1369 assert_eq!(Some(dur), t!(stream.read_timeout()));
1371 assert_eq!(None, t!(stream.write_timeout()));
1373 t!(stream.set_write_timeout(Some(dur)));
1374 assert_eq!(Some(dur), t!(stream.write_timeout()));
1376 t!(stream.set_read_timeout(None));
1377 assert_eq!(None, t!(stream.read_timeout()));
1379 t!(stream.set_write_timeout(None));
1380 assert_eq!(None, t!(stream.write_timeout()));
1385 fn test_read_timeout() {
1386 let addr = next_test_ip4();
1387 let listener = t!(TcpListener::bind(&addr));
1389 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1390 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1392 let mut buf = [0; 10];
1393 let start = Instant::now();
1394 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1395 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1396 assert!(start.elapsed() > Duration::from_millis(400));
1401 fn test_read_with_timeout() {
1402 let addr = next_test_ip4();
1403 let listener = t!(TcpListener::bind(&addr));
1405 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1406 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1408 let mut other_end = t!(listener.accept()).0;
1409 t!(other_end.write_all(b"hello world"));
1411 let mut buf = [0; 11];
1412 t!(stream.read(&mut buf));
1413 assert_eq!(b"hello world", &buf[..]);
1415 let start = Instant::now();
1416 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1417 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1418 assert!(start.elapsed() > Duration::from_millis(400));
1424 let addr = next_test_ip4();
1425 let _listener = t!(TcpListener::bind(&addr));
1427 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1429 assert_eq!(false, t!(stream.nodelay()));
1430 t!(stream.set_nodelay(true));
1431 assert_eq!(true, t!(stream.nodelay()));
1432 t!(stream.set_nodelay(false));
1433 assert_eq!(false, t!(stream.nodelay()));
1440 let addr = next_test_ip4();
1441 let listener = t!(TcpListener::bind(&addr));
1443 t!(listener.set_ttl(ttl));
1444 assert_eq!(ttl, t!(listener.ttl()));
1446 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1448 t!(stream.set_ttl(ttl));
1449 assert_eq!(ttl, t!(stream.ttl()));
1453 fn set_nonblocking() {
1454 let addr = next_test_ip4();
1455 let listener = t!(TcpListener::bind(&addr));
1457 t!(listener.set_nonblocking(true));
1458 t!(listener.set_nonblocking(false));
1460 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1462 t!(stream.set_nonblocking(false));
1463 t!(stream.set_nonblocking(true));
1466 match stream.read(&mut buf) {
1467 Ok(_) => panic!("expected error"),
1468 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1469 Err(e) => panic!("unexpected error {}", e),
1475 each_ip(&mut |addr| {
1476 let (txdone, rxdone) = channel();
1478 let srv = t!(TcpListener::bind(&addr));
1479 let _t = thread::spawn(move|| {
1480 let mut cl = t!(srv.accept()).0;
1481 cl.write(&[1,3,3,7]).unwrap();
1485 let mut c = t!(TcpStream::connect(&addr));
1486 let mut b = [0; 10];
1488 let len = c.peek(&mut b).unwrap();
1491 let len = c.read(&mut b).unwrap();
1494 t!(c.set_nonblocking(true));
1495 match c.peek(&mut b) {
1496 Ok(_) => panic!("expected error"),
1497 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1498 Err(e) => panic!("unexpected error {}", e),
1500 t!(txdone.send(()));