1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 use io::{self, Initializer};
15 use net::{ToSocketAddrs, SocketAddr, Shutdown};
16 use sys_common::net as net_imp;
17 use sys_common::{AsInner, FromInner, IntoInner};
20 /// A TCP stream between a local and a remote socket.
22 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
23 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
24 /// by [reading] and [writing] to it.
26 /// The connection will be closed when the value is dropped. The reading and writing
27 /// portions of the connection can also be shut down individually with the [`shutdown`]
30 /// The Transmission Control Protocol is specified in [IETF RFC 793].
32 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
33 /// [`connect`]: #method.connect
34 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
35 /// [reading]: ../../std/io/trait.Read.html
36 /// [`shutdown`]: #method.shutdown
37 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
38 /// [writing]: ../../std/io/trait.Write.html
43 /// use std::io::prelude::*;
44 /// use std::net::TcpStream;
47 /// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
49 /// // ignore the Result
50 /// let _ = stream.write(&[1]);
51 /// let _ = stream.read(&mut [0; 128]); // ignore here too
52 /// } // the stream is closed here
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub struct TcpStream(net_imp::TcpStream);
57 /// A TCP socket server, listening for connections.
59 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
60 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
61 /// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
63 /// The socket will be closed when the value is dropped.
65 /// The Transmission Control Protocol is specified in [IETF RFC 793].
67 /// [`accept`]: #method.accept
68 /// [`bind`]: #method.bind
69 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
70 /// [`Incoming`]: ../../std/net/struct.Incoming.html
71 /// [`TcpListener::incoming`]: #method.incoming
77 /// use std::net::{TcpListener, TcpStream};
79 /// fn handle_client(stream: TcpStream) {
83 /// fn main() -> io::Result<()> {
84 /// let listener = TcpListener::bind("127.0.0.1:80")?;
86 /// // accept connections and process them serially
87 /// for stream in listener.incoming() {
88 /// handle_client(stream?);
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub struct TcpListener(net_imp::TcpListener);
96 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
98 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
99 /// See its documentation for more.
101 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
102 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
103 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
104 #[stable(feature = "rust1", since = "1.0.0")]
106 pub struct Incoming<'a> { listener: &'a TcpListener }
109 /// Opens a TCP connection to a remote host.
111 /// `addr` is an address of the remote host. Anything which implements
112 /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
113 /// documentation for concrete examples.
115 /// If `addr` yields multiple addresses, `connect` will be attempted with
116 /// each of the addresses until a connection is successful. If none of
117 /// the addresses result in a successful connection, the error returned from
118 /// the last connection attempt (the last address) is returned.
120 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
124 /// Open a TCP connection to `127.0.0.1:8080`:
127 /// use std::net::TcpStream;
129 /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
130 /// println!("Connected to the server!");
132 /// println!("Couldn't connect to server...");
136 /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
137 /// a TCP connection to `127.0.0.1:8081`:
140 /// use std::net::{SocketAddr, TcpStream};
143 /// SocketAddr::from(([127, 0, 0, 1], 8080)),
144 /// SocketAddr::from(([127, 0, 0, 1], 8081)),
146 /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
147 /// println!("Connected to the server!");
149 /// println!("Couldn't connect to server...");
152 #[stable(feature = "rust1", since = "1.0.0")]
153 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
154 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
157 /// Opens a TCP connection to a remote host with a timeout.
159 /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
160 /// timeout must be applied to individual addresses.
162 /// It is an error to pass a zero `Duration` to this function.
164 /// Unlike other methods on `TcpStream`, this does not correspond to a
165 /// single system call. It instead calls `connect` in nonblocking mode and
166 /// then uses an OS-specific mechanism to await the completion of the
167 /// connection request.
169 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
170 #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
171 pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
172 net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
175 /// Returns the socket address of the remote peer of this TCP connection.
180 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
182 /// let stream = TcpStream::connect("127.0.0.1:8080")
183 /// .expect("Couldn't connect to the server...");
184 /// assert_eq!(stream.peer_addr().unwrap(),
185 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
192 /// Returns the socket address of the local half of this TCP connection.
197 /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
199 /// let stream = TcpStream::connect("127.0.0.1:8080")
200 /// .expect("Couldn't connect to the server...");
201 /// assert_eq!(stream.local_addr().unwrap().ip(),
202 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn local_addr(&self) -> io::Result<SocketAddr> {
209 /// Shuts down the read, write, or both halves of this connection.
211 /// This function will cause all pending and future I/O on the specified
212 /// portions to return immediately with an appropriate value (see the
213 /// documentation of [`Shutdown`]).
215 /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
217 /// # Platform-specific behavior
219 /// Calling this function multiple times may result in different behavior,
220 /// depending on the operating system. On Linux, the second call will
221 /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
222 /// This may change in the future.
227 /// use std::net::{Shutdown, TcpStream};
229 /// let stream = TcpStream::connect("127.0.0.1:8080")
230 /// .expect("Couldn't connect to the server...");
231 /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
233 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
238 /// Creates a new independently owned handle to the underlying socket.
240 /// The returned `TcpStream` is a reference to the same stream that this
241 /// object references. Both handles will read and write the same stream of
242 /// data, and options set on one stream will be propagated to the other
248 /// use std::net::TcpStream;
250 /// let stream = TcpStream::connect("127.0.0.1:8080")
251 /// .expect("Couldn't connect to the server...");
252 /// let stream_clone = stream.try_clone().expect("clone failed...");
254 #[stable(feature = "rust1", since = "1.0.0")]
255 pub fn try_clone(&self) -> io::Result<TcpStream> {
256 self.0.duplicate().map(TcpStream)
259 /// Sets the read timeout to the timeout specified.
261 /// If the value specified is [`None`], then [`read`] calls will block
262 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
263 /// passed to this method.
265 /// # Platform-specific behavior
267 /// Platforms may return a different error code whenever a read times out as
268 /// a result of setting this option. For example Unix typically returns an
269 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
271 /// [`None`]: ../../std/option/enum.Option.html#variant.None
272 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
273 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
274 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
275 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
276 /// [`Duration`]: ../../std/time/struct.Duration.html
281 /// use std::net::TcpStream;
283 /// let stream = TcpStream::connect("127.0.0.1:8080")
284 /// .expect("Couldn't connect to the server...");
285 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
288 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
293 /// use std::net::TcpStream;
294 /// use std::time::Duration;
296 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
297 /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
298 /// let err = result.unwrap_err();
299 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
301 #[stable(feature = "socket_timeout", since = "1.4.0")]
302 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
303 self.0.set_read_timeout(dur)
306 /// Sets the write timeout to the timeout specified.
308 /// If the value specified is [`None`], then [`write`] calls will block
309 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
310 /// passed to this method.
312 /// # Platform-specific behavior
314 /// Platforms may return a different error code whenever a write times out
315 /// as a result of setting this option. For example Unix typically returns
316 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
318 /// [`None`]: ../../std/option/enum.Option.html#variant.None
319 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
320 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
321 /// [`Duration`]: ../../std/time/struct.Duration.html
322 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
323 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
328 /// use std::net::TcpStream;
330 /// let stream = TcpStream::connect("127.0.0.1:8080")
331 /// .expect("Couldn't connect to the server...");
332 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
335 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
340 /// use std::net::TcpStream;
341 /// use std::time::Duration;
343 /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
344 /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
345 /// let err = result.unwrap_err();
346 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
348 #[stable(feature = "socket_timeout", since = "1.4.0")]
349 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
350 self.0.set_write_timeout(dur)
353 /// Returns the read timeout of this socket.
355 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
357 /// # Platform-specific behavior
359 /// Some platforms do not provide access to the current timeout.
361 /// [`None`]: ../../std/option/enum.Option.html#variant.None
362 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
367 /// use std::net::TcpStream;
369 /// let stream = TcpStream::connect("127.0.0.1:8080")
370 /// .expect("Couldn't connect to the server...");
371 /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
372 /// assert_eq!(stream.read_timeout().unwrap(), None);
374 #[stable(feature = "socket_timeout", since = "1.4.0")]
375 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
376 self.0.read_timeout()
379 /// Returns the write timeout of this socket.
381 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
383 /// # Platform-specific behavior
385 /// Some platforms do not provide access to the current timeout.
387 /// [`None`]: ../../std/option/enum.Option.html#variant.None
388 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
393 /// use std::net::TcpStream;
395 /// let stream = TcpStream::connect("127.0.0.1:8080")
396 /// .expect("Couldn't connect to the server...");
397 /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
398 /// assert_eq!(stream.write_timeout().unwrap(), None);
400 #[stable(feature = "socket_timeout", since = "1.4.0")]
401 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
402 self.0.write_timeout()
405 /// Receives data on the socket from the remote address to which it is
406 /// connected, without removing that data from the queue. On success,
407 /// returns the number of bytes peeked.
409 /// Successive calls return the same data. This is accomplished by passing
410 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
415 /// use std::net::TcpStream;
417 /// let stream = TcpStream::connect("127.0.0.1:8000")
418 /// .expect("couldn't bind to address");
419 /// let mut buf = [0; 10];
420 /// let len = stream.peek(&mut buf).expect("peek failed");
422 #[stable(feature = "peek", since = "1.18.0")]
423 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
427 /// Sets the value of the `TCP_NODELAY` option on this socket.
429 /// If set, this option disables the Nagle algorithm. This means that
430 /// segments are always sent as soon as possible, even if there is only a
431 /// small amount of data. When not set, data is buffered until there is a
432 /// sufficient amount to send out, thereby avoiding the frequent sending of
438 /// use std::net::TcpStream;
440 /// let stream = TcpStream::connect("127.0.0.1:8080")
441 /// .expect("Couldn't connect to the server...");
442 /// stream.set_nodelay(true).expect("set_nodelay call failed");
444 #[stable(feature = "net2_mutators", since = "1.9.0")]
445 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
446 self.0.set_nodelay(nodelay)
449 /// Gets the value of the `TCP_NODELAY` option on this socket.
451 /// For more information about this option, see [`set_nodelay`][link].
453 /// [link]: #method.set_nodelay
458 /// use std::net::TcpStream;
460 /// let stream = TcpStream::connect("127.0.0.1:8080")
461 /// .expect("Couldn't connect to the server...");
462 /// stream.set_nodelay(true).expect("set_nodelay call failed");
463 /// assert_eq!(stream.nodelay().unwrap_or(false), true);
465 #[stable(feature = "net2_mutators", since = "1.9.0")]
466 pub fn nodelay(&self) -> io::Result<bool> {
470 /// Sets the value for the `IP_TTL` option on this socket.
472 /// This value sets the time-to-live field that is used in every packet sent
473 /// from this socket.
478 /// use std::net::TcpStream;
480 /// let stream = TcpStream::connect("127.0.0.1:8080")
481 /// .expect("Couldn't connect to the server...");
482 /// stream.set_ttl(100).expect("set_ttl call failed");
484 #[stable(feature = "net2_mutators", since = "1.9.0")]
485 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
489 /// Gets the value of the `IP_TTL` option for this socket.
491 /// For more information about this option, see [`set_ttl`][link].
493 /// [link]: #method.set_ttl
498 /// use std::net::TcpStream;
500 /// let stream = TcpStream::connect("127.0.0.1:8080")
501 /// .expect("Couldn't connect to the server...");
502 /// stream.set_ttl(100).expect("set_ttl call failed");
503 /// assert_eq!(stream.ttl().unwrap_or(0), 100);
505 #[stable(feature = "net2_mutators", since = "1.9.0")]
506 pub fn ttl(&self) -> io::Result<u32> {
510 /// Get the value of the `SO_ERROR` option on this socket.
512 /// This will retrieve the stored error in the underlying socket, clearing
513 /// the field in the process. This can be useful for checking errors between
519 /// use std::net::TcpStream;
521 /// let stream = TcpStream::connect("127.0.0.1:8080")
522 /// .expect("Couldn't connect to the server...");
523 /// stream.take_error().expect("No error was expected...");
525 #[stable(feature = "net2_mutators", since = "1.9.0")]
526 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
530 /// Moves this TCP stream into or out of nonblocking mode.
532 /// This will result in `read`, `write`, `recv` and `send` operations
533 /// becoming nonblocking, i.e. immediately returning from their calls.
534 /// If the IO operation is successful, `Ok` is returned and no further
535 /// action is required. If the IO operation could not be completed and needs
536 /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
539 /// On Unix platforms, calling this method corresponds to calling `fcntl`
540 /// `FIONBIO`. On Windows calling this method corresponds to calling
541 /// `ioctlsocket` `FIONBIO`.
545 /// Reading bytes from a TCP stream in non-blocking mode:
548 /// use std::io::{self, Read};
549 /// use std::net::TcpStream;
551 /// let mut stream = TcpStream::connect("127.0.0.1:7878")
552 /// .expect("Couldn't connect to the server...");
553 /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
555 /// # fn wait_for_fd() { unimplemented!() }
556 /// let mut buf = vec![];
558 /// match stream.read_to_end(&mut buf) {
560 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
561 /// // wait until network socket is ready, typically implemented
562 /// // via platform-specific APIs such as epoll or IOCP
565 /// Err(e) => panic!("encountered IO error: {}", e),
568 /// println!("bytes: {:?}", buf);
571 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
572 #[stable(feature = "net2_mutators", since = "1.9.0")]
573 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
574 self.0.set_nonblocking(nonblocking)
578 #[stable(feature = "rust1", since = "1.0.0")]
579 impl Read for TcpStream {
580 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
583 unsafe fn initializer(&self) -> Initializer {
587 #[stable(feature = "rust1", since = "1.0.0")]
588 impl Write for TcpStream {
589 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
590 fn flush(&mut self) -> io::Result<()> { Ok(()) }
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl<'a> Read for &'a TcpStream {
594 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
597 unsafe fn initializer(&self) -> Initializer {
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl<'a> Write for &'a TcpStream {
603 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
604 fn flush(&mut self) -> io::Result<()> { Ok(()) }
607 impl AsInner<net_imp::TcpStream> for TcpStream {
608 fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
611 impl FromInner<net_imp::TcpStream> for TcpStream {
612 fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
615 impl IntoInner<net_imp::TcpStream> for TcpStream {
616 fn into_inner(self) -> net_imp::TcpStream { self.0 }
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl fmt::Debug for TcpStream {
621 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
627 /// Creates a new `TcpListener` which will be bound to the specified
630 /// The returned listener is ready for accepting connections.
632 /// Binding with a port number of 0 will request that the OS assigns a port
633 /// to this listener. The port allocated can be queried via the
634 /// [`local_addr`] method.
636 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
637 /// its documentation for concrete examples.
639 /// If `addr` yields multiple addresses, `bind` will be attempted with
640 /// each of the addresses until one succeeds and returns the listener. If
641 /// none of the addresses succeed in creating a listener, the error returned
642 /// from the last attempt (the last address) is returned.
644 /// [`local_addr`]: #method.local_addr
645 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
649 /// Create a TCP listener bound to `127.0.0.1:80`:
652 /// use std::net::TcpListener;
654 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
657 /// Create a TCP listener bound to `127.0.0.1:80`. If that fails, create a
658 /// TCP listener bound to `127.0.0.1:443`:
661 /// use std::net::{SocketAddr, TcpListener};
664 /// SocketAddr::from(([127, 0, 0, 1], 80)),
665 /// SocketAddr::from(([127, 0, 0, 1], 443)),
667 /// let listener = TcpListener::bind(&addrs[..]).unwrap();
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
671 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
674 /// Returns the local socket address of this listener.
679 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
681 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
682 /// assert_eq!(listener.local_addr().unwrap(),
683 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
685 #[stable(feature = "rust1", since = "1.0.0")]
686 pub fn local_addr(&self) -> io::Result<SocketAddr> {
690 /// Creates a new independently owned handle to the underlying socket.
692 /// The returned [`TcpListener`] is a reference to the same socket that this
693 /// object references. Both handles can be used to accept incoming
694 /// connections and options set on one listener will affect the other.
696 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
701 /// use std::net::TcpListener;
703 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
704 /// let listener_clone = listener.try_clone().unwrap();
706 #[stable(feature = "rust1", since = "1.0.0")]
707 pub fn try_clone(&self) -> io::Result<TcpListener> {
708 self.0.duplicate().map(TcpListener)
711 /// Accept a new incoming connection from this listener.
713 /// This function will block the calling thread until a new TCP connection
714 /// is established. When established, the corresponding [`TcpStream`] and the
715 /// remote peer's address will be returned.
717 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
722 /// use std::net::TcpListener;
724 /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
725 /// match listener.accept() {
726 /// Ok((_socket, addr)) => println!("new client: {:?}", addr),
727 /// Err(e) => println!("couldn't get client: {:?}", e),
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
732 self.0.accept().map(|(a, b)| (TcpStream(a), b))
735 /// Returns an iterator over the connections being received on this
738 /// The returned iterator will never return [`None`] and will also not yield
739 /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
740 /// calling [`accept`] in a loop.
742 /// [`None`]: ../../std/option/enum.Option.html#variant.None
743 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
744 /// [`accept`]: #method.accept
749 /// use std::net::TcpListener;
751 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
753 /// for stream in listener.incoming() {
756 /// println!("new client!");
758 /// Err(e) => { /* connection failed */ }
762 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn incoming(&self) -> Incoming {
764 Incoming { listener: self }
767 /// Sets the value for the `IP_TTL` option on this socket.
769 /// This value sets the time-to-live field that is used in every packet sent
770 /// from this socket.
775 /// use std::net::TcpListener;
777 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
778 /// listener.set_ttl(100).expect("could not set TTL");
780 #[stable(feature = "net2_mutators", since = "1.9.0")]
781 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
785 /// Gets the value of the `IP_TTL` option for this socket.
787 /// For more information about this option, see [`set_ttl`][link].
789 /// [link]: #method.set_ttl
794 /// use std::net::TcpListener;
796 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
797 /// listener.set_ttl(100).expect("could not set TTL");
798 /// assert_eq!(listener.ttl().unwrap_or(0), 100);
800 #[stable(feature = "net2_mutators", since = "1.9.0")]
801 pub fn ttl(&self) -> io::Result<u32> {
805 #[stable(feature = "net2_mutators", since = "1.9.0")]
806 #[rustc_deprecated(since = "1.16.0",
807 reason = "this option can only be set before the socket is bound")]
808 #[allow(missing_docs)]
809 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
810 self.0.set_only_v6(only_v6)
813 #[stable(feature = "net2_mutators", since = "1.9.0")]
814 #[rustc_deprecated(since = "1.16.0",
815 reason = "this option can only be set before the socket is bound")]
816 #[allow(missing_docs)]
817 pub fn only_v6(&self) -> io::Result<bool> {
821 /// Get the value of the `SO_ERROR` option on this socket.
823 /// This will retrieve the stored error in the underlying socket, clearing
824 /// the field in the process. This can be useful for checking errors between
830 /// use std::net::TcpListener;
832 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
833 /// listener.take_error().expect("No error was expected");
835 #[stable(feature = "net2_mutators", since = "1.9.0")]
836 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
840 /// Moves this TCP stream into or out of nonblocking mode.
842 /// This will result in the `accept` operation becoming nonblocking,
843 /// i.e. immediately returning from their calls. If the IO operation is
844 /// successful, `Ok` is returned and no further action is required. If the
845 /// IO operation could not be completed and needs to be retried, an error
846 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
848 /// On Unix platforms, calling this method corresponds to calling `fcntl`
849 /// `FIONBIO`. On Windows calling this method corresponds to calling
850 /// `ioctlsocket` `FIONBIO`.
854 /// Bind a TCP listener to an address, listen for connections, and read
855 /// bytes in nonblocking mode:
859 /// use std::net::TcpListener;
861 /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
862 /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
864 /// # fn wait_for_fd() { unimplemented!() }
865 /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
866 /// for stream in listener.incoming() {
869 /// // do something with the TcpStream
870 /// handle_connection(s);
872 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
873 /// // wait until network socket is ready, typically implemented
874 /// // via platform-specific APIs such as epoll or IOCP
878 /// Err(e) => panic!("encountered IO error: {}", e),
883 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
884 #[stable(feature = "net2_mutators", since = "1.9.0")]
885 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
886 self.0.set_nonblocking(nonblocking)
890 #[stable(feature = "rust1", since = "1.0.0")]
891 impl<'a> Iterator for Incoming<'a> {
892 type Item = io::Result<TcpStream>;
893 fn next(&mut self) -> Option<io::Result<TcpStream>> {
894 Some(self.listener.accept().map(|p| p.0))
898 impl AsInner<net_imp::TcpListener> for TcpListener {
899 fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
902 impl FromInner<net_imp::TcpListener> for TcpListener {
903 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
908 impl IntoInner<net_imp::TcpListener> for TcpListener {
909 fn into_inner(self) -> net_imp::TcpListener { self.0 }
912 #[stable(feature = "rust1", since = "1.0.0")]
913 impl fmt::Debug for TcpListener {
914 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
919 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
924 use net::test::{next_test_ip4, next_test_ip6};
925 use sync::mpsc::channel;
926 use sys_common::AsInner;
927 use time::{Instant, Duration};
930 fn each_ip(f: &mut dyn FnMut(SocketAddr)) {
939 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
946 match TcpListener::bind("1.1.1.1:9999") {
949 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
955 match TcpStream::connect("0.0.0.0:1") {
957 Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
958 e.kind() == ErrorKind::InvalidInput ||
959 e.kind() == ErrorKind::AddrInUse ||
960 e.kind() == ErrorKind::AddrNotAvailable,
961 "bad error: {} {:?}", e, e.kind()),
966 fn listen_localhost() {
967 let socket_addr = next_test_ip4();
968 let listener = t!(TcpListener::bind(&socket_addr));
970 let _t = thread::spawn(move || {
971 let mut stream = t!(TcpStream::connect(&("localhost",
972 socket_addr.port())));
973 t!(stream.write(&[144]));
976 let mut stream = t!(listener.accept()).0;
978 t!(stream.read(&mut buf));
979 assert!(buf[0] == 144);
983 fn connect_loopback() {
984 each_ip(&mut |addr| {
985 let acceptor = t!(TcpListener::bind(&addr));
987 let _t = thread::spawn(move|| {
988 let host = match addr {
989 SocketAddr::V4(..) => "127.0.0.1",
990 SocketAddr::V6(..) => "::1",
992 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
993 t!(stream.write(&[66]));
996 let mut stream = t!(acceptor.accept()).0;
998 t!(stream.read(&mut buf));
999 assert!(buf[0] == 66);
1005 each_ip(&mut |addr| {
1006 let acceptor = t!(TcpListener::bind(&addr));
1008 let (tx, rx) = channel();
1009 let _t = thread::spawn(move|| {
1010 let mut stream = t!(TcpStream::connect(&addr));
1011 t!(stream.write(&[99]));
1012 tx.send(t!(stream.local_addr())).unwrap();
1015 let (mut stream, addr) = t!(acceptor.accept());
1017 t!(stream.read(&mut buf));
1018 assert!(buf[0] == 99);
1019 assert_eq!(addr, t!(rx.recv()));
1025 each_ip(&mut |addr| {
1026 let acceptor = t!(TcpListener::bind(&addr));
1028 let _t = thread::spawn(move|| {
1029 let _stream = t!(TcpStream::connect(&addr));
1033 let mut stream = t!(acceptor.accept()).0;
1035 let nread = t!(stream.read(&mut buf));
1036 assert_eq!(nread, 0);
1037 let nread = t!(stream.read(&mut buf));
1038 assert_eq!(nread, 0);
1044 each_ip(&mut |addr| {
1045 let acceptor = t!(TcpListener::bind(&addr));
1047 let (tx, rx) = channel();
1048 let _t = thread::spawn(move|| {
1049 drop(t!(TcpStream::connect(&addr)));
1050 tx.send(()).unwrap();
1053 let mut stream = t!(acceptor.accept()).0;
1056 match stream.write(&buf) {
1059 assert!(e.kind() == ErrorKind::ConnectionReset ||
1060 e.kind() == ErrorKind::BrokenPipe ||
1061 e.kind() == ErrorKind::ConnectionAborted,
1062 "unknown error: {}", e);
1069 fn multiple_connect_serial() {
1070 each_ip(&mut |addr| {
1072 let acceptor = t!(TcpListener::bind(&addr));
1074 let _t = thread::spawn(move|| {
1076 let mut stream = t!(TcpStream::connect(&addr));
1077 t!(stream.write(&[99]));
1081 for stream in acceptor.incoming().take(max) {
1082 let mut stream = t!(stream);
1084 t!(stream.read(&mut buf));
1085 assert_eq!(buf[0], 99);
1091 fn multiple_connect_interleaved_greedy_schedule() {
1092 const MAX: usize = 10;
1093 each_ip(&mut |addr| {
1094 let acceptor = t!(TcpListener::bind(&addr));
1096 let _t = thread::spawn(move|| {
1097 let acceptor = acceptor;
1098 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
1099 // Start another thread to handle the connection
1100 let _t = thread::spawn(move|| {
1101 let mut stream = t!(stream);
1103 t!(stream.read(&mut buf));
1104 assert!(buf[0] == i as u8);
1112 fn connect(i: usize, addr: SocketAddr) {
1113 if i == MAX { return }
1115 let t = thread::spawn(move|| {
1116 let mut stream = t!(TcpStream::connect(&addr));
1117 // Connect again before writing
1118 connect(i + 1, addr);
1119 t!(stream.write(&[i as u8]));
1121 t.join().ok().unwrap();
1126 fn multiple_connect_interleaved_lazy_schedule() {
1127 const MAX: usize = 10;
1128 each_ip(&mut |addr| {
1129 let acceptor = t!(TcpListener::bind(&addr));
1131 let _t = thread::spawn(move|| {
1132 for stream in acceptor.incoming().take(MAX) {
1133 // Start another thread to handle the connection
1134 let _t = thread::spawn(move|| {
1135 let mut stream = t!(stream);
1137 t!(stream.read(&mut buf));
1138 assert!(buf[0] == 99);
1146 fn connect(i: usize, addr: SocketAddr) {
1147 if i == MAX { return }
1149 let t = thread::spawn(move|| {
1150 let mut stream = t!(TcpStream::connect(&addr));
1151 connect(i + 1, addr);
1152 t!(stream.write(&[99]));
1154 t.join().ok().unwrap();
1159 fn socket_and_peer_name() {
1160 each_ip(&mut |addr| {
1161 let listener = t!(TcpListener::bind(&addr));
1162 let so_name = t!(listener.local_addr());
1163 assert_eq!(addr, so_name);
1164 let _t = thread::spawn(move|| {
1165 t!(listener.accept());
1168 let stream = t!(TcpStream::connect(&addr));
1169 assert_eq!(addr, t!(stream.peer_addr()));
1175 each_ip(&mut |addr| {
1176 let (tx, rx) = channel();
1177 let srv = t!(TcpListener::bind(&addr));
1178 let _t = thread::spawn(move|| {
1179 let mut cl = t!(srv.accept()).0;
1180 cl.write(&[10]).unwrap();
1182 t!(cl.read(&mut b));
1183 tx.send(()).unwrap();
1186 let mut c = t!(TcpStream::connect(&addr));
1187 let mut b = [0; 10];
1188 assert_eq!(c.read(&mut b).unwrap(), 1);
1196 each_ip(&mut |addr| {
1197 let _listener = t!(TcpListener::bind(&addr));
1198 match TcpListener::bind(&addr) {
1201 assert!(e.kind() == ErrorKind::ConnectionRefused ||
1202 e.kind() == ErrorKind::Other ||
1203 e.kind() == ErrorKind::AddrInUse,
1204 "unknown error: {} {:?}", e, e.kind());
1212 each_ip(&mut |addr| {
1213 let acceptor = t!(TcpListener::bind(&addr));
1215 let _t = thread::spawn(move|| {
1216 t!(TcpStream::connect(&addr));
1219 t!(acceptor.accept());
1221 t!(TcpListener::bind(&addr));
1226 fn tcp_clone_smoke() {
1227 each_ip(&mut |addr| {
1228 let acceptor = t!(TcpListener::bind(&addr));
1230 let _t = thread::spawn(move|| {
1231 let mut s = t!(TcpStream::connect(&addr));
1232 let mut buf = [0, 0];
1233 assert_eq!(s.read(&mut buf).unwrap(), 1);
1234 assert_eq!(buf[0], 1);
1238 let mut s1 = t!(acceptor.accept()).0;
1239 let s2 = t!(s1.try_clone());
1241 let (tx1, rx1) = channel();
1242 let (tx2, rx2) = channel();
1243 let _t = thread::spawn(move|| {
1245 rx1.recv().unwrap();
1247 tx2.send(()).unwrap();
1249 tx1.send(()).unwrap();
1250 let mut buf = [0, 0];
1251 assert_eq!(s1.read(&mut buf).unwrap(), 1);
1252 rx2.recv().unwrap();
1257 fn tcp_clone_two_read() {
1258 each_ip(&mut |addr| {
1259 let acceptor = t!(TcpListener::bind(&addr));
1260 let (tx1, rx) = channel();
1261 let tx2 = tx1.clone();
1263 let _t = thread::spawn(move|| {
1264 let mut s = t!(TcpStream::connect(&addr));
1271 let mut s1 = t!(acceptor.accept()).0;
1272 let s2 = t!(s1.try_clone());
1274 let (done, rx) = channel();
1275 let _t = thread::spawn(move|| {
1277 let mut buf = [0, 0];
1278 t!(s2.read(&mut buf));
1279 tx2.send(()).unwrap();
1280 done.send(()).unwrap();
1282 let mut buf = [0, 0];
1283 t!(s1.read(&mut buf));
1284 tx1.send(()).unwrap();
1291 fn tcp_clone_two_write() {
1292 each_ip(&mut |addr| {
1293 let acceptor = t!(TcpListener::bind(&addr));
1295 let _t = thread::spawn(move|| {
1296 let mut s = t!(TcpStream::connect(&addr));
1297 let mut buf = [0, 1];
1298 t!(s.read(&mut buf));
1299 t!(s.read(&mut buf));
1302 let mut s1 = t!(acceptor.accept()).0;
1303 let s2 = t!(s1.try_clone());
1305 let (done, rx) = channel();
1306 let _t = thread::spawn(move|| {
1309 done.send(()).unwrap();
1318 fn shutdown_smoke() {
1319 each_ip(&mut |addr| {
1320 let a = t!(TcpListener::bind(&addr));
1321 let _t = thread::spawn(move|| {
1322 let mut c = t!(a.accept()).0;
1324 assert_eq!(c.read(&mut b).unwrap(), 0);
1328 let mut s = t!(TcpStream::connect(&addr));
1329 t!(s.shutdown(Shutdown::Write));
1330 assert!(s.write(&[1]).is_err());
1332 assert_eq!(t!(s.read(&mut b)), 1);
1333 assert_eq!(b[0], 1);
1338 fn close_readwrite_smoke() {
1339 each_ip(&mut |addr| {
1340 let a = t!(TcpListener::bind(&addr));
1341 let (tx, rx) = channel::<()>();
1342 let _t = thread::spawn(move|| {
1343 let _s = t!(a.accept());
1348 let mut s = t!(TcpStream::connect(&addr));
1349 let mut s2 = t!(s.try_clone());
1351 // closing should prevent reads/writes
1352 t!(s.shutdown(Shutdown::Write));
1353 assert!(s.write(&[0]).is_err());
1354 t!(s.shutdown(Shutdown::Read));
1355 assert_eq!(s.read(&mut b).unwrap(), 0);
1357 // closing should affect previous handles
1358 assert!(s2.write(&[0]).is_err());
1359 assert_eq!(s2.read(&mut b).unwrap(), 0);
1361 // closing should affect new handles
1362 let mut s3 = t!(s.try_clone());
1363 assert!(s3.write(&[0]).is_err());
1364 assert_eq!(s3.read(&mut b).unwrap(), 0);
1366 // make sure these don't die
1367 let _ = s2.shutdown(Shutdown::Read);
1368 let _ = s2.shutdown(Shutdown::Write);
1369 let _ = s3.shutdown(Shutdown::Read);
1370 let _ = s3.shutdown(Shutdown::Write);
1376 #[cfg(unix)] // test doesn't work on Windows, see #31657
1377 fn close_read_wakes_up() {
1378 each_ip(&mut |addr| {
1379 let a = t!(TcpListener::bind(&addr));
1380 let (tx1, rx) = channel::<()>();
1381 let _t = thread::spawn(move|| {
1382 let _s = t!(a.accept());
1386 let s = t!(TcpStream::connect(&addr));
1387 let s2 = t!(s.try_clone());
1388 let (tx, rx) = channel();
1389 let _t = thread::spawn(move|| {
1391 assert_eq!(t!(s2.read(&mut [0])), 0);
1392 tx.send(()).unwrap();
1394 // this should wake up the child thread
1395 t!(s.shutdown(Shutdown::Read));
1397 // this test will never finish if the child doesn't wake up
1404 fn clone_while_reading() {
1405 each_ip(&mut |addr| {
1406 let accept = t!(TcpListener::bind(&addr));
1408 // Enqueue a thread to write to a socket
1409 let (tx, rx) = channel();
1410 let (txdone, rxdone) = channel();
1411 let txdone2 = txdone.clone();
1412 let _t = thread::spawn(move|| {
1413 let mut tcp = t!(TcpStream::connect(&addr));
1415 t!(tcp.write(&[0]));
1416 txdone2.send(()).unwrap();
1419 // Spawn off a reading clone
1420 let tcp = t!(accept.accept()).0;
1421 let tcp2 = t!(tcp.try_clone());
1422 let txdone3 = txdone.clone();
1423 let _t = thread::spawn(move|| {
1424 let mut tcp2 = tcp2;
1425 t!(tcp2.read(&mut [0]));
1426 txdone3.send(()).unwrap();
1429 // Try to ensure that the reading clone is indeed reading
1431 thread::yield_now();
1434 // clone the handle again while it's reading, then let it finish the
1436 let _ = t!(tcp.try_clone());
1437 tx.send(()).unwrap();
1438 rxdone.recv().unwrap();
1439 rxdone.recv().unwrap();
1444 fn clone_accept_smoke() {
1445 each_ip(&mut |addr| {
1446 let a = t!(TcpListener::bind(&addr));
1447 let a2 = t!(a.try_clone());
1449 let _t = thread::spawn(move|| {
1450 let _ = TcpStream::connect(&addr);
1452 let _t = thread::spawn(move|| {
1453 let _ = TcpStream::connect(&addr);
1462 fn clone_accept_concurrent() {
1463 each_ip(&mut |addr| {
1464 let a = t!(TcpListener::bind(&addr));
1465 let a2 = t!(a.try_clone());
1467 let (tx, rx) = channel();
1468 let tx2 = tx.clone();
1470 let _t = thread::spawn(move|| {
1471 tx.send(t!(a.accept())).unwrap();
1473 let _t = thread::spawn(move|| {
1474 tx2.send(t!(a2.accept())).unwrap();
1477 let _t = thread::spawn(move|| {
1478 let _ = TcpStream::connect(&addr);
1480 let _t = thread::spawn(move|| {
1481 let _ = TcpStream::connect(&addr);
1491 let name = if cfg!(windows) {"socket"} else {"fd"};
1492 let socket_addr = next_test_ip4();
1494 let listener = t!(TcpListener::bind(&socket_addr));
1495 let listener_inner = listener.0.socket().as_inner();
1496 let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
1497 socket_addr, name, listener_inner);
1498 assert_eq!(format!("{:?}", listener), compare);
1500 let stream = t!(TcpStream::connect(&("localhost",
1501 socket_addr.port())));
1502 let stream_inner = stream.0.socket().as_inner();
1503 let compare = format!("TcpStream {{ addr: {:?}, \
1504 peer: {:?}, {}: {:?} }}",
1505 stream.local_addr().unwrap(),
1506 stream.peer_addr().unwrap(),
1509 assert_eq!(format!("{:?}", stream), compare);
1512 // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
1513 // no longer has rounding errors.
1514 #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1517 let addr = next_test_ip4();
1518 let listener = t!(TcpListener::bind(&addr));
1520 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1521 let dur = Duration::new(15410, 0);
1523 assert_eq!(None, t!(stream.read_timeout()));
1525 t!(stream.set_read_timeout(Some(dur)));
1526 assert_eq!(Some(dur), t!(stream.read_timeout()));
1528 assert_eq!(None, t!(stream.write_timeout()));
1530 t!(stream.set_write_timeout(Some(dur)));
1531 assert_eq!(Some(dur), t!(stream.write_timeout()));
1533 t!(stream.set_read_timeout(None));
1534 assert_eq!(None, t!(stream.read_timeout()));
1536 t!(stream.set_write_timeout(None));
1537 assert_eq!(None, t!(stream.write_timeout()));
1542 fn test_read_timeout() {
1543 let addr = next_test_ip4();
1544 let listener = t!(TcpListener::bind(&addr));
1546 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1547 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1549 let mut buf = [0; 10];
1550 let start = Instant::now();
1551 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1552 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1553 assert!(start.elapsed() > Duration::from_millis(400));
1558 fn test_read_with_timeout() {
1559 let addr = next_test_ip4();
1560 let listener = t!(TcpListener::bind(&addr));
1562 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1563 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1565 let mut other_end = t!(listener.accept()).0;
1566 t!(other_end.write_all(b"hello world"));
1568 let mut buf = [0; 11];
1569 t!(stream.read(&mut buf));
1570 assert_eq!(b"hello world", &buf[..]);
1572 let start = Instant::now();
1573 let kind = stream.read(&mut buf).err().expect("expected error").kind();
1574 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1575 assert!(start.elapsed() > Duration::from_millis(400));
1579 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1580 // when passed zero Durations
1582 fn test_timeout_zero_duration() {
1583 let addr = next_test_ip4();
1585 let listener = t!(TcpListener::bind(&addr));
1586 let stream = t!(TcpStream::connect(&addr));
1588 let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1589 let err = result.unwrap_err();
1590 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1592 let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1593 let err = result.unwrap_err();
1594 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1601 let addr = next_test_ip4();
1602 let _listener = t!(TcpListener::bind(&addr));
1604 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1606 assert_eq!(false, t!(stream.nodelay()));
1607 t!(stream.set_nodelay(true));
1608 assert_eq!(true, t!(stream.nodelay()));
1609 t!(stream.set_nodelay(false));
1610 assert_eq!(false, t!(stream.nodelay()));
1617 let addr = next_test_ip4();
1618 let listener = t!(TcpListener::bind(&addr));
1620 t!(listener.set_ttl(ttl));
1621 assert_eq!(ttl, t!(listener.ttl()));
1623 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1625 t!(stream.set_ttl(ttl));
1626 assert_eq!(ttl, t!(stream.ttl()));
1630 fn set_nonblocking() {
1631 let addr = next_test_ip4();
1632 let listener = t!(TcpListener::bind(&addr));
1634 t!(listener.set_nonblocking(true));
1635 t!(listener.set_nonblocking(false));
1637 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1639 t!(stream.set_nonblocking(false));
1640 t!(stream.set_nonblocking(true));
1643 match stream.read(&mut buf) {
1644 Ok(_) => panic!("expected error"),
1645 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1646 Err(e) => panic!("unexpected error {}", e),
1652 each_ip(&mut |addr| {
1653 let (txdone, rxdone) = channel();
1655 let srv = t!(TcpListener::bind(&addr));
1656 let _t = thread::spawn(move|| {
1657 let mut cl = t!(srv.accept()).0;
1658 cl.write(&[1,3,3,7]).unwrap();
1662 let mut c = t!(TcpStream::connect(&addr));
1663 let mut b = [0; 10];
1665 let len = c.peek(&mut b).unwrap();
1668 let len = c.read(&mut b).unwrap();
1671 t!(c.set_nonblocking(true));
1672 match c.peek(&mut b) {
1673 Ok(_) => panic!("expected error"),
1674 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1675 Err(e) => panic!("unexpected error {}", e),
1677 t!(txdone.send(()));
1682 fn connect_timeout_unroutable() {
1683 // this IP is unroutable, so connections should always time out,
1684 // provided the network is reachable to begin with.
1685 let addr = "10.255.255.1:80".parse().unwrap();
1686 let e = TcpStream::connect_timeout(&addr, Duration::from_millis(250)).unwrap_err();
1687 assert!(e.kind() == io::ErrorKind::TimedOut ||
1688 e.kind() == io::ErrorKind::Other,
1689 "bad error: {} {:?}", e, e.kind());
1693 fn connect_timeout_unbound() {
1694 // bind and drop a socket to track down a "probably unassigned" port
1695 let socket = TcpListener::bind("127.0.0.1:0").unwrap();
1696 let addr = socket.local_addr().unwrap();
1699 let timeout = Duration::from_secs(1);
1700 let e = TcpStream::connect_timeout(&addr, timeout).unwrap_err();
1701 assert!(e.kind() == io::ErrorKind::ConnectionRefused ||
1702 e.kind() == io::ErrorKind::TimedOut ||
1703 e.kind() == io::ErrorKind::Other,
1704 "bad error: {} {:?}", e, e.kind());
1708 fn connect_timeout_valid() {
1709 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1710 let addr = listener.local_addr().unwrap();
1711 TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();