std/net/socket_addr.rs
1// Tests for this module
2#[cfg(all(
3 test,
4 not(any(
5 target_os = "emscripten",
6 all(target_os = "wasi", target_env = "p1"),
7 target_os = "l4re"
8 ))
9))]
10mod tests;
11
12#[stable(feature = "rust1", since = "1.0.0")]
13pub use core::net::{SocketAddr, SocketAddrV4, SocketAddrV6};
14
15use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr};
16use crate::{io, iter, option, slice, vec};
17
18/// A trait for objects which can be converted or resolved to one or more
19/// [`SocketAddr`] values.
20///
21/// This trait is used for generic address resolution when constructing network
22/// objects. By default it is implemented for the following types:
23///
24/// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
25///
26/// * [`SocketAddrV4`], [`SocketAddrV6`], <code>([IpAddr], [u16])</code>,
27/// <code>([Ipv4Addr], [u16])</code>, <code>([Ipv6Addr], [u16])</code>:
28/// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
29///
30/// * <code>(&[str], [u16])</code>: <code>&[str]</code> should be either a string representation
31/// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
32/// name. [`u16`] is the port number.
33///
34/// * <code>&[str]</code>: the string should be either a string representation of a
35/// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
36/// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
37///
38/// * <code>&[[SocketAddr]]</code>: all [`SocketAddr`] values in the slice will be used.
39///
40/// This trait allows constructing network objects like [`TcpStream`] or
41/// [`UdpSocket`] easily with values of various types for the bind/connection
42/// address. It is needed because sometimes one type is more appropriate than
43/// the other: for simple uses a string like `"localhost:12345"` is much nicer
44/// than manual construction of the corresponding [`SocketAddr`], but sometimes
45/// [`SocketAddr`] value is *the* main source of the address, and converting it to
46/// some other type (e.g., a string) just for it to be converted back to
47/// [`SocketAddr`] in constructor methods is pointless.
48///
49/// Addresses returned by the operating system that are not IP addresses are
50/// silently ignored.
51///
52/// [`FromStr`]: crate::str::FromStr "std::str::FromStr"
53/// [`TcpStream`]: crate::net::TcpStream "net::TcpStream"
54/// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
55/// [`UdpSocket`]: crate::net::UdpSocket "net::UdpSocket"
56///
57/// # Examples
58///
59/// Creating a [`SocketAddr`] iterator that yields one item:
60///
61/// ```
62/// use std::net::{ToSocketAddrs, SocketAddr};
63///
64/// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
65/// let mut addrs_iter = addr.to_socket_addrs().unwrap();
66///
67/// assert_eq!(Some(addr), addrs_iter.next());
68/// assert!(addrs_iter.next().is_none());
69/// ```
70///
71/// Creating a [`SocketAddr`] iterator from a hostname:
72///
73/// ```no_run
74/// use std::net::{SocketAddr, ToSocketAddrs};
75///
76/// // assuming 'localhost' resolves to 127.0.0.1
77/// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
78/// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
79/// assert!(addrs_iter.next().is_none());
80///
81/// // assuming 'foo' does not resolve
82/// assert!("foo:443".to_socket_addrs().is_err());
83/// ```
84///
85/// Creating a [`SocketAddr`] iterator that yields multiple items:
86///
87/// ```
88/// use std::net::{SocketAddr, ToSocketAddrs};
89///
90/// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
91/// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
92/// let addrs = vec![addr1, addr2];
93///
94/// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
95///
96/// assert_eq!(Some(addr1), addrs_iter.next());
97/// assert_eq!(Some(addr2), addrs_iter.next());
98/// assert!(addrs_iter.next().is_none());
99/// ```
100///
101/// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
102/// socket address `&str` (missing the port):
103///
104/// ```
105/// use std::io;
106/// use std::net::ToSocketAddrs;
107///
108/// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
109/// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
110/// ```
111///
112/// [`TcpStream::connect`] is an example of a function that utilizes
113/// `ToSocketAddrs` as a trait bound on its parameter in order to accept
114/// different types:
115///
116/// ```no_run
117/// use std::net::{TcpStream, Ipv4Addr};
118///
119/// let stream = TcpStream::connect(("127.0.0.1", 443));
120/// // or
121/// let stream = TcpStream::connect("127.0.0.1:443");
122/// // or
123/// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
124/// ```
125///
126/// [`TcpStream::connect`]: crate::net::TcpStream::connect
127#[stable(feature = "rust1", since = "1.0.0")]
128pub trait ToSocketAddrs {
129 /// Returned iterator over socket addresses which this type may correspond
130 /// to.
131 #[stable(feature = "rust1", since = "1.0.0")]
132 type Iter: Iterator<Item = SocketAddr>;
133
134 /// Converts this object to an iterator of resolved [`SocketAddr`]s.
135 ///
136 /// The returned iterator might not actually yield any values depending on the
137 /// outcome of any resolution performed.
138 ///
139 /// Note that this function may block the current thread while resolution is
140 /// performed.
141 #[stable(feature = "rust1", since = "1.0.0")]
142 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
143}
144
145#[stable(feature = "rust1", since = "1.0.0")]
146impl ToSocketAddrs for SocketAddr {
147 type Iter = option::IntoIter<SocketAddr>;
148 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
149 Ok(Some(*self).into_iter())
150 }
151}
152
153#[stable(feature = "rust1", since = "1.0.0")]
154impl ToSocketAddrs for SocketAddrV4 {
155 type Iter = option::IntoIter<SocketAddr>;
156 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
157 SocketAddr::V4(*self).to_socket_addrs()
158 }
159}
160
161#[stable(feature = "rust1", since = "1.0.0")]
162impl ToSocketAddrs for SocketAddrV6 {
163 type Iter = option::IntoIter<SocketAddr>;
164 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
165 SocketAddr::V6(*self).to_socket_addrs()
166 }
167}
168
169#[stable(feature = "rust1", since = "1.0.0")]
170impl ToSocketAddrs for (IpAddr, u16) {
171 type Iter = option::IntoIter<SocketAddr>;
172 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
173 let (ip, port) = *self;
174 match ip {
175 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
176 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
177 }
178 }
179}
180
181#[stable(feature = "rust1", since = "1.0.0")]
182impl ToSocketAddrs for (Ipv4Addr, u16) {
183 type Iter = option::IntoIter<SocketAddr>;
184 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
185 let (ip, port) = *self;
186 SocketAddrV4::new(ip, port).to_socket_addrs()
187 }
188}
189
190#[stable(feature = "rust1", since = "1.0.0")]
191impl ToSocketAddrs for (Ipv6Addr, u16) {
192 type Iter = option::IntoIter<SocketAddr>;
193 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
194 let (ip, port) = *self;
195 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
196 }
197}
198
199#[stable(feature = "rust1", since = "1.0.0")]
200impl ToSocketAddrs for (&str, u16) {
201 type Iter = vec::IntoIter<SocketAddr>;
202 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
203 let (host, port) = *self;
204
205 // Try to parse the host as a regular IP address first
206 if let Ok(addr) = host.parse::<IpAddr>() {
207 let addr = SocketAddr::new(addr, port);
208 return Ok(vec![addr].into_iter());
209 }
210
211 // Otherwise, make the system look it up.
212 crate::sys::net::lookup_host(host, port).map(|addrs| Vec::from_iter(addrs).into_iter())
213 }
214}
215
216#[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
217impl ToSocketAddrs for (String, u16) {
218 type Iter = vec::IntoIter<SocketAddr>;
219 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
220 (&*self.0, self.1).to_socket_addrs()
221 }
222}
223
224// accepts strings like 'localhost:12345'
225#[stable(feature = "rust1", since = "1.0.0")]
226impl ToSocketAddrs for str {
227 type Iter = vec::IntoIter<SocketAddr>;
228 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
229 // Try to parse as a regular SocketAddr first
230 if let Ok(addr) = self.parse() {
231 return Ok(vec![addr].into_iter());
232 }
233
234 // Otherwise, make the system look it up.
235 crate::sys::net::lookup_host_string(self).map(|addrs| Vec::from_iter(addrs).into_iter())
236 }
237}
238
239#[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
240impl<'a> ToSocketAddrs for &'a [SocketAddr] {
241 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
242
243 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
244 Ok(self.iter().cloned())
245 }
246}
247
248#[stable(feature = "rust1", since = "1.0.0")]
249impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
250 type Iter = T::Iter;
251 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
252 (**self).to_socket_addrs()
253 }
254}
255
256#[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
257impl ToSocketAddrs for String {
258 type Iter = vec::IntoIter<SocketAddr>;
259 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
260 (**self).to_socket_addrs()
261 }
262}