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 infinite iterator over the connections from a `TcpListener`.
70 /// This iterator will infinitely yield [`Some`] of the accepted connections. It
71 /// is equivalent to calling `accept` in a loop.
73 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
75 /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
76 /// [`incoming`]: struct.TcpListener.html#method.incoming
77 /// [`TcpListener`]: struct.TcpListener.html
78 #[stable(feature = "rust1", since = "1.0.0")]
80 pub struct Incoming<'a> { listener: &'a TcpListener }
83 /// Opens a TCP connection to a remote host.
85 /// `addr` is an address of the remote host. Anything which implements
86 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
87 /// documentation for concrete examples.
88 /// In case [`ToSocketAddrs::to_socket_addrs()`] returns more than one entry,
89 /// then the first valid and reachable address is used.
91 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
92 /// [`ToSocketAddrs::to_socket_addrs()`]:
93 /// ../../std/net/trait.ToSocketAddrs.html#tymethod.to_socket_addrs
98 /// use std::net::TcpStream;
100 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
101 /// println!("Connected to the server!");
103 /// println!("Couldn't connect to server...");
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
108 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
111 /// Returns the socket address of the remote peer of this TCP connection.
116 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
118 /// let stream = TcpStream::connect("127.0.0.1:8080")
119 /// .expect("Couldn't connect to the server...");
120 /// assert_eq!(stream.peer_addr().unwrap(),
121 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
123 #[stable(feature = "rust1", since = "1.0.0")]
124 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
128 /// Returns the socket address of the local half of this TCP connection.
133 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
135 /// let stream = TcpStream::connect("127.0.0.1:8080")
136 /// .expect("Couldn't connect to the server...");
137 /// assert_eq!(stream.local_addr().unwrap(),
138 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
140 #[stable(feature = "rust1", since = "1.0.0")]
141 pub fn local_addr(&self) -> io::Result<SocketAddr> {
145 /// Shuts down the read, write, or both halves of this connection.
147 /// This function will cause all pending and future I/O on the specified
148 /// portions to return immediately with an appropriate value (see the
149 /// documentation of [`Shutdown`]).
151 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
156 /// use std::net::{Shutdown, TcpStream};
158 /// let stream = TcpStream::connect("127.0.0.1:8080")
159 /// .expect("Couldn't connect to the server...");
160 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
167 /// Creates a new independently owned handle to the underlying socket.
169 /// The returned `TcpStream` is a reference to the same stream that this
170 /// object references. Both handles will read and write the same stream of
171 /// data, and options set on one stream will be propagated to the other
177 /// use std::net::TcpStream;
179 /// let stream = TcpStream::connect("127.0.0.1:8080")
180 /// .expect("Couldn't connect to the server...");
181 /// let stream_clone = stream.try_clone().expect("clone failed...");
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn try_clone(&self) -> io::Result<TcpStream> {
185 self.0.duplicate().map(TcpStream)
188 /// Sets the read timeout to the timeout specified.
190 /// If the value specified is [`None`], then [`read`] calls will block
191 /// indefinitely. It is an error to pass the zero `Duration` to this
196 /// Platforms may return a different error code whenever a read times out as
197 /// a result of setting this option. For example Unix typically returns an
198 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
200 /// [`None`]: ../../std/option/enum.Option.html#variant.None
201 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
202 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
203 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
208 /// use std::net::TcpStream;
210 /// let stream = TcpStream::connect("127.0.0.1:8080")
211 /// .expect("Couldn't connect to the server...");
212 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
214 #[stable(feature = "socket_timeout", since = "1.4.0")]
215 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
216 self.0.set_read_timeout(dur)
219 /// Sets the write timeout to the timeout specified.
221 /// If the value specified is [`None`], then [`write`] calls will block
222 /// indefinitely. It is an error to pass the zero [`Duration`] to this
227 /// Platforms may return a different error code whenever a write times out
228 /// as a result of setting this option. For example Unix typically returns
229 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
231 /// [`None`]: ../../std/option/enum.Option.html#variant.None
232 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
233 /// [`Duration`]: ../../std/time/struct.Duration.html
234 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
235 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
240 /// use std::net::TcpStream;
242 /// let stream = TcpStream::connect("127.0.0.1:8080")
243 /// .expect("Couldn't connect to the server...");
244 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
246 #[stable(feature = "socket_timeout", since = "1.4.0")]
247 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
248 self.0.set_write_timeout(dur)
251 /// Returns the read timeout of this socket.
253 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
257 /// Some platforms do not provide access to the current timeout.
259 /// [`None`]: ../../std/option/enum.Option.html#variant.None
260 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
265 /// use std::net::TcpStream;
267 /// let stream = TcpStream::connect("127.0.0.1:8080")
268 /// .expect("Couldn't connect to the server...");
269 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
270 /// assert_eq!(stream.read_timeout().unwrap(), None);
272 #[stable(feature = "socket_timeout", since = "1.4.0")]
273 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
274 self.0.read_timeout()
277 /// Returns the write timeout of this socket.
279 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
283 /// Some platforms do not provide access to the current timeout.
285 /// [`None`]: ../../std/option/enum.Option.html#variant.None
286 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
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");
296 /// assert_eq!(stream.write_timeout().unwrap(), None);
298 #[stable(feature = "socket_timeout", since = "1.4.0")]
299 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
300 self.0.write_timeout()
303 /// Receives data on the socket from the remote adress to which it is
304 /// connected, without removing that data from the queue. On success,
305 /// returns the number of bytes peeked.
307 /// Successive calls return the same data. This is accomplished by passing
308 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
313 /// #![feature(peek)]
314 /// use std::net::TcpStream;
316 /// let stream = TcpStream::connect("127.0.0.1:8000")
317 /// .expect("couldn't bind to address");
318 /// let mut buf = [0; 10];
319 /// let len = stream.peek(&mut buf).expect("peek failed");
321 #[unstable(feature = "peek", issue = "38980")]
322 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
326 /// Sets the value of the `TCP_NODELAY` option on this socket.
328 /// If set, this option disables the Nagle algorithm. This means that
329 /// segments are always sent as soon as possible, even if there is only a
330 /// small amount of data. When not set, data is buffered until there is a
331 /// sufficient amount to send out, thereby avoiding the frequent sending of
337 /// use std::net::TcpStream;
339 /// let stream = TcpStream::connect("127.0.0.1:8080")
340 /// .expect("Couldn't connect to the server...");
341 /// stream.set_nodelay(true).expect("set_nodelay call failed");
343 #[stable(feature = "net2_mutators", since = "1.9.0")]
344 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
345 self.0.set_nodelay(nodelay)
348 /// Gets the value of the `TCP_NODELAY` option on this socket.
350 /// For more information about this option, see [`set_nodelay`][link].
352 /// [link]: #method.set_nodelay
357 /// use std::net::TcpStream;
359 /// let stream = TcpStream::connect("127.0.0.1:8080")
360 /// .expect("Couldn't connect to the server...");
361 /// stream.set_nodelay(true).expect("set_nodelay call failed");
362 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
364 #[stable(feature = "net2_mutators", since = "1.9.0")]
365 pub fn nodelay(&self) -> io::Result<bool> {
369 /// Sets the value for the `IP_TTL` option on this socket.
371 /// This value sets the time-to-live field that is used in every packet sent
372 /// from this socket.
377 /// use std::net::TcpStream;
379 /// let stream = TcpStream::connect("127.0.0.1:8080")
380 /// .expect("Couldn't connect to the server...");
381 /// stream.set_ttl(100).expect("set_ttl call failed");
383 #[stable(feature = "net2_mutators", since = "1.9.0")]
384 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
388 /// Gets the value of the `IP_TTL` option for this socket.
390 /// For more information about this option, see [`set_ttl`][link].
392 /// [link]: #method.set_ttl
397 /// use std::net::TcpStream;
399 /// let stream = TcpStream::connect("127.0.0.1:8080")
400 /// .expect("Couldn't connect to the server...");
401 /// stream.set_ttl(100).expect("set_ttl call failed");
402 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
404 #[stable(feature = "net2_mutators", since = "1.9.0")]
405 pub fn ttl(&self) -> io::Result<u32> {
409 /// Get the value of the `SO_ERROR` option on this socket.
411 /// This will retrieve the stored error in the underlying socket, clearing
412 /// the field in the process. This can be useful for checking errors between
418 /// use std::net::TcpStream;
420 /// let stream = TcpStream::connect("127.0.0.1:8080")
421 /// .expect("Couldn't connect to the server...");
422 /// stream.take_error().expect("No error was expected...");
424 #[stable(feature = "net2_mutators", since = "1.9.0")]
425 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
429 /// Moves this TCP stream into or out of nonblocking mode.
431 /// On Unix this corresponds to calling fcntl, and on Windows this
432 /// corresponds to calling ioctlsocket.
437 /// use std::net::TcpStream;
439 /// let stream = TcpStream::connect("127.0.0.1:8080")
440 /// .expect("Couldn't connect to the server...");
441 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
443 #[stable(feature = "net2_mutators", since = "1.9.0")]
444 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
445 self.0.set_nonblocking(nonblocking)
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl Read for TcpStream {
451 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
452 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
453 self.0.read_to_end(buf)
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl Write for TcpStream {
458 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
459 fn flush(&mut self) -> io::Result<()> { Ok(()) }
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl<'a> Read for &'a TcpStream {
463 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
464 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
465 self.0.read_to_end(buf)
468 #[stable(feature = "rust1", since = "1.0.0")]
469 impl<'a> Write for &'a TcpStream {
470 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
471 fn flush(&mut self) -> io::Result<()> { Ok(()) }
474 impl AsInner<net_imp::TcpStream> for TcpStream {
475 fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
478 impl FromInner<net_imp::TcpStream> for TcpStream {
479 fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
482 impl IntoInner<net_imp::TcpStream> for TcpStream {
483 fn into_inner(self) -> net_imp::TcpStream { self.0 }
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl fmt::Debug for TcpStream {
488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
494 /// Creates a new `TcpListener` which will be bound to the specified
497 /// The returned listener is ready for accepting connections.
499 /// Binding with a port number of 0 will request that the OS assigns a port
500 /// to this listener. The port allocated can be queried via the
501 /// [`local_addr`] method.
503 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
504 /// its documentation for concrete examples.
506 /// [`local_addr`]: #method.local_addr
507 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
512 /// use std::net::TcpListener;
514 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
518 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
521 /// Returns the local socket address of this listener.
526 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
528 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
529 /// assert_eq!(listener.local_addr().unwrap(),
530 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn local_addr(&self) -> io::Result<SocketAddr> {
537 /// Creates a new independently owned handle to the underlying socket.
539 /// The returned [`TcpListener`] is a reference to the same socket that this
540 /// object references. Both handles can be used to accept incoming
541 /// connections and options set on one listener will affect the other.
543 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
548 /// use std::net::TcpListener;
550 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
551 /// let listener_clone = listener.try_clone().unwrap();
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn try_clone(&self) -> io::Result<TcpListener> {
555 self.0.duplicate().map(TcpListener)
558 /// Accept a new incoming connection from this listener.
560 /// This function will block the calling thread until a new TCP connection
561 /// is established. When established, the corresponding [`TcpStream`] and the
562 /// remote peer's address will be returned.
564 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
569 /// use std::net::TcpListener;
571 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
572 /// match listener.accept() {
573 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
574 /// Err(e) => println!("couldn't get client: {:?}", e),
577 #[stable(feature = "rust1", since = "1.0.0")]
578 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
579 self.0.accept().map(|(a, b)| (TcpStream(a), b))
582 /// Returns an iterator over the connections being received on this
585 /// The returned iterator will never return [`None`] and will also not yield
586 /// the peer's [`SocketAddr`] structure.
588 /// [`None`]: ../../std/option/enum.Option.html#variant.None
589 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
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(()));