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