Thanks to visit codestin.com
Credit goes to doc.rust-lang.org

std/net/
socket_addr.rs

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