]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/addr.rs
Revert "[net] clippy: needless_update"
[rust.git] / library / std / src / net / addr.rs
1 #[cfg(all(test, not(target_os = "emscripten")))]
2 mod tests;
3
4 use crate::cmp::Ordering;
5 use crate::convert::TryInto;
6 use crate::fmt;
7 use crate::hash;
8 use crate::io::{self, Write};
9 use crate::iter;
10 use crate::mem;
11 use crate::net::{htons, ntohs, IpAddr, Ipv4Addr, Ipv6Addr};
12 use crate::option;
13 use crate::slice;
14 use crate::sys::net::netc as c;
15 use crate::sys_common::net::LookupHost;
16 use crate::sys_common::{AsInner, FromInner, IntoInner};
17 use crate::vec;
18
19 /// An internet socket address, either IPv4 or IPv6.
20 ///
21 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
22 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
23 /// [`SocketAddrV6`]'s respective documentation for more details.
24 ///
25 /// The size of a `SocketAddr` instance may vary depending on the target operating
26 /// system.
27 ///
28 /// [IP address]: IpAddr
29 ///
30 /// # Examples
31 ///
32 /// ```
33 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
34 ///
35 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
36 ///
37 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
38 /// assert_eq!(socket.port(), 8080);
39 /// assert_eq!(socket.is_ipv4(), true);
40 /// ```
41 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub enum SocketAddr {
44     /// An IPv4 socket address.
45     #[stable(feature = "rust1", since = "1.0.0")]
46     V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
47     /// An IPv6 socket address.
48     #[stable(feature = "rust1", since = "1.0.0")]
49     V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
50 }
51
52 /// An IPv4 socket address.
53 ///
54 /// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
55 /// stated in [IETF RFC 793].
56 ///
57 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
58 ///
59 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
60 /// system.
61 ///
62 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
63 /// [`IPv4` address]: Ipv4Addr
64 ///
65 /// # Examples
66 ///
67 /// ```
68 /// use std::net::{Ipv4Addr, SocketAddrV4};
69 ///
70 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
71 ///
72 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
73 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
74 /// assert_eq!(socket.port(), 8080);
75 /// ```
76 #[derive(Copy)]
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct SocketAddrV4 {
79     inner: c::sockaddr_in,
80 }
81
82 /// An IPv6 socket address.
83 ///
84 /// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
85 /// as fields containing the traffic class, the flow label, and a scope identifier
86 /// (see [IETF RFC 2553, Section 3.3] for more details).
87 ///
88 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
89 ///
90 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
91 /// system.
92 ///
93 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
94 /// [`IPv6` address]: Ipv6Addr
95 ///
96 /// # Examples
97 ///
98 /// ```
99 /// use std::net::{Ipv6Addr, SocketAddrV6};
100 ///
101 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
102 ///
103 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
104 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
105 /// assert_eq!(socket.port(), 8080);
106 /// ```
107 #[derive(Copy)]
108 #[stable(feature = "rust1", since = "1.0.0")]
109 pub struct SocketAddrV6 {
110     inner: c::sockaddr_in6,
111 }
112
113 impl SocketAddr {
114     /// Creates a new socket address from an [IP address] and a port number.
115     ///
116     /// [IP address]: IpAddr
117     ///
118     /// # Examples
119     ///
120     /// ```
121     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
122     ///
123     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
124     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
125     /// assert_eq!(socket.port(), 8080);
126     /// ```
127     #[stable(feature = "ip_addr", since = "1.7.0")]
128     pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
129         match ip {
130             IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
131             IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
132         }
133     }
134
135     /// Returns the IP address associated with this socket address.
136     ///
137     /// # Examples
138     ///
139     /// ```
140     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
141     ///
142     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
143     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
144     /// ```
145     #[stable(feature = "ip_addr", since = "1.7.0")]
146     pub fn ip(&self) -> IpAddr {
147         match *self {
148             SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
149             SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
150         }
151     }
152
153     /// Changes the IP address associated with this socket address.
154     ///
155     /// # Examples
156     ///
157     /// ```
158     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
159     ///
160     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
161     /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
162     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
163     /// ```
164     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
165     pub fn set_ip(&mut self, new_ip: IpAddr) {
166         // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
167         match (self, new_ip) {
168             (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
169             (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
170             (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
171         }
172     }
173
174     /// Returns the port number associated with this socket address.
175     ///
176     /// # Examples
177     ///
178     /// ```
179     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
180     ///
181     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
182     /// assert_eq!(socket.port(), 8080);
183     /// ```
184     #[stable(feature = "rust1", since = "1.0.0")]
185     pub fn port(&self) -> u16 {
186         match *self {
187             SocketAddr::V4(ref a) => a.port(),
188             SocketAddr::V6(ref a) => a.port(),
189         }
190     }
191
192     /// Changes the port number associated with this socket address.
193     ///
194     /// # Examples
195     ///
196     /// ```
197     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
198     ///
199     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
200     /// socket.set_port(1025);
201     /// assert_eq!(socket.port(), 1025);
202     /// ```
203     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
204     pub fn set_port(&mut self, new_port: u16) {
205         match *self {
206             SocketAddr::V4(ref mut a) => a.set_port(new_port),
207             SocketAddr::V6(ref mut a) => a.set_port(new_port),
208         }
209     }
210
211     /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
212     /// [`IPv4` address], and [`false`] otherwise.
213     ///
214     /// [IP address]: IpAddr
215     /// [`IPv4` address]: IpAddr::V4
216     ///
217     /// # Examples
218     ///
219     /// ```
220     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
221     ///
222     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
223     /// assert_eq!(socket.is_ipv4(), true);
224     /// assert_eq!(socket.is_ipv6(), false);
225     /// ```
226     #[stable(feature = "sockaddr_checker", since = "1.16.0")]
227     pub fn is_ipv4(&self) -> bool {
228         matches!(*self, SocketAddr::V4(_))
229     }
230
231     /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
232     /// [`IPv6` address], and [`false`] otherwise.
233     ///
234     /// [IP address]: IpAddr
235     /// [`IPv6` address]: IpAddr::V6
236     ///
237     /// # Examples
238     ///
239     /// ```
240     /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
241     ///
242     /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
243     /// assert_eq!(socket.is_ipv4(), false);
244     /// assert_eq!(socket.is_ipv6(), true);
245     /// ```
246     #[stable(feature = "sockaddr_checker", since = "1.16.0")]
247     pub fn is_ipv6(&self) -> bool {
248         matches!(*self, SocketAddr::V6(_))
249     }
250 }
251
252 impl SocketAddrV4 {
253     /// Creates a new socket address from an [`IPv4` address] and a port number.
254     ///
255     /// [`IPv4` address]: Ipv4Addr
256     ///
257     /// # Examples
258     ///
259     /// ```
260     /// use std::net::{SocketAddrV4, Ipv4Addr};
261     ///
262     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
263     /// ```
264     #[stable(feature = "rust1", since = "1.0.0")]
265     pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
266         SocketAddrV4 {
267             inner: c::sockaddr_in {
268                 sin_family: c::AF_INET as c::sa_family_t,
269                 sin_port: htons(port),
270                 sin_addr: ip.into_inner(),
271                 ..unsafe { mem::zeroed() }
272             },
273         }
274     }
275
276     /// Returns the IP address associated with this socket address.
277     ///
278     /// # Examples
279     ///
280     /// ```
281     /// use std::net::{SocketAddrV4, Ipv4Addr};
282     ///
283     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
284     /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
285     /// ```
286     #[stable(feature = "rust1", since = "1.0.0")]
287     pub fn ip(&self) -> &Ipv4Addr {
288         // SAFETY: `Ipv4Addr` is `#[repr(C)] struct { _: in_addr; }`.
289         // It is safe to cast from `&in_addr` to `&Ipv4Addr`.
290         unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
291     }
292
293     /// Changes the IP address associated with this socket address.
294     ///
295     /// # Examples
296     ///
297     /// ```
298     /// use std::net::{SocketAddrV4, Ipv4Addr};
299     ///
300     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
301     /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
302     /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
303     /// ```
304     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
305     pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
306         self.inner.sin_addr = new_ip.into_inner()
307     }
308
309     /// Returns the port number associated with this socket address.
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// use std::net::{SocketAddrV4, Ipv4Addr};
315     ///
316     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
317     /// assert_eq!(socket.port(), 8080);
318     /// ```
319     #[stable(feature = "rust1", since = "1.0.0")]
320     pub fn port(&self) -> u16 {
321         ntohs(self.inner.sin_port)
322     }
323
324     /// Changes the port number associated with this socket address.
325     ///
326     /// # Examples
327     ///
328     /// ```
329     /// use std::net::{SocketAddrV4, Ipv4Addr};
330     ///
331     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
332     /// socket.set_port(4242);
333     /// assert_eq!(socket.port(), 4242);
334     /// ```
335     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
336     pub fn set_port(&mut self, new_port: u16) {
337         self.inner.sin_port = htons(new_port);
338     }
339 }
340
341 impl SocketAddrV6 {
342     /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
343     /// and the `flowinfo` and `scope_id` fields.
344     ///
345     /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
346     /// parameters, see [IETF RFC 2553, Section 3.3].
347     ///
348     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
349     /// [`IPv6` address]: Ipv6Addr
350     ///
351     /// # Examples
352     ///
353     /// ```
354     /// use std::net::{SocketAddrV6, Ipv6Addr};
355     ///
356     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
357     /// ```
358     #[stable(feature = "rust1", since = "1.0.0")]
359     pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
360         SocketAddrV6 {
361             inner: c::sockaddr_in6 {
362                 sin6_family: c::AF_INET6 as c::sa_family_t,
363                 sin6_port: htons(port),
364                 sin6_addr: *ip.as_inner(),
365                 sin6_flowinfo: flowinfo,
366                 sin6_scope_id: scope_id,
367                 ..unsafe { mem::zeroed() }
368             },
369         }
370     }
371
372     /// Returns the IP address associated with this socket address.
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// use std::net::{SocketAddrV6, Ipv6Addr};
378     ///
379     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
380     /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
381     /// ```
382     #[stable(feature = "rust1", since = "1.0.0")]
383     pub fn ip(&self) -> &Ipv6Addr {
384         unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }
385     }
386
387     /// Changes the IP address associated with this socket address.
388     ///
389     /// # Examples
390     ///
391     /// ```
392     /// use std::net::{SocketAddrV6, Ipv6Addr};
393     ///
394     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
395     /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
396     /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
397     /// ```
398     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
399     pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
400         self.inner.sin6_addr = *new_ip.as_inner()
401     }
402
403     /// Returns the port number associated with this socket address.
404     ///
405     /// # Examples
406     ///
407     /// ```
408     /// use std::net::{SocketAddrV6, Ipv6Addr};
409     ///
410     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
411     /// assert_eq!(socket.port(), 8080);
412     /// ```
413     #[stable(feature = "rust1", since = "1.0.0")]
414     pub fn port(&self) -> u16 {
415         ntohs(self.inner.sin6_port)
416     }
417
418     /// Changes the port number associated with this socket address.
419     ///
420     /// # Examples
421     ///
422     /// ```
423     /// use std::net::{SocketAddrV6, Ipv6Addr};
424     ///
425     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
426     /// socket.set_port(4242);
427     /// assert_eq!(socket.port(), 4242);
428     /// ```
429     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
430     pub fn set_port(&mut self, new_port: u16) {
431         self.inner.sin6_port = htons(new_port);
432     }
433
434     /// Returns the flow information associated with this address.
435     ///
436     /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
437     /// as specified in [IETF RFC 2553, Section 3.3].
438     /// It combines information about the flow label and the traffic class as specified
439     /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
440     ///
441     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
442     /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
443     /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
444     /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
445     ///
446     /// # Examples
447     ///
448     /// ```
449     /// use std::net::{SocketAddrV6, Ipv6Addr};
450     ///
451     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
452     /// assert_eq!(socket.flowinfo(), 10);
453     /// ```
454     #[stable(feature = "rust1", since = "1.0.0")]
455     pub fn flowinfo(&self) -> u32 {
456         self.inner.sin6_flowinfo
457     }
458
459     /// Changes the flow information associated with this socket address.
460     ///
461     /// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
462     ///
463     /// # Examples
464     ///
465     /// ```
466     /// use std::net::{SocketAddrV6, Ipv6Addr};
467     ///
468     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
469     /// socket.set_flowinfo(56);
470     /// assert_eq!(socket.flowinfo(), 56);
471     /// ```
472     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
473     pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
474         self.inner.sin6_flowinfo = new_flowinfo;
475     }
476
477     /// Returns the scope ID associated with this address.
478     ///
479     /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
480     /// as specified in [IETF RFC 2553, Section 3.3].
481     ///
482     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
483     ///
484     /// # Examples
485     ///
486     /// ```
487     /// use std::net::{SocketAddrV6, Ipv6Addr};
488     ///
489     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
490     /// assert_eq!(socket.scope_id(), 78);
491     /// ```
492     #[stable(feature = "rust1", since = "1.0.0")]
493     pub fn scope_id(&self) -> u32 {
494         self.inner.sin6_scope_id
495     }
496
497     /// Changes the scope ID associated with this socket address.
498     ///
499     /// See [`SocketAddrV6::scope_id`]'s documentation for more details.
500     ///
501     /// # Examples
502     ///
503     /// ```
504     /// use std::net::{SocketAddrV6, Ipv6Addr};
505     ///
506     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
507     /// socket.set_scope_id(42);
508     /// assert_eq!(socket.scope_id(), 42);
509     /// ```
510     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
511     pub fn set_scope_id(&mut self, new_scope_id: u32) {
512         self.inner.sin6_scope_id = new_scope_id;
513     }
514 }
515
516 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
517     fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
518         SocketAddrV4 { inner: addr }
519     }
520 }
521
522 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
523     fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
524         SocketAddrV6 { inner: addr }
525     }
526 }
527
528 #[stable(feature = "ip_from_ip", since = "1.16.0")]
529 impl From<SocketAddrV4> for SocketAddr {
530     /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
531     fn from(sock4: SocketAddrV4) -> SocketAddr {
532         SocketAddr::V4(sock4)
533     }
534 }
535
536 #[stable(feature = "ip_from_ip", since = "1.16.0")]
537 impl From<SocketAddrV6> for SocketAddr {
538     /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
539     fn from(sock6: SocketAddrV6) -> SocketAddr {
540         SocketAddr::V6(sock6)
541     }
542 }
543
544 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
545 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
546     /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
547     ///
548     /// This conversion creates a [`SocketAddr::V4`] for a [`IpAddr::V4`]
549     /// and creates a [`SocketAddr::V6`] for a [`IpAddr::V6`].
550     ///
551     /// `u16` is treated as port of the newly created [`SocketAddr`].
552     fn from(pieces: (I, u16)) -> SocketAddr {
553         SocketAddr::new(pieces.0.into(), pieces.1)
554     }
555 }
556
557 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
558     fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
559         match *self {
560             SocketAddr::V4(ref a) => {
561                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
562             }
563             SocketAddr::V6(ref a) => {
564                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
565             }
566         }
567     }
568 }
569
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl fmt::Display for SocketAddr {
572     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573         match *self {
574             SocketAddr::V4(ref a) => a.fmt(f),
575             SocketAddr::V6(ref a) => a.fmt(f),
576         }
577     }
578 }
579
580 #[stable(feature = "rust1", since = "1.0.0")]
581 impl fmt::Debug for SocketAddr {
582     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
583         fmt::Display::fmt(self, fmt)
584     }
585 }
586
587 #[stable(feature = "rust1", since = "1.0.0")]
588 impl fmt::Display for SocketAddrV4 {
589     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
590         // Fast path: if there's no alignment stuff, write to the output buffer
591         // directly
592         if f.precision().is_none() && f.width().is_none() {
593             write!(f, "{}:{}", self.ip(), self.port())
594         } else {
595             const IPV4_SOCKET_BUF_LEN: usize = (3 * 4)  // the segments
596                 + 3  // the separators
597                 + 1 + 5; // the port
598             let mut buf = [0; IPV4_SOCKET_BUF_LEN];
599             let mut buf_slice = &mut buf[..];
600
601             // Unwrap is fine because writing to a sufficiently-sized
602             // buffer is infallible
603             write!(buf_slice, "{}:{}", self.ip(), self.port()).unwrap();
604             let len = IPV4_SOCKET_BUF_LEN - buf_slice.len();
605
606             // This unsafe is OK because we know what is being written to the buffer
607             let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
608             f.pad(buf)
609         }
610     }
611 }
612
613 #[stable(feature = "rust1", since = "1.0.0")]
614 impl fmt::Debug for SocketAddrV4 {
615     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
616         fmt::Display::fmt(self, fmt)
617     }
618 }
619
620 #[stable(feature = "rust1", since = "1.0.0")]
621 impl fmt::Display for SocketAddrV6 {
622     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623         // Fast path: if there's no alignment stuff, write to the output
624         // buffer directly
625         if f.precision().is_none() && f.width().is_none() {
626             match self.scope_id() {
627                 0 => write!(f, "[{}]:{}", self.ip(), self.port()),
628                 scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
629             }
630         } else {
631             const IPV6_SOCKET_BUF_LEN: usize = (4 * 8)  // The address
632             + 7  // The colon separators
633             + 2  // The brackets
634             + 1 + 10 // The scope id
635             + 1 + 5; // The port
636
637             let mut buf = [0; IPV6_SOCKET_BUF_LEN];
638             let mut buf_slice = &mut buf[..];
639
640             match self.scope_id() {
641                 0 => write!(buf_slice, "[{}]:{}", self.ip(), self.port()),
642                 scope_id => write!(buf_slice, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
643             }
644             // Unwrap is fine because writing to a sufficiently-sized
645             // buffer is infallible
646             .unwrap();
647             let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
648
649             // This unsafe is OK because we know what is being written to the buffer
650             let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
651             f.pad(buf)
652         }
653     }
654 }
655
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl fmt::Debug for SocketAddrV6 {
658     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
659         fmt::Display::fmt(self, fmt)
660     }
661 }
662
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl Clone for SocketAddrV4 {
665     fn clone(&self) -> SocketAddrV4 {
666         *self
667     }
668 }
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl Clone for SocketAddrV6 {
671     fn clone(&self) -> SocketAddrV6 {
672         *self
673     }
674 }
675
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl PartialEq for SocketAddrV4 {
678     fn eq(&self, other: &SocketAddrV4) -> bool {
679         self.inner.sin_port == other.inner.sin_port
680             && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
681     }
682 }
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl PartialEq for SocketAddrV6 {
685     fn eq(&self, other: &SocketAddrV6) -> bool {
686         self.inner.sin6_port == other.inner.sin6_port
687             && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
688             && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
689             && self.inner.sin6_scope_id == other.inner.sin6_scope_id
690     }
691 }
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl Eq for SocketAddrV4 {}
694 #[stable(feature = "rust1", since = "1.0.0")]
695 impl Eq for SocketAddrV6 {}
696
697 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
698 impl PartialOrd for SocketAddrV4 {
699     fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
700         Some(self.cmp(other))
701     }
702 }
703
704 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
705 impl PartialOrd for SocketAddrV6 {
706     fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
707         Some(self.cmp(other))
708     }
709 }
710
711 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
712 impl Ord for SocketAddrV4 {
713     fn cmp(&self, other: &SocketAddrV4) -> Ordering {
714         self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
715     }
716 }
717
718 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
719 impl Ord for SocketAddrV6 {
720     fn cmp(&self, other: &SocketAddrV6) -> Ordering {
721         self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
722     }
723 }
724
725 #[stable(feature = "rust1", since = "1.0.0")]
726 impl hash::Hash for SocketAddrV4 {
727     fn hash<H: hash::Hasher>(&self, s: &mut H) {
728         (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
729     }
730 }
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl hash::Hash for SocketAddrV6 {
733     fn hash<H: hash::Hasher>(&self, s: &mut H) {
734         (
735             self.inner.sin6_port,
736             &self.inner.sin6_addr.s6_addr,
737             self.inner.sin6_flowinfo,
738             self.inner.sin6_scope_id,
739         )
740             .hash(s)
741     }
742 }
743
744 /// A trait for objects which can be converted or resolved to one or more
745 /// [`SocketAddr`] values.
746 ///
747 /// This trait is used for generic address resolution when constructing network
748 /// objects. By default it is implemented for the following types:
749 ///
750 ///  * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
751 ///
752 ///  * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
753 ///    `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
754 ///    [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
755 ///
756 ///  * `(`[`&str`]`, `[`u16`]`)`: [`&str`] should be either a string representation
757 ///    of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
758 ///    name. [`u16`] is the port number.
759 ///
760 ///  * [`&str`]: the string should be either a string representation of a
761 ///    [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
762 ///    `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
763 ///
764 /// This trait allows constructing network objects like [`TcpStream`] or
765 /// [`UdpSocket`] easily with values of various types for the bind/connection
766 /// address. It is needed because sometimes one type is more appropriate than
767 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
768 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
769 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
770 /// some other type (e.g., a string) just for it to be converted back to
771 /// [`SocketAddr`] in constructor methods is pointless.
772 ///
773 /// Addresses returned by the operating system that are not IP addresses are
774 /// silently ignored.
775 ///
776 /// [`FromStr`]: crate::str::FromStr
777 /// [`&str`]: str
778 /// [`TcpStream`]: crate::net::TcpStream
779 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
780 /// [`UdpSocket`]: crate::net::UdpSocket
781 ///
782 /// # Examples
783 ///
784 /// Creating a [`SocketAddr`] iterator that yields one item:
785 ///
786 /// ```
787 /// use std::net::{ToSocketAddrs, SocketAddr};
788 ///
789 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
790 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
791 ///
792 /// assert_eq!(Some(addr), addrs_iter.next());
793 /// assert!(addrs_iter.next().is_none());
794 /// ```
795 ///
796 /// Creating a [`SocketAddr`] iterator from a hostname:
797 ///
798 /// ```no_run
799 /// use std::net::{SocketAddr, ToSocketAddrs};
800 ///
801 /// // assuming 'localhost' resolves to 127.0.0.1
802 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
803 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
804 /// assert!(addrs_iter.next().is_none());
805 ///
806 /// // assuming 'foo' does not resolve
807 /// assert!("foo:443".to_socket_addrs().is_err());
808 /// ```
809 ///
810 /// Creating a [`SocketAddr`] iterator that yields multiple items:
811 ///
812 /// ```
813 /// use std::net::{SocketAddr, ToSocketAddrs};
814 ///
815 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
816 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
817 /// let addrs = vec![addr1, addr2];
818 ///
819 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
820 ///
821 /// assert_eq!(Some(addr1), addrs_iter.next());
822 /// assert_eq!(Some(addr2), addrs_iter.next());
823 /// assert!(addrs_iter.next().is_none());
824 /// ```
825 ///
826 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
827 /// socket address `&str` (missing the port):
828 ///
829 /// ```
830 /// use std::io;
831 /// use std::net::ToSocketAddrs;
832 ///
833 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
834 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
835 /// ```
836 ///
837 /// [`TcpStream::connect`] is an example of an function that utilizes
838 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
839 /// different types:
840 ///
841 /// ```no_run
842 /// use std::net::{TcpStream, Ipv4Addr};
843 ///
844 /// let stream = TcpStream::connect(("127.0.0.1", 443));
845 /// // or
846 /// let stream = TcpStream::connect("127.0.0.1:443");
847 /// // or
848 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
849 /// ```
850 ///
851 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
852 #[stable(feature = "rust1", since = "1.0.0")]
853 pub trait ToSocketAddrs {
854     /// Returned iterator over socket addresses which this type may correspond
855     /// to.
856     #[stable(feature = "rust1", since = "1.0.0")]
857     type Iter: Iterator<Item = SocketAddr>;
858
859     /// Converts this object to an iterator of resolved `SocketAddr`s.
860     ///
861     /// The returned iterator may not actually yield any values depending on the
862     /// outcome of any resolution performed.
863     ///
864     /// Note that this function may block the current thread while resolution is
865     /// performed.
866     #[stable(feature = "rust1", since = "1.0.0")]
867     fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
868 }
869
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl ToSocketAddrs for SocketAddr {
872     type Iter = option::IntoIter<SocketAddr>;
873     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
874         Ok(Some(*self).into_iter())
875     }
876 }
877
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl ToSocketAddrs for SocketAddrV4 {
880     type Iter = option::IntoIter<SocketAddr>;
881     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
882         SocketAddr::V4(*self).to_socket_addrs()
883     }
884 }
885
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl ToSocketAddrs for SocketAddrV6 {
888     type Iter = option::IntoIter<SocketAddr>;
889     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
890         SocketAddr::V6(*self).to_socket_addrs()
891     }
892 }
893
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl ToSocketAddrs for (IpAddr, u16) {
896     type Iter = option::IntoIter<SocketAddr>;
897     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
898         let (ip, port) = *self;
899         match ip {
900             IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
901             IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
902         }
903     }
904 }
905
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl ToSocketAddrs for (Ipv4Addr, u16) {
908     type Iter = option::IntoIter<SocketAddr>;
909     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
910         let (ip, port) = *self;
911         SocketAddrV4::new(ip, port).to_socket_addrs()
912     }
913 }
914
915 #[stable(feature = "rust1", since = "1.0.0")]
916 impl ToSocketAddrs for (Ipv6Addr, u16) {
917     type Iter = option::IntoIter<SocketAddr>;
918     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
919         let (ip, port) = *self;
920         SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
921     }
922 }
923
924 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
925     let p = lh.port();
926     let v: Vec<_> = lh
927         .map(|mut a| {
928             a.set_port(p);
929             a
930         })
931         .collect();
932     Ok(v.into_iter())
933 }
934
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl ToSocketAddrs for (&str, u16) {
937     type Iter = vec::IntoIter<SocketAddr>;
938     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
939         let (host, port) = *self;
940
941         // try to parse the host as a regular IP address first
942         if let Ok(addr) = host.parse::<Ipv4Addr>() {
943             let addr = SocketAddrV4::new(addr, port);
944             return Ok(vec![SocketAddr::V4(addr)].into_iter());
945         }
946         if let Ok(addr) = host.parse::<Ipv6Addr>() {
947             let addr = SocketAddrV6::new(addr, port, 0, 0);
948             return Ok(vec![SocketAddr::V6(addr)].into_iter());
949         }
950
951         resolve_socket_addr((host, port).try_into()?)
952     }
953 }
954
955 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
956 impl ToSocketAddrs for (String, u16) {
957     type Iter = vec::IntoIter<SocketAddr>;
958     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
959         (&*self.0, self.1).to_socket_addrs()
960     }
961 }
962
963 // accepts strings like 'localhost:12345'
964 #[stable(feature = "rust1", since = "1.0.0")]
965 impl ToSocketAddrs for str {
966     type Iter = vec::IntoIter<SocketAddr>;
967     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
968         // try to parse as a regular SocketAddr first
969         if let Ok(addr) = self.parse() {
970             return Ok(vec![addr].into_iter());
971         }
972
973         resolve_socket_addr(self.try_into()?)
974     }
975 }
976
977 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
978 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
979     type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
980
981     fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
982         Ok(self.iter().cloned())
983     }
984 }
985
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
988     type Iter = T::Iter;
989     fn to_socket_addrs(&self) -> io::Result<T::Iter> {
990         (**self).to_socket_addrs()
991     }
992 }
993
994 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
995 impl ToSocketAddrs for String {
996     type Iter = vec::IntoIter<SocketAddr>;
997     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
998         (&**self).to_socket_addrs()
999     }
1000 }