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 structure which represents a TCP stream between a local socket and a
23 /// The socket will be closed when the value is dropped.
28 /// use std::io::prelude::*;
29 /// use std::net::TcpStream;
32 /// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
34 /// // ignore the Result
35 /// let _ = stream.write(&[1]);
36 /// let _ = stream.read(&mut [0; 128]); // ignore here too
37 /// } // the stream is closed here
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub struct TcpStream(net_imp::TcpStream);
42 /// A structure representing a socket server.
47 /// use std::net::{TcpListener, TcpStream};
49 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
51 /// fn handle_client(stream: TcpStream) {
55 /// // accept connections and process them serially
56 /// for stream in listener.incoming() {
59 /// handle_client(stream);
61 /// Err(e) => { /* connection failed */ }
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub struct TcpListener(net_imp::TcpListener);
68 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
70 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
71 /// See its documentation for more.
73 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
74 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
75 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
76 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct Incoming<'a> { listener: &'a TcpListener }
81 /// Opens a TCP connection to a remote host.
83 /// `addr` is an address of the remote host. Anything which implements
84 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
85 /// documentation for concrete examples.
86 /// In case [`ToSocketAddrs::to_socket_addrs()`] returns more than one entry,
87 /// then the first valid and reachable address is used.
89 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
90 /// [`ToSocketAddrs::to_socket_addrs()`]:
91 /// ../../std/net/trait.ToSocketAddrs.html#tymethod.to_socket_addrs
96 /// use std::net::TcpStream;
98 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
99 /// println!("Connected to the server!");
101 /// println!("Couldn't connect to server...");
104 #[stable(feature = "rust1", since = "1.0.0")]
105 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
106 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
109 /// Returns the socket address of the remote peer of this TCP connection.
114 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
116 /// let stream = TcpStream::connect("127.0.0.1:8080")
117 /// .expect("Couldn't connect to the server...");
118 /// assert_eq!(stream.peer_addr().unwrap(),
119 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
121 #[stable(feature = "rust1", since = "1.0.0")]
122 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
126 /// Returns the socket address of the local half of this TCP connection.
131 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
133 /// let stream = TcpStream::connect("127.0.0.1:8080")
134 /// .expect("Couldn't connect to the server...");
135 /// assert_eq!(stream.local_addr().unwrap(),
136 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
138 #[stable(feature = "rust1", since = "1.0.0")]
139 pub fn local_addr(&self) -> io::Result<SocketAddr> {
143 /// Shuts down the read, write, or both halves of this connection.
145 /// This function will cause all pending and future I/O on the specified
146 /// portions to return immediately with an appropriate value (see the
147 /// documentation of [`Shutdown`]).
149 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
154 /// use std::net::{Shutdown, TcpStream};
156 /// let stream = TcpStream::connect("127.0.0.1:8080")
157 /// .expect("Couldn't connect to the server...");
158 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
160 #[stable(feature = "rust1", since = "1.0.0")]
161 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
165 /// Creates a new independently owned handle to the underlying socket.
167 /// The returned `TcpStream` is a reference to the same stream that this
168 /// object references. Both handles will read and write the same stream of
169 /// data, and options set on one stream will be propagated to the other
175 /// use std::net::TcpStream;
177 /// let stream = TcpStream::connect("127.0.0.1:8080")
178 /// .expect("Couldn't connect to the server...");
179 /// let stream_clone = stream.try_clone().expect("clone failed...");
181 #[stable(feature = "rust1", since = "1.0.0")]
182 pub fn try_clone(&self) -> io::Result<TcpStream> {
183 self.0.duplicate().map(TcpStream)
186 /// Sets the read timeout to the timeout specified.
188 /// If the value specified is [`None`], then [`read`] calls will block
189 /// indefinitely. It is an error to pass the zero `Duration` to this
194 /// Platforms may return a different error code whenever a read times out as
195 /// a result of setting this option. For example Unix typically returns an
196 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
198 /// [`None`]: ../../std/option/enum.Option.html#variant.None
199 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
200 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
201 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
206 /// use std::net::TcpStream;
208 /// let stream = TcpStream::connect("127.0.0.1:8080")
209 /// .expect("Couldn't connect to the server...");
210 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
212 #[stable(feature = "socket_timeout", since = "1.4.0")]
213 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
214 self.0.set_read_timeout(dur)
217 /// Sets the write timeout to the timeout specified.
219 /// If the value specified is [`None`], then [`write`] calls will block
220 /// indefinitely. It is an error to pass the zero [`Duration`] to this
225 /// Platforms may return a different error code whenever a write times out
226 /// as a result of setting this option. For example Unix typically returns
227 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
229 /// [`None`]: ../../std/option/enum.Option.html#variant.None
230 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
231 /// [`Duration`]: ../../std/time/struct.Duration.html
232 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
233 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
238 /// use std::net::TcpStream;
240 /// let stream = TcpStream::connect("127.0.0.1:8080")
241 /// .expect("Couldn't connect to the server...");
242 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
244 #[stable(feature = "socket_timeout", since = "1.4.0")]
245 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
246 self.0.set_write_timeout(dur)
249 /// Returns the read timeout of this socket.
251 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
255 /// Some platforms do not provide access to the current timeout.
257 /// [`None`]: ../../std/option/enum.Option.html#variant.None
258 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
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");
268 /// assert_eq!(stream.read_timeout().unwrap(), None);
270 #[stable(feature = "socket_timeout", since = "1.4.0")]
271 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
272 self.0.read_timeout()
275 /// Returns the write timeout of this socket.
277 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
281 /// Some platforms do not provide access to the current timeout.
283 /// [`None`]: ../../std/option/enum.Option.html#variant.None
284 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
289 /// use std::net::TcpStream;
291 /// let stream = TcpStream::connect("127.0.0.1:8080")
292 /// .expect("Couldn't connect to the server...");
293 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
294 /// assert_eq!(stream.write_timeout().unwrap(), None);
296 #[stable(feature = "socket_timeout", since = "1.4.0")]
297 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
298 self.0.write_timeout()
301 /// Receives data on the socket from the remote adress to which it is
302 /// connected, without removing that data from the queue. On success,
303 /// returns the number of bytes peeked.
305 /// Successive calls return the same data. This is accomplished by passing
306 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
311 /// #![feature(peek)]
312 /// use std::net::TcpStream;
314 /// let stream = TcpStream::connect("127.0.0.1:8000")
315 /// .expect("couldn't bind to address");
316 /// let mut buf = [0; 10];
317 /// let len = stream.peek(&mut buf).expect("peek failed");
319 #[unstable(feature = "peek", issue = "38980")]
320 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
324 /// Sets the value of the `TCP_NODELAY` option on this socket.
326 /// If set, this option disables the Nagle algorithm. This means that
327 /// segments are always sent as soon as possible, even if there is only a
328 /// small amount of data. When not set, data is buffered until there is a
329 /// sufficient amount to send out, thereby avoiding the frequent sending of
335 /// use std::net::TcpStream;
337 /// let stream = TcpStream::connect("127.0.0.1:8080")
338 /// .expect("Couldn't connect to the server...");
339 /// stream.set_nodelay(true).expect("set_nodelay call failed");
341 #[stable(feature = "net2_mutators", since = "1.9.0")]
342 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
343 self.0.set_nodelay(nodelay)
346 /// Gets the value of the `TCP_NODELAY` option on this socket.
348 /// For more information about this option, see [`set_nodelay`][link].
350 /// [link]: #method.set_nodelay
355 /// use std::net::TcpStream;
357 /// let stream = TcpStream::connect("127.0.0.1:8080")
358 /// .expect("Couldn't connect to the server...");
359 /// stream.set_nodelay(true).expect("set_nodelay call failed");
360 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
362 #[stable(feature = "net2_mutators", since = "1.9.0")]
363 pub fn nodelay(&self) -> io::Result<bool> {
367 /// Sets the value for the `IP_TTL` option on this socket.
369 /// This value sets the time-to-live field that is used in every packet sent
370 /// from this socket.
375 /// use std::net::TcpStream;
377 /// let stream = TcpStream::connect("127.0.0.1:8080")
378 /// .expect("Couldn't connect to the server...");
379 /// stream.set_ttl(100).expect("set_ttl call failed");
381 #[stable(feature = "net2_mutators", since = "1.9.0")]
382 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
386 /// Gets the value of the `IP_TTL` option for this socket.
388 /// For more information about this option, see [`set_ttl`][link].
390 /// [link]: #method.set_ttl
395 /// use std::net::TcpStream;
397 /// let stream = TcpStream::connect("127.0.0.1:8080")
398 /// .expect("Couldn't connect to the server...");
399 /// stream.set_ttl(100).expect("set_ttl call failed");
400 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
402 #[stable(feature = "net2_mutators", since = "1.9.0")]
403 pub fn ttl(&self) -> io::Result<u32> {
407 /// Get the value of the `SO_ERROR` option on this socket.
409 /// This will retrieve the stored error in the underlying socket, clearing
410 /// the field in the process. This can be useful for checking errors between
416 /// use std::net::TcpStream;
418 /// let stream = TcpStream::connect("127.0.0.1:8080")
419 /// .expect("Couldn't connect to the server...");
420 /// stream.take_error().expect("No error was expected...");
422 #[stable(feature = "net2_mutators", since = "1.9.0")]
423 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
427 /// Moves this TCP stream into or out of nonblocking mode.
429 /// On Unix this corresponds to calling fcntl, and on Windows this
430 /// corresponds to calling ioctlsocket.
435 /// use std::net::TcpStream;
437 /// let stream = TcpStream::connect("127.0.0.1:8080")
438 /// .expect("Couldn't connect to the server...");
439 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
441 #[stable(feature = "net2_mutators", since = "1.9.0")]
442 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
443 self.0.set_nonblocking(nonblocking)
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl Read for TcpStream {
449 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
450 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
451 self.0.read_to_end(buf)
454 #[stable(feature = "rust1", since = "1.0.0")]
455 impl Write for TcpStream {
456 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
457 fn flush(&mut self) -> io::Result<()> { Ok(()) }
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl<'a> Read for &'a TcpStream {
461 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
462 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
463 self.0.read_to_end(buf)
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl<'a> Write for &'a TcpStream {
468 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
469 fn flush(&mut self) -> io::Result<()> { Ok(()) }
472 impl AsInner<net_imp::TcpStream> for TcpStream {
473 fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
476 impl FromInner<net_imp::TcpStream> for TcpStream {
477 fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
480 impl IntoInner<net_imp::TcpStream> for TcpStream {
481 fn into_inner(self) -> net_imp::TcpStream { self.0 }
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl fmt::Debug for TcpStream {
486 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
492 /// Creates a new `TcpListener` which will be bound to the specified
495 /// The returned listener is ready for accepting connections.
497 /// Binding with a port number of 0 will request that the OS assigns a port
498 /// to this listener. The port allocated can be queried via the
499 /// [`local_addr`] method.
501 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
502 /// its documentation for concrete examples.
504 /// [`local_addr`]: #method.local_addr
505 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
510 /// use std::net::TcpListener;
512 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
516 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
519 /// Returns the local socket address of this listener.
524 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
526 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
527 /// assert_eq!(listener.local_addr().unwrap(),
528 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub fn local_addr(&self) -> io::Result<SocketAddr> {
535 /// Creates a new independently owned handle to the underlying socket.
537 /// The returned [`TcpListener`] is a reference to the same socket that this
538 /// object references. Both handles can be used to accept incoming
539 /// connections and options set on one listener will affect the other.
541 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
546 /// use std::net::TcpListener;
548 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
549 /// let listener_clone = listener.try_clone().unwrap();
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn try_clone(&self) -> io::Result<TcpListener> {
553 self.0.duplicate().map(TcpListener)
556 /// Accept a new incoming connection from this listener.
558 /// This function will block the calling thread until a new TCP connection
559 /// is established. When established, the corresponding [`TcpStream`] and the
560 /// remote peer's address will be returned.
562 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
567 /// use std::net::TcpListener;
569 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
570 /// match listener.accept() {
571 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
572 /// Err(e) => println!("couldn't get client: {:?}", e),
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
577 self.0.accept().map(|(a, b)| (TcpStream(a), b))
580 /// Returns an iterator over the connections being received on this
583 /// The returned iterator will never return [`None`] and will also not yield
584 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
585 /// calling [`accept`] in a loop.
587 /// [`None`]: ../../std/option/enum.Option.html#variant.None
588 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
589 /// [`accept`]: #method.accept
594 /// use std::net::TcpListener;
596 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
598 /// for stream in listener.incoming() {
601 /// println!("new client!");
603 /// Err(e) => { /* connection failed */ }
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn incoming(&self) -> Incoming {
609 Incoming { listener: self }
612 /// Sets the value for the `IP_TTL` option on this socket.
614 /// This value sets the time-to-live field that is used in every packet sent
615 /// from this socket.
620 /// use std::net::TcpListener;
622 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
623 /// listener.set_ttl(100).expect("could not set TTL");
625 #[stable(feature = "net2_mutators", since = "1.9.0")]
626 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
630 /// Gets the value of the `IP_TTL` option for this socket.
632 /// For more information about this option, see [`set_ttl`][link].
634 /// [link]: #method.set_ttl
639 /// use std::net::TcpListener;
641 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
642 /// listener.set_ttl(100).expect("could not set TTL");
643 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
645 #[stable(feature = "net2_mutators", since = "1.9.0")]
646 pub fn ttl(&self) -> io::Result<u32> {
650 #[stable(feature = "net2_mutators", since = "1.9.0")]
651 #[rustc_deprecated(since = "1.16.0",
652 reason = "this option can only be set before the socket is bound")]
653 #[allow(missing_docs)]
654 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
655 self.0.set_only_v6(only_v6)
658 #[stable(feature = "net2_mutators", since = "1.9.0")]
659 #[rustc_deprecated(since = "1.16.0",
660 reason = "this option can only be set before the socket is bound")]
661 #[allow(missing_docs)]
662 pub fn only_v6(&self) -> io::Result<bool> {
666 /// Get the value of the `SO_ERROR` option on this socket.
668 /// This will retrieve the stored error in the underlying socket, clearing
669 /// the field in the process. This can be useful for checking errors between
675 /// use std::net::TcpListener;
677 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
678 /// listener.take_error().expect("No error was expected");
680 #[stable(feature = "net2_mutators", since = "1.9.0")]
681 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
685 /// Moves this TCP stream into or out of nonblocking mode.
687 /// On Unix this corresponds to calling fcntl, and on Windows this
688 /// corresponds to calling ioctlsocket.
693 /// use std::net::TcpListener;
695 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
696 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
698 #[stable(feature = "net2_mutators", since = "1.9.0")]
699 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
700 self.0.set_nonblocking(nonblocking)
704 #[stable(feature = "rust1", since = "1.0.0")]
705 impl<'a> Iterator for Incoming<'a> {
706 type Item = io::Result<TcpStream>;
707 fn next(&mut self) -> Option<io::Result<TcpStream>> {
708 Some(self.listener.accept().map(|p| p.0))
712 impl AsInner<net_imp::TcpListener> for TcpListener {
713 fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
716 impl FromInner<net_imp::TcpListener> for TcpListener {
717 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
722 impl IntoInner<net_imp::TcpListener> for TcpListener {
723 fn into_inner(self) -> net_imp::TcpListener { self.0 }
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl fmt::Debug for TcpListener {
728 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
733 #[cfg(all(test, not(target_os = "emscripten")))]
738 use net::test::{next_test_ip4, next_test_ip6};
739 use sync::mpsc::channel;
740 use sys_common::AsInner;
741 use time::{Instant, Duration};
744 fn each_ip(f: &mut FnMut(SocketAddr)) {
753 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
760 match TcpListener::bind("1.1.1.1:9999") {
763 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
769 match TcpStream::connect("0.0.0.0:1") {
771 Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
772 e.kind() == ErrorKind::InvalidInput ||
773 e.kind() == ErrorKind::AddrInUse ||
774 e.kind() == ErrorKind::AddrNotAvailable,
775 "bad error: {} {:?}", e, e.kind()),
780 fn listen_localhost() {
781 let socket_addr = next_test_ip4();
782 let listener = t!(TcpListener::bind(&socket_addr));
784 let _t = thread::spawn(move || {
785 let mut stream = t!(TcpStream::connect(&("localhost",
786 socket_addr.port())));
787 t!(stream.write(&[144]));
790 let mut stream = t!(listener.accept()).0;
792 t!(stream.read(&mut buf));
793 assert!(buf[0] == 144);
797 fn connect_loopback() {
798 each_ip(&mut |addr| {
799 let acceptor = t!(TcpListener::bind(&addr));
801 let _t = thread::spawn(move|| {
802 let host = match addr {
803 SocketAddr::V4(..) => "127.0.0.1",
804 SocketAddr::V6(..) => "::1",
806 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
807 t!(stream.write(&[66]));
810 let mut stream = t!(acceptor.accept()).0;
812 t!(stream.read(&mut buf));
813 assert!(buf[0] == 66);
819 each_ip(&mut |addr| {
820 let acceptor = t!(TcpListener::bind(&addr));
822 let (tx, rx) = channel();
823 let _t = thread::spawn(move|| {
824 let mut stream = t!(TcpStream::connect(&addr));
825 t!(stream.write(&[99]));
826 tx.send(t!(stream.local_addr())).unwrap();
829 let (mut stream, addr) = t!(acceptor.accept());
831 t!(stream.read(&mut buf));
832 assert!(buf[0] == 99);
833 assert_eq!(addr, t!(rx.recv()));
839 each_ip(&mut |addr| {
840 let acceptor = t!(TcpListener::bind(&addr));
842 let _t = thread::spawn(move|| {
843 let _stream = t!(TcpStream::connect(&addr));
847 let mut stream = t!(acceptor.accept()).0;
849 let nread = t!(stream.read(&mut buf));
850 assert_eq!(nread, 0);
851 let nread = t!(stream.read(&mut buf));
852 assert_eq!(nread, 0);
858 each_ip(&mut |addr| {
859 let acceptor = t!(TcpListener::bind(&addr));
861 let (tx, rx) = channel();
862 let _t = thread::spawn(move|| {
863 drop(t!(TcpStream::connect(&addr)));
864 tx.send(()).unwrap();
867 let mut stream = t!(acceptor.accept()).0;
870 match stream.write(&buf) {
873 assert!(e.kind() == ErrorKind::ConnectionReset ||
874 e.kind() == ErrorKind::BrokenPipe ||
875 e.kind() == ErrorKind::ConnectionAborted,
876 "unknown error: {}", e);
883 fn multiple_connect_serial() {
884 each_ip(&mut |addr| {
886 let acceptor = t!(TcpListener::bind(&addr));
888 let _t = thread::spawn(move|| {
890 let mut stream = t!(TcpStream::connect(&addr));
891 t!(stream.write(&[99]));
895 for stream in acceptor.incoming().take(max) {
896 let mut stream = t!(stream);
898 t!(stream.read(&mut buf));
899 assert_eq!(buf[0], 99);
905 fn multiple_connect_interleaved_greedy_schedule() {
906 const MAX: usize = 10;
907 each_ip(&mut |addr| {
908 let acceptor = t!(TcpListener::bind(&addr));
910 let _t = thread::spawn(move|| {
911 let acceptor = acceptor;
912 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
913 // Start another thread to handle the connection
914 let _t = thread::spawn(move|| {
915 let mut stream = t!(stream);
917 t!(stream.read(&mut buf));
918 assert!(buf[0] == i as u8);
926 fn connect(i: usize, addr: SocketAddr) {
927 if i == MAX { return }
929 let t = thread::spawn(move|| {
930 let mut stream = t!(TcpStream::connect(&addr));
931 // Connect again before writing
932 connect(i + 1, addr);
933 t!(stream.write(&[i as u8]));
935 t.join().ok().unwrap();
940 fn multiple_connect_interleaved_lazy_schedule() {
941 const MAX: usize = 10;
942 each_ip(&mut |addr| {
943 let acceptor = t!(TcpListener::bind(&addr));
945 let _t = thread::spawn(move|| {
946 for stream in acceptor.incoming().take(MAX) {
947 // Start another thread to handle the connection
948 let _t = thread::spawn(move|| {
949 let mut stream = t!(stream);
951 t!(stream.read(&mut buf));
952 assert!(buf[0] == 99);
960 fn connect(i: usize, addr: SocketAddr) {
961 if i == MAX { return }
963 let t = thread::spawn(move|| {
964 let mut stream = t!(TcpStream::connect(&addr));
965 connect(i + 1, addr);
966 t!(stream.write(&[99]));
968 t.join().ok().unwrap();
973 fn socket_and_peer_name() {
974 each_ip(&mut |addr| {
975 let listener = t!(TcpListener::bind(&addr));
976 let so_name = t!(listener.local_addr());
977 assert_eq!(addr, so_name);
978 let _t = thread::spawn(move|| {
979 t!(listener.accept());
982 let stream = t!(TcpStream::connect(&addr));
983 assert_eq!(addr, t!(stream.peer_addr()));
989 each_ip(&mut |addr| {
990 let (tx, rx) = channel();
991 let srv = t!(TcpListener::bind(&addr));
992 let _t = thread::spawn(move|| {
993 let mut cl = t!(srv.accept()).0;
994 cl.write(&[10]).unwrap();
997 tx.send(()).unwrap();
1000 let mut c = t!(TcpStream::connect(&addr));
1001 let mut b = [0; 10];
1002 assert_eq!(c.read(&mut b).unwrap(), 1);
1010 each_ip(&mut |addr| {
1011 let _listener = t!(TcpListener::bind(&addr));
1012 match TcpListener::bind(&addr) {
1015 assert!(e.kind() == ErrorKind::ConnectionRefused ||
1016 e.kind() == ErrorKind::Other ||
1017 e.kind() == ErrorKind::AddrInUse,
1018 "unknown error: {} {:?}", e, e.kind());
1026 each_ip(&mut |addr| {
1027 let acceptor = t!(TcpListener::bind(&addr));
1029 let _t = thread::spawn(move|| {
1030 t!(TcpStream::connect(&addr));
1033 t!(acceptor.accept());
1035 t!(TcpListener::bind(&addr));
1040 fn tcp_clone_smoke() {
1041 each_ip(&mut |addr| {
1042 let acceptor = t!(TcpListener::bind(&addr));
1044 let _t = thread::spawn(move|| {
1045 let mut s = t!(TcpStream::connect(&addr));
1046 let mut buf = [0, 0];
1047 assert_eq!(s.read(&mut buf).unwrap(), 1);
1048 assert_eq!(buf[0], 1);
1052 let mut s1 = t!(acceptor.accept()).0;
1053 let s2 = t!(s1.try_clone());
1055 let (tx1, rx1) = channel();
1056 let (tx2, rx2) = channel();
1057 let _t = thread::spawn(move|| {
1059 rx1.recv().unwrap();
1061 tx2.send(()).unwrap();
1063 tx1.send(()).unwrap();
1064 let mut buf = [0, 0];
1065 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1066 rx2.recv().unwrap();
1071 fn tcp_clone_two_read() {
1072 each_ip(&mut |addr| {
1073 let acceptor = t!(TcpListener::bind(&addr));
1074 let (tx1, rx) = channel();
1075 let tx2 = tx1.clone();
1077 let _t = thread::spawn(move|| {
1078 let mut s = t!(TcpStream::connect(&addr));
1085 let mut s1 = t!(acceptor.accept()).0;
1086 let s2 = t!(s1.try_clone());
1088 let (done, rx) = channel();
1089 let _t = thread::spawn(move|| {
1091 let mut buf = [0, 0];
1092 t!(s2.read(&mut buf));
1093 tx2.send(()).unwrap();
1094 done.send(()).unwrap();
1096 let mut buf = [0, 0];
1097 t!(s1.read(&mut buf));
1098 tx1.send(()).unwrap();
1105 fn tcp_clone_two_write() {
1106 each_ip(&mut |addr| {
1107 let acceptor = t!(TcpListener::bind(&addr));
1109 let _t = thread::spawn(move|| {
1110 let mut s = t!(TcpStream::connect(&addr));
1111 let mut buf = [0, 1];
1112 t!(s.read(&mut buf));
1113 t!(s.read(&mut buf));
1116 let mut s1 = t!(acceptor.accept()).0;
1117 let s2 = t!(s1.try_clone());
1119 let (done, rx) = channel();
1120 let _t = thread::spawn(move|| {
1123 done.send(()).unwrap();
1132 fn shutdown_smoke() {
1133 each_ip(&mut |addr| {
1134 let a = t!(TcpListener::bind(&addr));
1135 let _t = thread::spawn(move|| {
1136 let mut c = t!(a.accept()).0;
1138 assert_eq!(c.read(&mut b).unwrap(), 0);
1142 let mut s = t!(TcpStream::connect(&addr));
1143 t!(s.shutdown(Shutdown::Write));
1144 assert!(s.write(&[1]).is_err());
1146 assert_eq!(t!(s.read(&mut b)), 1);
1147 assert_eq!(b[0], 1);
1152 fn close_readwrite_smoke() {
1153 each_ip(&mut |addr| {
1154 let a = t!(TcpListener::bind(&addr));
1155 let (tx, rx) = channel::<()>();
1156 let _t = thread::spawn(move|| {
1157 let _s = t!(a.accept());
1162 let mut s = t!(TcpStream::connect(&addr));
1163 let mut s2 = t!(s.try_clone());
1165 // closing should prevent reads/writes
1166 t!(s.shutdown(Shutdown::Write));
1167 assert!(s.write(&[0]).is_err());
1168 t!(s.shutdown(Shutdown::Read));
1169 assert_eq!(s.read(&mut b).unwrap(), 0);
1171 // closing should affect previous handles
1172 assert!(s2.write(&[0]).is_err());
1173 assert_eq!(s2.read(&mut b).unwrap(), 0);
1175 // closing should affect new handles
1176 let mut s3 = t!(s.try_clone());
1177 assert!(s3.write(&[0]).is_err());
1178 assert_eq!(s3.read(&mut b).unwrap(), 0);
1180 // make sure these don't die
1181 let _ = s2.shutdown(Shutdown::Read);
1182 let _ = s2.shutdown(Shutdown::Write);
1183 let _ = s3.shutdown(Shutdown::Read);
1184 let _ = s3.shutdown(Shutdown::Write);
1190 #[cfg(unix)] // test doesn't work on Windows, see #31657
1191 fn close_read_wakes_up() {
1192 each_ip(&mut |addr| {
1193 let a = t!(TcpListener::bind(&addr));
1194 let (tx1, rx) = channel::<()>();
1195 let _t = thread::spawn(move|| {
1196 let _s = t!(a.accept());
1200 let s = t!(TcpStream::connect(&addr));
1201 let s2 = t!(s.try_clone());
1202 let (tx, rx) = channel();
1203 let _t = thread::spawn(move|| {
1205 assert_eq!(t!(s2.read(&mut [0])), 0);
1206 tx.send(()).unwrap();
1208 // this should wake up the child thread
1209 t!(s.shutdown(Shutdown::Read));
1211 // this test will never finish if the child doesn't wake up
1218 fn clone_while_reading() {
1219 each_ip(&mut |addr| {
1220 let accept = t!(TcpListener::bind(&addr));
1222 // Enqueue a thread to write to a socket
1223 let (tx, rx) = channel();
1224 let (txdone, rxdone) = channel();
1225 let txdone2 = txdone.clone();
1226 let _t = thread::spawn(move|| {
1227 let mut tcp = t!(TcpStream::connect(&addr));
1229 t!(tcp.write(&[0]));
1230 txdone2.send(()).unwrap();
1233 // Spawn off a reading clone
1234 let tcp = t!(accept.accept()).0;
1235 let tcp2 = t!(tcp.try_clone());
1236 let txdone3 = txdone.clone();
1237 let _t = thread::spawn(move|| {
1238 let mut tcp2 = tcp2;
1239 t!(tcp2.read(&mut [0]));
1240 txdone3.send(()).unwrap();
1243 // Try to ensure that the reading clone is indeed reading
1245 thread::yield_now();
1248 // clone the handle again while it's reading, then let it finish the
1250 let _ = t!(tcp.try_clone());
1251 tx.send(()).unwrap();
1252 rxdone.recv().unwrap();
1253 rxdone.recv().unwrap();
1258 fn clone_accept_smoke() {
1259 each_ip(&mut |addr| {
1260 let a = t!(TcpListener::bind(&addr));
1261 let a2 = t!(a.try_clone());
1263 let _t = thread::spawn(move|| {
1264 let _ = TcpStream::connect(&addr);
1266 let _t = thread::spawn(move|| {
1267 let _ = TcpStream::connect(&addr);
1276 fn clone_accept_concurrent() {
1277 each_ip(&mut |addr| {
1278 let a = t!(TcpListener::bind(&addr));
1279 let a2 = t!(a.try_clone());
1281 let (tx, rx) = channel();
1282 let tx2 = tx.clone();
1284 let _t = thread::spawn(move|| {
1285 tx.send(t!(a.accept())).unwrap();
1287 let _t = thread::spawn(move|| {
1288 tx2.send(t!(a2.accept())).unwrap();
1291 let _t = thread::spawn(move|| {
1292 let _ = TcpStream::connect(&addr);
1294 let _t = thread::spawn(move|| {
1295 let _ = TcpStream::connect(&addr);
1305 let name = if cfg!(windows) {"socket"} else {"fd"};
1306 let socket_addr = next_test_ip4();
1308 let listener = t!(TcpListener::bind(&socket_addr));
1309 let listener_inner = listener.0.socket().as_inner();
1310 let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
1311 socket_addr, name, listener_inner);
1312 assert_eq!(format!("{:?}", listener), compare);
1314 let stream = t!(TcpStream::connect(&("localhost",
1315 socket_addr.port())));
1316 let stream_inner = stream.0.socket().as_inner();
1317 let compare = format!("TcpStream {{ addr: {:?}, \
1318 peer: {:?}, {}: {:?} }}",
1319 stream.local_addr().unwrap(),
1320 stream.peer_addr().unwrap(),
1323 assert_eq!(format!("{:?}", stream), compare);
1326 // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
1327 // no longer has rounding errors.
1328 #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1331 let addr = next_test_ip4();
1332 let listener = t!(TcpListener::bind(&addr));
1334 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1335 let dur = Duration::new(15410, 0);
1337 assert_eq!(None, t!(stream.read_timeout()));
1339 t!(stream.set_read_timeout(Some(dur)));
1340 assert_eq!(Some(dur), t!(stream.read_timeout()));
1342 assert_eq!(None, t!(stream.write_timeout()));
1344 t!(stream.set_write_timeout(Some(dur)));
1345 assert_eq!(Some(dur), t!(stream.write_timeout()));
1347 t!(stream.set_read_timeout(None));
1348 assert_eq!(None, t!(stream.read_timeout()));
1350 t!(stream.set_write_timeout(None));
1351 assert_eq!(None, t!(stream.write_timeout()));
1356 fn test_read_timeout() {
1357 let addr = next_test_ip4();
1358 let listener = t!(TcpListener::bind(&addr));
1360 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1361 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1363 let mut buf = [0; 10];
1364 let start = Instant::now();
1365 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1366 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1367 assert!(start.elapsed() > Duration::from_millis(400));
1372 fn test_read_with_timeout() {
1373 let addr = next_test_ip4();
1374 let listener = t!(TcpListener::bind(&addr));
1376 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1377 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1379 let mut other_end = t!(listener.accept()).0;
1380 t!(other_end.write_all(b"hello world"));
1382 let mut buf = [0; 11];
1383 t!(stream.read(&mut buf));
1384 assert_eq!(b"hello world", &buf[..]);
1386 let start = Instant::now();
1387 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1388 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1389 assert!(start.elapsed() > Duration::from_millis(400));
1395 let addr = next_test_ip4();
1396 let _listener = t!(TcpListener::bind(&addr));
1398 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1400 assert_eq!(false, t!(stream.nodelay()));
1401 t!(stream.set_nodelay(true));
1402 assert_eq!(true, t!(stream.nodelay()));
1403 t!(stream.set_nodelay(false));
1404 assert_eq!(false, t!(stream.nodelay()));
1411 let addr = next_test_ip4();
1412 let listener = t!(TcpListener::bind(&addr));
1414 t!(listener.set_ttl(ttl));
1415 assert_eq!(ttl, t!(listener.ttl()));
1417 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1419 t!(stream.set_ttl(ttl));
1420 assert_eq!(ttl, t!(stream.ttl()));
1424 fn set_nonblocking() {
1425 let addr = next_test_ip4();
1426 let listener = t!(TcpListener::bind(&addr));
1428 t!(listener.set_nonblocking(true));
1429 t!(listener.set_nonblocking(false));
1431 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1433 t!(stream.set_nonblocking(false));
1434 t!(stream.set_nonblocking(true));
1437 match stream.read(&mut buf) {
1438 Ok(_) => panic!("expected error"),
1439 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1440 Err(e) => panic!("unexpected error {}", e),
1446 each_ip(&mut |addr| {
1447 let (txdone, rxdone) = channel();
1449 let srv = t!(TcpListener::bind(&addr));
1450 let _t = thread::spawn(move|| {
1451 let mut cl = t!(srv.accept()).0;
1452 cl.write(&[1,3,3,7]).unwrap();
1456 let mut c = t!(TcpStream::connect(&addr));
1457 let mut b = [0; 10];
1459 let len = c.peek(&mut b).unwrap();
1462 let len = c.read(&mut b).unwrap();
1465 t!(c.set_nonblocking(true));
1466 match c.peek(&mut b) {
1467 Ok(_) => panic!("expected error"),
1468 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1469 Err(e) => panic!("unexpected error {}", e),
1471 t!(txdone.send(()));