]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/mod.rs
Auto merge of #49252 - Manishearth:easy-feature-flag, r=nikomatsakis
[rust.git] / src / libstd / net / mod.rs
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.
4 //
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.
10
11 //! Networking primitives for TCP/UDP communication.
12 //!
13 //! This module provides networking functionality for the Transmission Control and User
14 //! Datagram Protocols, as well as types for IP and socket addresses.
15 //!
16 //! # Organization
17 //!
18 //! * [`TcpListener`] and [`TcpStream`] provide functionality for communication over TCP
19 //! * [`UdpSocket`] provides functionality for communication over UDP
20 //! * [`IpAddr`] represents IP addresses of either IPv4 or IPv6; [`Ipv4Addr`] and
21 //!   [`Ipv6Addr`] are respectively IPv4 and IPv6 addresses
22 //! * [`SocketAddr`] represents socket addresses of either IPv4 or IPv6; [`SocketAddrV4`]
23 //!   and [`SocketAddrV6`] are respectively IPv4 and IPv6 socket addresses
24 //! * [`ToSocketAddrs`] is a trait that used for generic address resolution when interacting
25 //!   with networking objects like [`TcpListener`], [`TcpStream`] or [`UdpSocket`]
26 //! * Other types are return or parameter types for various methods in this module
27 //!
28 //! [`IpAddr`]: ../../std/net/enum.IpAddr.html
29 //! [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
30 //! [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
31 //! [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
32 //! [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
33 //! [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
34 //! [`TcpListener`]: ../../std/net/struct.TcpListener.html
35 //! [`TcpStream`]: ../../std/net/struct.TcpStream.html
36 //! [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
37 //! [`UdpSocket`]: ../../std/net/struct.UdpSocket.html
38
39 #![stable(feature = "rust1", since = "1.0.0")]
40
41 use fmt;
42 use io::{self, Error, ErrorKind};
43 use sys_common::net as net_imp;
44
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub use self::ip::{IpAddr, Ipv4Addr, Ipv6Addr, Ipv6MulticastScope};
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub use self::addr::{SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub use self::tcp::{TcpStream, TcpListener, Incoming};
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub use self::udp::UdpSocket;
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub use self::parser::AddrParseError;
55
56 mod ip;
57 mod addr;
58 mod tcp;
59 mod udp;
60 mod parser;
61 #[cfg(test)]
62 mod test;
63
64 /// Possible values which can be passed to the [`shutdown`] method of
65 /// [`TcpStream`].
66 ///
67 /// [`shutdown`]: struct.TcpStream.html#method.shutdown
68 /// [`TcpStream`]: struct.TcpStream.html
69 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub enum Shutdown {
72     /// The reading portion of the [`TcpStream`] should be shut down.
73     ///
74     /// All currently blocked and future [reads] will return [`Ok(0)`].
75     ///
76     /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
77     /// [reads]: ../../std/io/trait.Read.html
78     /// [`Ok(0)`]: ../../std/result/enum.Result.html#variant.Ok
79     #[stable(feature = "rust1", since = "1.0.0")]
80     Read,
81     /// The writing portion of the [`TcpStream`] should be shut down.
82     ///
83     /// All currently blocked and future [writes] will return an error.
84     ///
85     /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
86     /// [writes]: ../../std/io/trait.Write.html
87     #[stable(feature = "rust1", since = "1.0.0")]
88     Write,
89     /// Both the reading and the writing portions of the [`TcpStream`] should be shut down.
90     ///
91     /// See [`Shutdown::Read`] and [`Shutdown::Write`] for more information.
92     ///
93     /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
94     /// [`Shutdown::Read`]: #variant.Read
95     /// [`Shutdown::Write`]: #variant.Write
96     #[stable(feature = "rust1", since = "1.0.0")]
97     Both,
98 }
99
100 #[doc(hidden)]
101 trait NetInt {
102     fn from_be(i: Self) -> Self;
103     fn to_be(&self) -> Self;
104 }
105 macro_rules! doit {
106     ($($t:ident)*) => ($(impl NetInt for $t {
107         fn from_be(i: Self) -> Self { <$t>::from_be(i) }
108         fn to_be(&self) -> Self { <$t>::to_be(*self) }
109     })*)
110 }
111 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
112
113 fn hton<I: NetInt>(i: I) -> I { i.to_be() }
114 fn ntoh<I: NetInt>(i: I) -> I { I::from_be(i) }
115
116 fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T>
117     where F: FnMut(&SocketAddr) -> io::Result<T>
118 {
119     let mut last_err = None;
120     for addr in addr.to_socket_addrs()? {
121         match f(&addr) {
122             Ok(l) => return Ok(l),
123             Err(e) => last_err = Some(e),
124         }
125     }
126     Err(last_err.unwrap_or_else(|| {
127         Error::new(ErrorKind::InvalidInput,
128                    "could not resolve to any addresses")
129     }))
130 }
131
132 /// An iterator over `SocketAddr` values returned from a host lookup operation.
133 #[unstable(feature = "lookup_host", reason = "unsure about the returned \
134                                               iterator and returning socket \
135                                               addresses",
136            issue = "27705")]
137 #[rustc_deprecated(since = "1.25.0", reason = "Use the ToSocketAddrs trait instead")]
138 pub struct LookupHost(net_imp::LookupHost);
139
140 #[unstable(feature = "lookup_host", reason = "unsure about the returned \
141                                               iterator and returning socket \
142                                               addresses",
143            issue = "27705")]
144 #[rustc_deprecated(since = "1.25.0", reason = "Use the ToSocketAddrs trait instead")]
145 #[allow(deprecated)]
146 impl Iterator for LookupHost {
147     type Item = SocketAddr;
148     fn next(&mut self) -> Option<SocketAddr> { self.0.next() }
149 }
150
151 #[unstable(feature = "lookup_host", reason = "unsure about the returned \
152                                               iterator and returning socket \
153                                               addresses",
154            issue = "27705")]
155 #[rustc_deprecated(since = "1.25.0", reason = "Use the ToSocketAddrs trait instead")]
156 #[allow(deprecated)]
157 impl fmt::Debug for LookupHost {
158     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
159         f.pad("LookupHost { .. }")
160     }
161 }
162
163 /// Resolve the host specified by `host` as a number of `SocketAddr` instances.
164 ///
165 /// This method may perform a DNS query to resolve `host` and may also inspect
166 /// system configuration to resolve the specified hostname.
167 ///
168 /// The returned iterator will skip over any unknown addresses returned by the
169 /// operating system.
170 ///
171 /// # Examples
172 ///
173 /// ```no_run
174 /// #![feature(lookup_host)]
175 ///
176 /// use std::net;
177 ///
178 /// fn main() -> std::io::Result<()> {
179 ///     for host in net::lookup_host("rust-lang.org")? {
180 ///         println!("found address: {}", host);
181 ///     }
182 ///     Ok(())
183 /// }
184 /// ```
185 #[unstable(feature = "lookup_host", reason = "unsure about the returned \
186                                               iterator and returning socket \
187                                               addresses",
188            issue = "27705")]
189 #[rustc_deprecated(since = "1.25.0", reason = "Use the ToSocketAddrs trait instead")]
190 #[allow(deprecated)]
191 pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
192     net_imp::lookup_host(host).map(LookupHost)
193 }