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