]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/ip.rs
Add documentation for `Ipv6MulticastScope`
[rust.git] / library / std / src / net / ip.rs
1 // Tests for this module
2 #[cfg(all(test, not(target_os = "emscripten")))]
3 mod tests;
4
5 use crate::cmp::Ordering;
6 use crate::fmt::{self, Write as FmtWrite};
7 use crate::hash;
8 use crate::io::Write as IoWrite;
9 use crate::mem::transmute;
10 use crate::sys::net::netc as c;
11 use crate::sys_common::{AsInner, FromInner, IntoInner};
12
13 /// An IP address, either IPv4 or IPv6.
14 ///
15 /// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
16 /// respective documentation for more details.
17 ///
18 /// The size of an `IpAddr` instance may vary depending on the target operating
19 /// system.
20 ///
21 /// # Examples
22 ///
23 /// ```
24 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
25 ///
26 /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
27 /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
28 ///
29 /// assert_eq!("127.0.0.1".parse(), Ok(localhost_v4));
30 /// assert_eq!("::1".parse(), Ok(localhost_v6));
31 ///
32 /// assert_eq!(localhost_v4.is_ipv6(), false);
33 /// assert_eq!(localhost_v4.is_ipv4(), true);
34 /// ```
35 #[stable(feature = "ip_addr", since = "1.7.0")]
36 #[derive(Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
37 pub enum IpAddr {
38     /// An IPv4 address.
39     #[stable(feature = "ip_addr", since = "1.7.0")]
40     V4(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv4Addr),
41     /// An IPv6 address.
42     #[stable(feature = "ip_addr", since = "1.7.0")]
43     V6(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv6Addr),
44 }
45
46 /// An IPv4 address.
47 ///
48 /// IPv4 addresses are defined as 32-bit integers in [IETF RFC 791].
49 /// They are usually represented as four octets.
50 ///
51 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
52 ///
53 /// The size of an `Ipv4Addr` struct may vary depending on the target operating
54 /// system.
55 ///
56 /// [IETF RFC 791]: https://tools.ietf.org/html/rfc791
57 ///
58 /// # Textual representation
59 ///
60 /// `Ipv4Addr` provides a [`FromStr`] implementation. The four octets are in decimal
61 /// notation, divided by `.` (this is called "dot-decimal notation").
62 /// Notably, octal numbers and hexadecimal numbers are not allowed per [IETF RFC 6943].
63 ///
64 /// [IETF RFC 6943]: https://tools.ietf.org/html/rfc6943#section-3.1.1
65 /// [`FromStr`]: crate::str::FromStr
66 ///
67 /// # Examples
68 ///
69 /// ```
70 /// use std::net::Ipv4Addr;
71 ///
72 /// let localhost = Ipv4Addr::new(127, 0, 0, 1);
73 /// assert_eq!("127.0.0.1".parse(), Ok(localhost));
74 /// assert_eq!(localhost.is_loopback(), true);
75 /// ```
76 #[derive(Copy)]
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct Ipv4Addr {
79     inner: c::in_addr,
80 }
81
82 /// An IPv6 address.
83 ///
84 /// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
85 /// They are usually represented as eight 16-bit segments.
86 ///
87 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
88 ///
89 /// The size of an `Ipv6Addr` struct may vary depending on the target operating
90 /// system.
91 ///
92 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
93 ///
94 /// # Textual representation
95 ///
96 /// `Ipv6Addr` provides a [`FromStr`] implementation. There are many ways to represent
97 /// an IPv6 address in text, but in general, each segments is written in hexadecimal
98 /// notation, and segments are separated by `:`. For more information, see
99 /// [IETF RFC 5952].
100 ///
101 /// [`FromStr`]: crate::str::FromStr
102 /// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952
103 ///
104 /// # Examples
105 ///
106 /// ```
107 /// use std::net::Ipv6Addr;
108 ///
109 /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
110 /// assert_eq!("::1".parse(), Ok(localhost));
111 /// assert_eq!(localhost.is_loopback(), true);
112 /// ```
113 #[derive(Copy)]
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub struct Ipv6Addr {
116     inner: c::in6_addr,
117 }
118
119 /// Scope of an [IPv6 multicast address] as defined in [IETF RFC 7346 section 2].
120 ///
121 /// # Stability Guarantees
122 ///
123 /// Not all possible values for a multicast scope have been assigned.
124 /// Future RFCs may introduce new scopes, which will be added as variants to this enum;
125 /// because of this the enum is marked as `#[non_exhaustive]`.
126 ///
127 /// # Examples
128 /// ```
129 /// #![feature(ip)]
130 ///
131 /// use std::net::Ipv6Addr;
132 /// use std::net::Ipv6MulticastScope::*;
133 ///
134 /// // An IPv6 multicast address with global scope (`ff0e::`).
135 /// let address = Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0);
136 ///
137 /// // Will print "Global scope".
138 /// match address.multicast_scope() {
139 ///     Some(InterfaceLocal) => println!("Interface-Local scope"),
140 ///     Some(LinkLocal) => println!("Link-Local scope"),
141 ///     Some(RealmLocal) => println!("Realm-Local scope"),
142 ///     Some(AdminLocal) => println!("Admin-Local scope"),
143 ///     Some(SiteLocal) => println!("Site-Local scope"),
144 ///     Some(OrganizationLocal) => println!("Organization-Local scope"),
145 ///     Some(Global) => println!("Global scope"),
146 ///     Some(_) => println!("Unknown scope"),
147 ///     None => println!("Not a multicast address!")
148 /// }
149 ///
150 /// ```
151 ///
152 /// [IPv6 multicast address]: Ipv6Addr
153 /// [IETF RFC 7346 section 2]: https://tools.ietf.org/html/rfc7346#section-2
154 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
155 #[unstable(feature = "ip", issue = "27709")]
156 #[non_exhaustive]
157 pub enum Ipv6MulticastScope {
158     /// Interface-Local scope.
159     InterfaceLocal,
160     /// Link-Local scope.
161     LinkLocal,
162     /// Realm-Local scope.
163     RealmLocal,
164     /// Admin-Local scope.
165     AdminLocal,
166     /// Site-Local scope.
167     SiteLocal,
168     /// Organization-Local scope.
169     OrganizationLocal,
170     /// Global scope.
171     Global,
172 }
173
174 impl IpAddr {
175     /// Returns [`true`] for the special 'unspecified' address.
176     ///
177     /// See the documentation for [`Ipv4Addr::is_unspecified()`] and
178     /// [`Ipv6Addr::is_unspecified()`] for more details.
179     ///
180     /// # Examples
181     ///
182     /// ```
183     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
184     ///
185     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
186     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
187     /// ```
188     #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
189     #[stable(feature = "ip_shared", since = "1.12.0")]
190     #[inline]
191     pub const fn is_unspecified(&self) -> bool {
192         match self {
193             IpAddr::V4(ip) => ip.is_unspecified(),
194             IpAddr::V6(ip) => ip.is_unspecified(),
195         }
196     }
197
198     /// Returns [`true`] if this is a loopback address.
199     ///
200     /// See the documentation for [`Ipv4Addr::is_loopback()`] and
201     /// [`Ipv6Addr::is_loopback()`] for more details.
202     ///
203     /// # Examples
204     ///
205     /// ```
206     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
207     ///
208     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
209     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
210     /// ```
211     #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
212     #[stable(feature = "ip_shared", since = "1.12.0")]
213     #[inline]
214     pub const fn is_loopback(&self) -> bool {
215         match self {
216             IpAddr::V4(ip) => ip.is_loopback(),
217             IpAddr::V6(ip) => ip.is_loopback(),
218         }
219     }
220
221     /// Returns [`true`] if the address appears to be globally routable.
222     ///
223     /// See the documentation for [`Ipv4Addr::is_global()`] and
224     /// [`Ipv6Addr::is_global()`] for more details.
225     ///
226     /// # Examples
227     ///
228     /// ```
229     /// #![feature(ip)]
230     ///
231     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
232     ///
233     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true);
234     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true);
235     /// ```
236     #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
237     #[unstable(feature = "ip", issue = "27709")]
238     #[inline]
239     pub const fn is_global(&self) -> bool {
240         match self {
241             IpAddr::V4(ip) => ip.is_global(),
242             IpAddr::V6(ip) => ip.is_global(),
243         }
244     }
245
246     /// Returns [`true`] if this is a multicast address.
247     ///
248     /// See the documentation for [`Ipv4Addr::is_multicast()`] and
249     /// [`Ipv6Addr::is_multicast()`] for more details.
250     ///
251     /// # Examples
252     ///
253     /// ```
254     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
255     ///
256     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
257     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
258     /// ```
259     #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
260     #[stable(feature = "ip_shared", since = "1.12.0")]
261     #[inline]
262     pub const fn is_multicast(&self) -> bool {
263         match self {
264             IpAddr::V4(ip) => ip.is_multicast(),
265             IpAddr::V6(ip) => ip.is_multicast(),
266         }
267     }
268
269     /// Returns [`true`] if this address is in a range designated for documentation.
270     ///
271     /// See the documentation for [`Ipv4Addr::is_documentation()`] and
272     /// [`Ipv6Addr::is_documentation()`] for more details.
273     ///
274     /// # Examples
275     ///
276     /// ```
277     /// #![feature(ip)]
278     ///
279     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
280     ///
281     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
282     /// assert_eq!(
283     ///     IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(),
284     ///     true
285     /// );
286     /// ```
287     #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
288     #[unstable(feature = "ip", issue = "27709")]
289     #[inline]
290     pub const fn is_documentation(&self) -> bool {
291         match self {
292             IpAddr::V4(ip) => ip.is_documentation(),
293             IpAddr::V6(ip) => ip.is_documentation(),
294         }
295     }
296
297     /// Returns [`true`] if this address is an [`IPv4` address], and [`false`]
298     /// otherwise.
299     ///
300     /// [`IPv4` address]: IpAddr::V4
301     ///
302     /// # Examples
303     ///
304     /// ```
305     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
306     ///
307     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
308     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false);
309     /// ```
310     #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
311     #[stable(feature = "ipaddr_checker", since = "1.16.0")]
312     #[inline]
313     pub const fn is_ipv4(&self) -> bool {
314         matches!(self, IpAddr::V4(_))
315     }
316
317     /// Returns [`true`] if this address is an [`IPv6` address], and [`false`]
318     /// otherwise.
319     ///
320     /// [`IPv6` address]: IpAddr::V6
321     ///
322     /// # Examples
323     ///
324     /// ```
325     /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
326     ///
327     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
328     /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true);
329     /// ```
330     #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
331     #[stable(feature = "ipaddr_checker", since = "1.16.0")]
332     #[inline]
333     pub const fn is_ipv6(&self) -> bool {
334         matches!(self, IpAddr::V6(_))
335     }
336 }
337
338 impl Ipv4Addr {
339     /// Creates a new IPv4 address from four eight-bit octets.
340     ///
341     /// The result will represent the IP address `a`.`b`.`c`.`d`.
342     ///
343     /// # Examples
344     ///
345     /// ```
346     /// use std::net::Ipv4Addr;
347     ///
348     /// let addr = Ipv4Addr::new(127, 0, 0, 1);
349     /// ```
350     #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
351     #[stable(feature = "rust1", since = "1.0.0")]
352     #[inline]
353     pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
354         // `s_addr` is stored as BE on all machine and the array is in BE order.
355         // So the native endian conversion method is used so that it's never swapped.
356         Ipv4Addr { inner: c::in_addr { s_addr: u32::from_ne_bytes([a, b, c, d]) } }
357     }
358
359     /// An IPv4 address with the address pointing to localhost: `127.0.0.1`
360     ///
361     /// # Examples
362     ///
363     /// ```
364     /// use std::net::Ipv4Addr;
365     ///
366     /// let addr = Ipv4Addr::LOCALHOST;
367     /// assert_eq!(addr, Ipv4Addr::new(127, 0, 0, 1));
368     /// ```
369     #[stable(feature = "ip_constructors", since = "1.30.0")]
370     pub const LOCALHOST: Self = Ipv4Addr::new(127, 0, 0, 1);
371
372     /// An IPv4 address representing an unspecified address: `0.0.0.0`
373     ///
374     /// This corresponds to the constant `INADDR_ANY` in other languages.
375     ///
376     /// # Examples
377     ///
378     /// ```
379     /// use std::net::Ipv4Addr;
380     ///
381     /// let addr = Ipv4Addr::UNSPECIFIED;
382     /// assert_eq!(addr, Ipv4Addr::new(0, 0, 0, 0));
383     /// ```
384     #[doc(alias = "INADDR_ANY")]
385     #[stable(feature = "ip_constructors", since = "1.30.0")]
386     pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0);
387
388     /// An IPv4 address representing the broadcast address: `255.255.255.255`
389     ///
390     /// # Examples
391     ///
392     /// ```
393     /// use std::net::Ipv4Addr;
394     ///
395     /// let addr = Ipv4Addr::BROADCAST;
396     /// assert_eq!(addr, Ipv4Addr::new(255, 255, 255, 255));
397     /// ```
398     #[stable(feature = "ip_constructors", since = "1.30.0")]
399     pub const BROADCAST: Self = Ipv4Addr::new(255, 255, 255, 255);
400
401     /// Returns the four eight-bit integers that make up this address.
402     ///
403     /// # Examples
404     ///
405     /// ```
406     /// use std::net::Ipv4Addr;
407     ///
408     /// let addr = Ipv4Addr::new(127, 0, 0, 1);
409     /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
410     /// ```
411     #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
412     #[stable(feature = "rust1", since = "1.0.0")]
413     #[inline]
414     pub const fn octets(&self) -> [u8; 4] {
415         // This returns the order we want because s_addr is stored in big-endian.
416         self.inner.s_addr.to_ne_bytes()
417     }
418
419     /// Returns [`true`] for the special 'unspecified' address (`0.0.0.0`).
420     ///
421     /// This property is defined in _UNIX Network Programming, Second Edition_,
422     /// W. Richard Stevens, p. 891; see also [ip7].
423     ///
424     /// [ip7]: https://man7.org/linux/man-pages/man7/ip.7.html
425     ///
426     /// # Examples
427     ///
428     /// ```
429     /// use std::net::Ipv4Addr;
430     ///
431     /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
432     /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
433     /// ```
434     #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
435     #[stable(feature = "ip_shared", since = "1.12.0")]
436     #[inline]
437     pub const fn is_unspecified(&self) -> bool {
438         self.inner.s_addr == 0
439     }
440
441     /// Returns [`true`] if this is a loopback address (`127.0.0.0/8`).
442     ///
443     /// This property is defined by [IETF RFC 1122].
444     ///
445     /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
446     ///
447     /// # Examples
448     ///
449     /// ```
450     /// use std::net::Ipv4Addr;
451     ///
452     /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
453     /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
454     /// ```
455     #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
456     #[stable(since = "1.7.0", feature = "ip_17")]
457     #[inline]
458     pub const fn is_loopback(&self) -> bool {
459         self.octets()[0] == 127
460     }
461
462     /// Returns [`true`] if this is a private address.
463     ///
464     /// The private address ranges are defined in [IETF RFC 1918] and include:
465     ///
466     ///  - `10.0.0.0/8`
467     ///  - `172.16.0.0/12`
468     ///  - `192.168.0.0/16`
469     ///
470     /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// use std::net::Ipv4Addr;
476     ///
477     /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
478     /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
479     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
480     /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
481     /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
482     /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
483     /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
484     /// ```
485     #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
486     #[stable(since = "1.7.0", feature = "ip_17")]
487     #[inline]
488     pub const fn is_private(&self) -> bool {
489         match self.octets() {
490             [10, ..] => true,
491             [172, b, ..] if b >= 16 && b <= 31 => true,
492             [192, 168, ..] => true,
493             _ => false,
494         }
495     }
496
497     /// Returns [`true`] if the address is link-local (`169.254.0.0/16`).
498     ///
499     /// This property is defined by [IETF RFC 3927].
500     ///
501     /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
502     ///
503     /// # Examples
504     ///
505     /// ```
506     /// use std::net::Ipv4Addr;
507     ///
508     /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
509     /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
510     /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
511     /// ```
512     #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
513     #[stable(since = "1.7.0", feature = "ip_17")]
514     #[inline]
515     pub const fn is_link_local(&self) -> bool {
516         matches!(self.octets(), [169, 254, ..])
517     }
518
519     /// Returns [`true`] if the address appears to be globally routable.
520     /// See [iana-ipv4-special-registry][ipv4-sr].
521     ///
522     /// The following return [`false`]:
523     ///
524     /// - private addresses (see [`Ipv4Addr::is_private()`])
525     /// - the loopback address (see [`Ipv4Addr::is_loopback()`])
526     /// - the link-local address (see [`Ipv4Addr::is_link_local()`])
527     /// - the broadcast address (see [`Ipv4Addr::is_broadcast()`])
528     /// - addresses used for documentation (see [`Ipv4Addr::is_documentation()`])
529     /// - the unspecified address (see [`Ipv4Addr::is_unspecified()`]), and the whole
530     ///   `0.0.0.0/8` block
531     /// - addresses reserved for future protocols (see
532     /// [`Ipv4Addr::is_ietf_protocol_assignment()`], except
533     /// `192.0.0.9/32` and `192.0.0.10/32` which are globally routable
534     /// - addresses reserved for future use (see [`Ipv4Addr::is_reserved()`]
535     /// - addresses reserved for networking devices benchmarking (see
536     /// [`Ipv4Addr::is_benchmarking()`])
537     ///
538     /// [ipv4-sr]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
539     ///
540     /// # Examples
541     ///
542     /// ```
543     /// #![feature(ip)]
544     ///
545     /// use std::net::Ipv4Addr;
546     ///
547     /// // private addresses are not global
548     /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
549     /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
550     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
551     ///
552     /// // the 0.0.0.0/8 block is not global
553     /// assert_eq!(Ipv4Addr::new(0, 1, 2, 3).is_global(), false);
554     /// // in particular, the unspecified address is not global
555     /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_global(), false);
556     ///
557     /// // the loopback address is not global
558     /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_global(), false);
559     ///
560     /// // link local addresses are not global
561     /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
562     ///
563     /// // the broadcast address is not global
564     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_global(), false);
565     ///
566     /// // the address space designated for documentation is not global
567     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
568     /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
569     /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
570     ///
571     /// // shared addresses are not global
572     /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
573     ///
574     /// // addresses reserved for protocol assignment are not global
575     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_global(), false);
576     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_global(), false);
577     ///
578     /// // addresses reserved for future use are not global
579     /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
580     ///
581     /// // addresses reserved for network devices benchmarking are not global
582     /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
583     ///
584     /// // All the other addresses are global
585     /// assert_eq!(Ipv4Addr::new(1, 1, 1, 1).is_global(), true);
586     /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
587     /// ```
588     #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
589     #[unstable(feature = "ip", issue = "27709")]
590     #[inline]
591     pub const fn is_global(&self) -> bool {
592         // check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two
593         // globally routable addresses in the 192.0.0.0/24 range.
594         if u32::from_be_bytes(self.octets()) == 0xc0000009
595             || u32::from_be_bytes(self.octets()) == 0xc000000a
596         {
597             return true;
598         }
599         !self.is_private()
600             && !self.is_loopback()
601             && !self.is_link_local()
602             && !self.is_broadcast()
603             && !self.is_documentation()
604             && !self.is_shared()
605             && !self.is_ietf_protocol_assignment()
606             && !self.is_reserved()
607             && !self.is_benchmarking()
608             // Make sure the address is not in 0.0.0.0/8
609             && self.octets()[0] != 0
610     }
611
612     /// Returns [`true`] if this address is part of the Shared Address Space defined in
613     /// [IETF RFC 6598] (`100.64.0.0/10`).
614     ///
615     /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
616     ///
617     /// # Examples
618     ///
619     /// ```
620     /// #![feature(ip)]
621     /// use std::net::Ipv4Addr;
622     ///
623     /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
624     /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
625     /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
626     /// ```
627     #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
628     #[unstable(feature = "ip", issue = "27709")]
629     #[inline]
630     pub const fn is_shared(&self) -> bool {
631         self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
632     }
633
634     /// Returns [`true`] if this address is part of `192.0.0.0/24`, which is reserved to
635     /// IANA for IETF protocol assignments, as documented in [IETF RFC 6890].
636     ///
637     /// Note that parts of this block are in use:
638     ///
639     /// - `192.0.0.8/32` is the "IPv4 dummy address" (see [IETF RFC 7600])
640     /// - `192.0.0.9/32` is the "Port Control Protocol Anycast" (see [IETF RFC 7723])
641     /// - `192.0.0.10/32` is used for NAT traversal (see [IETF RFC 8155])
642     ///
643     /// [IETF RFC 6890]: https://tools.ietf.org/html/rfc6890
644     /// [IETF RFC 7600]: https://tools.ietf.org/html/rfc7600
645     /// [IETF RFC 7723]: https://tools.ietf.org/html/rfc7723
646     /// [IETF RFC 8155]: https://tools.ietf.org/html/rfc8155
647     ///
648     /// # Examples
649     ///
650     /// ```
651     /// #![feature(ip)]
652     /// use std::net::Ipv4Addr;
653     ///
654     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_ietf_protocol_assignment(), true);
655     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 8).is_ietf_protocol_assignment(), true);
656     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 9).is_ietf_protocol_assignment(), true);
657     /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_ietf_protocol_assignment(), true);
658     /// assert_eq!(Ipv4Addr::new(192, 0, 1, 0).is_ietf_protocol_assignment(), false);
659     /// assert_eq!(Ipv4Addr::new(191, 255, 255, 255).is_ietf_protocol_assignment(), false);
660     /// ```
661     #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
662     #[unstable(feature = "ip", issue = "27709")]
663     #[inline]
664     pub const fn is_ietf_protocol_assignment(&self) -> bool {
665         self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0
666     }
667
668     /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
669     /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
670     /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
671     ///
672     /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
673     /// [errata 423]: https://www.rfc-editor.org/errata/eid423
674     ///
675     /// # Examples
676     ///
677     /// ```
678     /// #![feature(ip)]
679     /// use std::net::Ipv4Addr;
680     ///
681     /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
682     /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
683     /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
684     /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
685     /// ```
686     #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
687     #[unstable(feature = "ip", issue = "27709")]
688     #[inline]
689     pub const fn is_benchmarking(&self) -> bool {
690         self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
691     }
692
693     /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
694     /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
695     /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
696     /// it is obviously not reserved for future use.
697     ///
698     /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
699     ///
700     /// # Warning
701     ///
702     /// As IANA assigns new addresses, this method will be
703     /// updated. This may result in non-reserved addresses being
704     /// treated as reserved in code that relies on an outdated version
705     /// of this method.
706     ///
707     /// # Examples
708     ///
709     /// ```
710     /// #![feature(ip)]
711     /// use std::net::Ipv4Addr;
712     ///
713     /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
714     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
715     ///
716     /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
717     /// // The broadcast address is not considered as reserved for future use by this implementation
718     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
719     /// ```
720     #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
721     #[unstable(feature = "ip", issue = "27709")]
722     #[inline]
723     pub const fn is_reserved(&self) -> bool {
724         self.octets()[0] & 240 == 240 && !self.is_broadcast()
725     }
726
727     /// Returns [`true`] if this is a multicast address (`224.0.0.0/4`).
728     ///
729     /// Multicast addresses have a most significant octet between `224` and `239`,
730     /// and is defined by [IETF RFC 5771].
731     ///
732     /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
733     ///
734     /// # Examples
735     ///
736     /// ```
737     /// use std::net::Ipv4Addr;
738     ///
739     /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
740     /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
741     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
742     /// ```
743     #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
744     #[stable(since = "1.7.0", feature = "ip_17")]
745     #[inline]
746     pub const fn is_multicast(&self) -> bool {
747         self.octets()[0] >= 224 && self.octets()[0] <= 239
748     }
749
750     /// Returns [`true`] if this is a broadcast address (`255.255.255.255`).
751     ///
752     /// A broadcast address has all octets set to `255` as defined in [IETF RFC 919].
753     ///
754     /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
755     ///
756     /// # Examples
757     ///
758     /// ```
759     /// use std::net::Ipv4Addr;
760     ///
761     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
762     /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
763     /// ```
764     #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
765     #[stable(since = "1.7.0", feature = "ip_17")]
766     #[inline]
767     pub const fn is_broadcast(&self) -> bool {
768         u32::from_be_bytes(self.octets()) == u32::from_be_bytes(Self::BROADCAST.octets())
769     }
770
771     /// Returns [`true`] if this address is in a range designated for documentation.
772     ///
773     /// This is defined in [IETF RFC 5737]:
774     ///
775     /// - `192.0.2.0/24` (TEST-NET-1)
776     /// - `198.51.100.0/24` (TEST-NET-2)
777     /// - `203.0.113.0/24` (TEST-NET-3)
778     ///
779     /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
780     ///
781     /// # Examples
782     ///
783     /// ```
784     /// use std::net::Ipv4Addr;
785     ///
786     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
787     /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
788     /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
789     /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
790     /// ```
791     #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
792     #[stable(since = "1.7.0", feature = "ip_17")]
793     #[inline]
794     pub const fn is_documentation(&self) -> bool {
795         match self.octets() {
796             [192, 0, 2, _] => true,
797             [198, 51, 100, _] => true,
798             [203, 0, 113, _] => true,
799             _ => false,
800         }
801     }
802
803     /// Converts this address to an IPv4-compatible [`IPv6` address].
804     ///
805     /// `a.b.c.d` becomes `::a.b.c.d`
806     ///
807     /// This isn't typically the method you want; these addresses don't typically
808     /// function on modern systems. Use `to_ipv6_mapped` instead.
809     ///
810     /// [`IPv6` address]: Ipv6Addr
811     ///
812     /// # Examples
813     ///
814     /// ```
815     /// use std::net::{Ipv4Addr, Ipv6Addr};
816     ///
817     /// assert_eq!(
818     ///     Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
819     ///     Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x2ff)
820     /// );
821     /// ```
822     #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
823     #[stable(feature = "rust1", since = "1.0.0")]
824     #[inline]
825     pub const fn to_ipv6_compatible(&self) -> Ipv6Addr {
826         let [a, b, c, d] = self.octets();
827         Ipv6Addr {
828             inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] },
829         }
830     }
831
832     /// Converts this address to an IPv4-mapped [`IPv6` address].
833     ///
834     /// `a.b.c.d` becomes `::ffff:a.b.c.d`
835     ///
836     /// [`IPv6` address]: Ipv6Addr
837     ///
838     /// # Examples
839     ///
840     /// ```
841     /// use std::net::{Ipv4Addr, Ipv6Addr};
842     ///
843     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
844     ///            Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff));
845     /// ```
846     #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
847     #[stable(feature = "rust1", since = "1.0.0")]
848     #[inline]
849     pub const fn to_ipv6_mapped(&self) -> Ipv6Addr {
850         let [a, b, c, d] = self.octets();
851         Ipv6Addr {
852             inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] },
853         }
854     }
855 }
856
857 #[stable(feature = "ip_addr", since = "1.7.0")]
858 impl fmt::Display for IpAddr {
859     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
860         match self {
861             IpAddr::V4(ip) => ip.fmt(fmt),
862             IpAddr::V6(ip) => ip.fmt(fmt),
863         }
864     }
865 }
866
867 #[stable(feature = "ip_addr", since = "1.7.0")]
868 impl fmt::Debug for IpAddr {
869     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
870         fmt::Display::fmt(self, fmt)
871     }
872 }
873
874 #[stable(feature = "ip_from_ip", since = "1.16.0")]
875 impl From<Ipv4Addr> for IpAddr {
876     /// Copies this address to a new `IpAddr::V4`.
877     ///
878     /// # Examples
879     ///
880     /// ```
881     /// use std::net::{IpAddr, Ipv4Addr};
882     ///
883     /// let addr = Ipv4Addr::new(127, 0, 0, 1);
884     ///
885     /// assert_eq!(
886     ///     IpAddr::V4(addr),
887     ///     IpAddr::from(addr)
888     /// )
889     /// ```
890     #[inline]
891     fn from(ipv4: Ipv4Addr) -> IpAddr {
892         IpAddr::V4(ipv4)
893     }
894 }
895
896 #[stable(feature = "ip_from_ip", since = "1.16.0")]
897 impl From<Ipv6Addr> for IpAddr {
898     /// Copies this address to a new `IpAddr::V6`.
899     ///
900     /// # Examples
901     ///
902     /// ```
903     /// use std::net::{IpAddr, Ipv6Addr};
904     ///
905     /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
906     ///
907     /// assert_eq!(
908     ///     IpAddr::V6(addr),
909     ///     IpAddr::from(addr)
910     /// );
911     /// ```
912     #[inline]
913     fn from(ipv6: Ipv6Addr) -> IpAddr {
914         IpAddr::V6(ipv6)
915     }
916 }
917
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl fmt::Display for Ipv4Addr {
920     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
921         let octets = self.octets();
922         // Fast Path: if there's no alignment stuff, write directly to the buffer
923         if fmt.precision().is_none() && fmt.width().is_none() {
924             write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
925         } else {
926             const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
927             let mut buf = [0u8; IPV4_BUF_LEN];
928             let mut buf_slice = &mut buf[..];
929
930             // Note: The call to write should never fail, hence the unwrap
931             write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
932             let len = IPV4_BUF_LEN - buf_slice.len();
933
934             // This unsafe is OK because we know what is being written to the buffer
935             let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
936             fmt.pad(buf)
937         }
938     }
939 }
940
941 #[stable(feature = "rust1", since = "1.0.0")]
942 impl fmt::Debug for Ipv4Addr {
943     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
944         fmt::Display::fmt(self, fmt)
945     }
946 }
947
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl Clone for Ipv4Addr {
950     #[inline]
951     fn clone(&self) -> Ipv4Addr {
952         *self
953     }
954 }
955
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl PartialEq for Ipv4Addr {
958     #[inline]
959     fn eq(&self, other: &Ipv4Addr) -> bool {
960         self.inner.s_addr == other.inner.s_addr
961     }
962 }
963
964 #[stable(feature = "ip_cmp", since = "1.16.0")]
965 impl PartialEq<Ipv4Addr> for IpAddr {
966     #[inline]
967     fn eq(&self, other: &Ipv4Addr) -> bool {
968         match self {
969             IpAddr::V4(v4) => v4 == other,
970             IpAddr::V6(_) => false,
971         }
972     }
973 }
974
975 #[stable(feature = "ip_cmp", since = "1.16.0")]
976 impl PartialEq<IpAddr> for Ipv4Addr {
977     #[inline]
978     fn eq(&self, other: &IpAddr) -> bool {
979         match other {
980             IpAddr::V4(v4) => self == v4,
981             IpAddr::V6(_) => false,
982         }
983     }
984 }
985
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl Eq for Ipv4Addr {}
988
989 #[stable(feature = "rust1", since = "1.0.0")]
990 impl hash::Hash for Ipv4Addr {
991     #[inline]
992     fn hash<H: hash::Hasher>(&self, s: &mut H) {
993         // NOTE:
994         // * hash in big endian order
995         // * in netbsd, `in_addr` has `repr(packed)`, we need to
996         //   copy `s_addr` to avoid unsafe borrowing
997         { self.inner.s_addr }.hash(s)
998     }
999 }
1000
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl PartialOrd for Ipv4Addr {
1003     #[inline]
1004     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1005         Some(self.cmp(other))
1006     }
1007 }
1008
1009 #[stable(feature = "ip_cmp", since = "1.16.0")]
1010 impl PartialOrd<Ipv4Addr> for IpAddr {
1011     #[inline]
1012     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1013         match self {
1014             IpAddr::V4(v4) => v4.partial_cmp(other),
1015             IpAddr::V6(_) => Some(Ordering::Greater),
1016         }
1017     }
1018 }
1019
1020 #[stable(feature = "ip_cmp", since = "1.16.0")]
1021 impl PartialOrd<IpAddr> for Ipv4Addr {
1022     #[inline]
1023     fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1024         match other {
1025             IpAddr::V4(v4) => self.partial_cmp(v4),
1026             IpAddr::V6(_) => Some(Ordering::Less),
1027         }
1028     }
1029 }
1030
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 impl Ord for Ipv4Addr {
1033     #[inline]
1034     fn cmp(&self, other: &Ipv4Addr) -> Ordering {
1035         // Compare as native endian
1036         u32::from_be(self.inner.s_addr).cmp(&u32::from_be(other.inner.s_addr))
1037     }
1038 }
1039
1040 impl IntoInner<c::in_addr> for Ipv4Addr {
1041     #[inline]
1042     fn into_inner(self) -> c::in_addr {
1043         self.inner
1044     }
1045 }
1046
1047 #[stable(feature = "ip_u32", since = "1.1.0")]
1048 impl From<Ipv4Addr> for u32 {
1049     /// Converts an `Ipv4Addr` into a host byte order `u32`.
1050     ///
1051     /// # Examples
1052     ///
1053     /// ```
1054     /// use std::net::Ipv4Addr;
1055     ///
1056     /// let addr = Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe);
1057     /// assert_eq!(0xcafebabe, u32::from(addr));
1058     /// ```
1059     #[inline]
1060     fn from(ip: Ipv4Addr) -> u32 {
1061         let ip = ip.octets();
1062         u32::from_be_bytes(ip)
1063     }
1064 }
1065
1066 #[stable(feature = "ip_u32", since = "1.1.0")]
1067 impl From<u32> for Ipv4Addr {
1068     /// Converts a host byte order `u32` into an `Ipv4Addr`.
1069     ///
1070     /// # Examples
1071     ///
1072     /// ```
1073     /// use std::net::Ipv4Addr;
1074     ///
1075     /// let addr = Ipv4Addr::from(0xcafebabe);
1076     /// assert_eq!(Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe), addr);
1077     /// ```
1078     #[inline]
1079     fn from(ip: u32) -> Ipv4Addr {
1080         Ipv4Addr::from(ip.to_be_bytes())
1081     }
1082 }
1083
1084 #[stable(feature = "from_slice_v4", since = "1.9.0")]
1085 impl From<[u8; 4]> for Ipv4Addr {
1086     /// Creates an `Ipv4Addr` from a four element byte array.
1087     ///
1088     /// # Examples
1089     ///
1090     /// ```
1091     /// use std::net::Ipv4Addr;
1092     ///
1093     /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1094     /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1095     /// ```
1096     #[inline]
1097     fn from(octets: [u8; 4]) -> Ipv4Addr {
1098         Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])
1099     }
1100 }
1101
1102 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1103 impl From<[u8; 4]> for IpAddr {
1104     /// Creates an `IpAddr::V4` from a four element byte array.
1105     ///
1106     /// # Examples
1107     ///
1108     /// ```
1109     /// use std::net::{IpAddr, Ipv4Addr};
1110     ///
1111     /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1112     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1113     /// ```
1114     #[inline]
1115     fn from(octets: [u8; 4]) -> IpAddr {
1116         IpAddr::V4(Ipv4Addr::from(octets))
1117     }
1118 }
1119
1120 impl Ipv6Addr {
1121     /// Creates a new IPv6 address from eight 16-bit segments.
1122     ///
1123     /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1124     ///
1125     /// # Examples
1126     ///
1127     /// ```
1128     /// use std::net::Ipv6Addr;
1129     ///
1130     /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1131     /// ```
1132     #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1133     #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1134     #[stable(feature = "rust1", since = "1.0.0")]
1135     #[inline]
1136     pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1137         let addr16 = [
1138             a.to_be(),
1139             b.to_be(),
1140             c.to_be(),
1141             d.to_be(),
1142             e.to_be(),
1143             f.to_be(),
1144             g.to_be(),
1145             h.to_be(),
1146         ];
1147         Ipv6Addr {
1148             inner: c::in6_addr {
1149                 // All elements in `addr16` are big endian.
1150                 // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1151                 // rustc_allow_const_fn_unstable: the transmute could be written as stable const
1152                 // code, but that leads to worse code generation (#75085)
1153                 s6_addr: unsafe { transmute::<_, [u8; 16]>(addr16) },
1154             },
1155         }
1156     }
1157
1158     /// An IPv6 address representing localhost: `::1`.
1159     ///
1160     /// # Examples
1161     ///
1162     /// ```
1163     /// use std::net::Ipv6Addr;
1164     ///
1165     /// let addr = Ipv6Addr::LOCALHOST;
1166     /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1167     /// ```
1168     #[stable(feature = "ip_constructors", since = "1.30.0")]
1169     pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1170
1171     /// An IPv6 address representing the unspecified address: `::`
1172     ///
1173     /// # Examples
1174     ///
1175     /// ```
1176     /// use std::net::Ipv6Addr;
1177     ///
1178     /// let addr = Ipv6Addr::UNSPECIFIED;
1179     /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1180     /// ```
1181     #[stable(feature = "ip_constructors", since = "1.30.0")]
1182     pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1183
1184     /// Returns the eight 16-bit segments that make up this address.
1185     ///
1186     /// # Examples
1187     ///
1188     /// ```
1189     /// use std::net::Ipv6Addr;
1190     ///
1191     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1192     ///            [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1193     /// ```
1194     #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1195     #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1196     #[stable(feature = "rust1", since = "1.0.0")]
1197     #[inline]
1198     pub const fn segments(&self) -> [u16; 8] {
1199         // All elements in `s6_addr` must be big endian.
1200         // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1201         // rustc_allow_const_fn_unstable: the transmute could be written as stable const code, but
1202         // that leads to worse code generation (#75085)
1203         let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.inner.s6_addr) };
1204         // We want native endian u16
1205         [
1206             u16::from_be(a),
1207             u16::from_be(b),
1208             u16::from_be(c),
1209             u16::from_be(d),
1210             u16::from_be(e),
1211             u16::from_be(f),
1212             u16::from_be(g),
1213             u16::from_be(h),
1214         ]
1215     }
1216
1217     /// Returns [`true`] for the special 'unspecified' address (`::`).
1218     ///
1219     /// This property is defined in [IETF RFC 4291].
1220     ///
1221     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1222     ///
1223     /// # Examples
1224     ///
1225     /// ```
1226     /// use std::net::Ipv6Addr;
1227     ///
1228     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1229     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1230     /// ```
1231     #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1232     #[stable(since = "1.7.0", feature = "ip_17")]
1233     #[inline]
1234     pub const fn is_unspecified(&self) -> bool {
1235         u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1236     }
1237
1238     /// Returns [`true`] if this is a loopback address (::1).
1239     ///
1240     /// This property is defined in [IETF RFC 4291].
1241     ///
1242     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1243     ///
1244     /// # Examples
1245     ///
1246     /// ```
1247     /// use std::net::Ipv6Addr;
1248     ///
1249     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1250     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1251     /// ```
1252     #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1253     #[stable(since = "1.7.0", feature = "ip_17")]
1254     #[inline]
1255     pub const fn is_loopback(&self) -> bool {
1256         u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1257     }
1258
1259     /// Returns [`true`] if the address appears to be globally routable.
1260     ///
1261     /// The following return [`false`]:
1262     ///
1263     /// - the loopback address
1264     /// - link-local and unique local unicast addresses
1265     /// - interface-, link-, realm-, admin- and site-local multicast addresses
1266     ///
1267     /// # Examples
1268     ///
1269     /// ```
1270     /// #![feature(ip)]
1271     ///
1272     /// use std::net::Ipv6Addr;
1273     ///
1274     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), true);
1275     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_global(), false);
1276     /// assert_eq!(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1).is_global(), true);
1277     /// ```
1278     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1279     #[unstable(feature = "ip", issue = "27709")]
1280     #[inline]
1281     pub const fn is_global(&self) -> bool {
1282         match self.multicast_scope() {
1283             Some(Ipv6MulticastScope::Global) => true,
1284             None => self.is_unicast_global(),
1285             _ => false,
1286         }
1287     }
1288
1289     /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1290     ///
1291     /// This property is defined in [IETF RFC 4193].
1292     ///
1293     /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1294     ///
1295     /// # Examples
1296     ///
1297     /// ```
1298     /// #![feature(ip)]
1299     ///
1300     /// use std::net::Ipv6Addr;
1301     ///
1302     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1303     /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1304     /// ```
1305     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1306     #[unstable(feature = "ip", issue = "27709")]
1307     #[inline]
1308     pub const fn is_unique_local(&self) -> bool {
1309         (self.segments()[0] & 0xfe00) == 0xfc00
1310     }
1311
1312     /// Returns [`true`] if this is a unicast address, as defined by [IETF RFC 4291].
1313     /// Any address that is not a [multicast address] (`ff00::/8`) is unicast.
1314     ///
1315     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1316     /// [multicast address]: Ipv6Addr::is_multicast
1317     ///
1318     /// # Examples
1319     ///
1320     /// ```
1321     /// #![feature(ip)]
1322     ///
1323     /// use std::net::Ipv6Addr;
1324     ///
1325     /// // The unspecified and loopback addresses are unicast.
1326     /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_unicast(), true);
1327     /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast(), true);
1328     ///
1329     /// // Any address that is not a multicast address (`ff00::/8`) is unicast.
1330     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast(), true);
1331     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_unicast(), false);
1332     /// ```
1333     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1334     #[unstable(feature = "ip", issue = "27709")]
1335     #[inline]
1336     pub const fn is_unicast(&self) -> bool {
1337         !self.is_multicast()
1338     }
1339
1340     /// Returns `true` if the address is a unicast address with link-local scope,
1341     /// as defined in [RFC 4291].
1342     ///
1343     /// A unicast address has link-local scope if it has the prefix `fe80::/10`, as per [RFC 4291 section 2.4].
1344     /// Note that this encompasses more addresses than those defined in [RFC 4291 section 2.5.6],
1345     /// which describes "Link-Local IPv6 Unicast Addresses" as having the following stricter format:
1346     ///
1347     /// ```text
1348     /// | 10 bits  |         54 bits         |          64 bits           |
1349     /// +----------+-------------------------+----------------------------+
1350     /// |1111111010|           0             |       interface ID         |
1351     /// +----------+-------------------------+----------------------------+
1352     /// ```
1353     /// So while currently the only addresses with link-local scope an application will encounter are all in `fe80::/64`,
1354     /// this might change in the future with the publication of new standards. More addresses in `fe80::/10` could be allocated,
1355     /// and those addresses will have link-local scope.
1356     ///
1357     /// Also note that while [RFC 4291 section 2.5.3] mentions about the [loopback address] (`::1`) that "it is treated as having Link-Local scope",
1358     /// this does not mean that the loopback address actually has link-local scope and this method will return `false` on it.
1359     ///
1360     /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
1361     /// [RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1362     /// [RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1363     /// [RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1364     /// [loopback address]: Ipv6Addr::LOCALHOST
1365     ///
1366     /// # Examples
1367     ///
1368     /// ```
1369     /// #![feature(ip)]
1370     ///
1371     /// use std::net::Ipv6Addr;
1372     ///
1373     /// // The loopback address (`::1`) does not actually have link-local scope.
1374     /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast_link_local(), false);
1375     ///
1376     /// // Only addresses in `fe80::/10` have link-local scope.
1377     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), false);
1378     /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1379     ///
1380     /// // Addresses outside the stricter `fe80::/64` also have link-local scope.
1381     /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0).is_unicast_link_local(), true);
1382     /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1383     /// ```
1384     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1385     #[unstable(feature = "ip", issue = "27709")]
1386     #[inline]
1387     pub const fn is_unicast_link_local(&self) -> bool {
1388         (self.segments()[0] & 0xffc0) == 0xfe80
1389     }
1390
1391     /// Returns [`true`] if this is an address reserved for documentation
1392     /// (`2001:db8::/32`).
1393     ///
1394     /// This property is defined in [IETF RFC 3849].
1395     ///
1396     /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1397     ///
1398     /// # Examples
1399     ///
1400     /// ```
1401     /// #![feature(ip)]
1402     ///
1403     /// use std::net::Ipv6Addr;
1404     ///
1405     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1406     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1407     /// ```
1408     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1409     #[unstable(feature = "ip", issue = "27709")]
1410     #[inline]
1411     pub const fn is_documentation(&self) -> bool {
1412         (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1413     }
1414
1415     /// Returns [`true`] if the address is a globally routable unicast address.
1416     ///
1417     /// The following return false:
1418     ///
1419     /// - the loopback address
1420     /// - the link-local addresses
1421     /// - unique local addresses
1422     /// - the unspecified address
1423     /// - the address range reserved for documentation
1424     ///
1425     /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1426     ///
1427     /// ```no_rust
1428     /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1429     /// be supported in new implementations (i.e., new implementations must treat this prefix as
1430     /// Global Unicast).
1431     /// ```
1432     ///
1433     /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1434     ///
1435     /// # Examples
1436     ///
1437     /// ```
1438     /// #![feature(ip)]
1439     ///
1440     /// use std::net::Ipv6Addr;
1441     ///
1442     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1443     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1444     /// ```
1445     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1446     #[unstable(feature = "ip", issue = "27709")]
1447     #[inline]
1448     pub const fn is_unicast_global(&self) -> bool {
1449         self.is_unicast()
1450             && !self.is_loopback()
1451             && !self.is_unicast_link_local()
1452             && !self.is_unique_local()
1453             && !self.is_unspecified()
1454             && !self.is_documentation()
1455     }
1456
1457     /// Returns the address's multicast scope if the address is multicast.
1458     ///
1459     /// # Examples
1460     ///
1461     /// ```
1462     /// #![feature(ip)]
1463     ///
1464     /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1465     ///
1466     /// assert_eq!(
1467     ///     Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1468     ///     Some(Ipv6MulticastScope::Global)
1469     /// );
1470     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1471     /// ```
1472     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1473     #[unstable(feature = "ip", issue = "27709")]
1474     #[inline]
1475     pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1476         if self.is_multicast() {
1477             match self.segments()[0] & 0x000f {
1478                 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1479                 2 => Some(Ipv6MulticastScope::LinkLocal),
1480                 3 => Some(Ipv6MulticastScope::RealmLocal),
1481                 4 => Some(Ipv6MulticastScope::AdminLocal),
1482                 5 => Some(Ipv6MulticastScope::SiteLocal),
1483                 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1484                 14 => Some(Ipv6MulticastScope::Global),
1485                 _ => None,
1486             }
1487         } else {
1488             None
1489         }
1490     }
1491
1492     /// Returns [`true`] if this is a multicast address (`ff00::/8`).
1493     ///
1494     /// This property is defined by [IETF RFC 4291].
1495     ///
1496     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1497     ///
1498     /// # Examples
1499     ///
1500     /// ```
1501     /// use std::net::Ipv6Addr;
1502     ///
1503     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1504     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1505     /// ```
1506     #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1507     #[stable(since = "1.7.0", feature = "ip_17")]
1508     #[inline]
1509     pub const fn is_multicast(&self) -> bool {
1510         (self.segments()[0] & 0xff00) == 0xff00
1511     }
1512
1513     /// Converts this address to an [`IPv4` address] if it's an "IPv4-mapped IPv6 address"
1514     /// defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1515     ///
1516     /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1517     /// All addresses *not* starting with `::ffff` will return `None`.
1518     ///
1519     /// [`IPv4` address]: Ipv4Addr
1520     /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1521     ///
1522     /// # Examples
1523     ///
1524     /// ```
1525     /// #![feature(ip)]
1526     ///
1527     /// use std::net::{Ipv4Addr, Ipv6Addr};
1528     ///
1529     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1530     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1531     ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1532     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1533     /// ```
1534     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1535     #[unstable(feature = "ip", issue = "27709")]
1536     #[inline]
1537     pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1538         match self.octets() {
1539             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1540                 Some(Ipv4Addr::new(a, b, c, d))
1541             }
1542             _ => None,
1543         }
1544     }
1545
1546     /// Converts this address to an [`IPv4` address]. Returns [`None`] if this address is
1547     /// neither IPv4-compatible or IPv4-mapped.
1548     ///
1549     /// `::a.b.c.d` and `::ffff:a.b.c.d` become `a.b.c.d`
1550     ///
1551     /// [`IPv4` address]: Ipv4Addr
1552     ///
1553     /// # Examples
1554     ///
1555     /// ```
1556     /// use std::net::{Ipv4Addr, Ipv6Addr};
1557     ///
1558     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1559     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1560     ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1561     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1562     ///            Some(Ipv4Addr::new(0, 0, 0, 1)));
1563     /// ```
1564     #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1565     #[stable(feature = "rust1", since = "1.0.0")]
1566     #[inline]
1567     pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1568         if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1569             let [a, b] = ab.to_be_bytes();
1570             let [c, d] = cd.to_be_bytes();
1571             Some(Ipv4Addr::new(a, b, c, d))
1572         } else {
1573             None
1574         }
1575     }
1576
1577     /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1578     ///
1579     /// ```
1580     /// use std::net::Ipv6Addr;
1581     ///
1582     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1583     ///            [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1584     /// ```
1585     #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1586     #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1587     #[inline]
1588     pub const fn octets(&self) -> [u8; 16] {
1589         self.inner.s6_addr
1590     }
1591 }
1592
1593 /// Write an Ipv6Addr, conforming to the canonical style described by
1594 /// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 impl fmt::Display for Ipv6Addr {
1597     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1598         // If there are no alignment requirements, write out the IP address to
1599         // f. Otherwise, write it to a local buffer, then use f.pad.
1600         if f.precision().is_none() && f.width().is_none() {
1601             let segments = self.segments();
1602
1603             // Special case for :: and ::1; otherwise they get written with the
1604             // IPv4 formatter
1605             if self.is_unspecified() {
1606                 f.write_str("::")
1607             } else if self.is_loopback() {
1608                 f.write_str("::1")
1609             } else if let Some(ipv4) = self.to_ipv4() {
1610                 match segments[5] {
1611                     // IPv4 Compatible address
1612                     0 => write!(f, "::{}", ipv4),
1613                     // IPv4 Mapped address
1614                     0xffff => write!(f, "::ffff:{}", ipv4),
1615                     _ => unreachable!(),
1616                 }
1617             } else {
1618                 #[derive(Copy, Clone, Default)]
1619                 struct Span {
1620                     start: usize,
1621                     len: usize,
1622                 }
1623
1624                 // Find the inner 0 span
1625                 let zeroes = {
1626                     let mut longest = Span::default();
1627                     let mut current = Span::default();
1628
1629                     for (i, &segment) in segments.iter().enumerate() {
1630                         if segment == 0 {
1631                             if current.len == 0 {
1632                                 current.start = i;
1633                             }
1634
1635                             current.len += 1;
1636
1637                             if current.len > longest.len {
1638                                 longest = current;
1639                             }
1640                         } else {
1641                             current = Span::default();
1642                         }
1643                     }
1644
1645                     longest
1646                 };
1647
1648                 /// Write a colon-separated part of the address
1649                 #[inline]
1650                 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1651                     if let Some((first, tail)) = chunk.split_first() {
1652                         write!(f, "{:x}", first)?;
1653                         for segment in tail {
1654                             f.write_char(':')?;
1655                             write!(f, "{:x}", segment)?;
1656                         }
1657                     }
1658                     Ok(())
1659                 }
1660
1661                 if zeroes.len > 1 {
1662                     fmt_subslice(f, &segments[..zeroes.start])?;
1663                     f.write_str("::")?;
1664                     fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1665                 } else {
1666                     fmt_subslice(f, &segments)
1667                 }
1668             }
1669         } else {
1670             // Slow path: write the address to a local buffer, the use f.pad.
1671             // Defined recursively by using the fast path to write to the
1672             // buffer.
1673
1674             // This is the largest possible size of an IPv6 address
1675             const IPV6_BUF_LEN: usize = (4 * 8) + 7;
1676             let mut buf = [0u8; IPV6_BUF_LEN];
1677             let mut buf_slice = &mut buf[..];
1678
1679             // Note: This call to write should never fail, so unwrap is okay.
1680             write!(buf_slice, "{}", self).unwrap();
1681             let len = IPV6_BUF_LEN - buf_slice.len();
1682
1683             // This is safe because we know exactly what can be in this buffer
1684             let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1685             f.pad(buf)
1686         }
1687     }
1688 }
1689
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 impl fmt::Debug for Ipv6Addr {
1692     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1693         fmt::Display::fmt(self, fmt)
1694     }
1695 }
1696
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl Clone for Ipv6Addr {
1699     #[inline]
1700     fn clone(&self) -> Ipv6Addr {
1701         *self
1702     }
1703 }
1704
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 impl PartialEq for Ipv6Addr {
1707     #[inline]
1708     fn eq(&self, other: &Ipv6Addr) -> bool {
1709         self.inner.s6_addr == other.inner.s6_addr
1710     }
1711 }
1712
1713 #[stable(feature = "ip_cmp", since = "1.16.0")]
1714 impl PartialEq<IpAddr> for Ipv6Addr {
1715     #[inline]
1716     fn eq(&self, other: &IpAddr) -> bool {
1717         match other {
1718             IpAddr::V4(_) => false,
1719             IpAddr::V6(v6) => self == v6,
1720         }
1721     }
1722 }
1723
1724 #[stable(feature = "ip_cmp", since = "1.16.0")]
1725 impl PartialEq<Ipv6Addr> for IpAddr {
1726     #[inline]
1727     fn eq(&self, other: &Ipv6Addr) -> bool {
1728         match self {
1729             IpAddr::V4(_) => false,
1730             IpAddr::V6(v6) => v6 == other,
1731         }
1732     }
1733 }
1734
1735 #[stable(feature = "rust1", since = "1.0.0")]
1736 impl Eq for Ipv6Addr {}
1737
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 impl hash::Hash for Ipv6Addr {
1740     #[inline]
1741     fn hash<H: hash::Hasher>(&self, s: &mut H) {
1742         self.inner.s6_addr.hash(s)
1743     }
1744 }
1745
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 impl PartialOrd for Ipv6Addr {
1748     #[inline]
1749     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1750         Some(self.cmp(other))
1751     }
1752 }
1753
1754 #[stable(feature = "ip_cmp", since = "1.16.0")]
1755 impl PartialOrd<Ipv6Addr> for IpAddr {
1756     #[inline]
1757     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1758         match self {
1759             IpAddr::V4(_) => Some(Ordering::Less),
1760             IpAddr::V6(v6) => v6.partial_cmp(other),
1761         }
1762     }
1763 }
1764
1765 #[stable(feature = "ip_cmp", since = "1.16.0")]
1766 impl PartialOrd<IpAddr> for Ipv6Addr {
1767     #[inline]
1768     fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1769         match other {
1770             IpAddr::V4(_) => Some(Ordering::Greater),
1771             IpAddr::V6(v6) => self.partial_cmp(v6),
1772         }
1773     }
1774 }
1775
1776 #[stable(feature = "rust1", since = "1.0.0")]
1777 impl Ord for Ipv6Addr {
1778     #[inline]
1779     fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1780         self.segments().cmp(&other.segments())
1781     }
1782 }
1783
1784 impl AsInner<c::in6_addr> for Ipv6Addr {
1785     #[inline]
1786     fn as_inner(&self) -> &c::in6_addr {
1787         &self.inner
1788     }
1789 }
1790 impl FromInner<c::in6_addr> for Ipv6Addr {
1791     #[inline]
1792     fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1793         Ipv6Addr { inner: addr }
1794     }
1795 }
1796
1797 #[stable(feature = "i128", since = "1.26.0")]
1798 impl From<Ipv6Addr> for u128 {
1799     /// Convert an `Ipv6Addr` into a host byte order `u128`.
1800     ///
1801     /// # Examples
1802     ///
1803     /// ```
1804     /// use std::net::Ipv6Addr;
1805     ///
1806     /// let addr = Ipv6Addr::new(
1807     ///     0x1020, 0x3040, 0x5060, 0x7080,
1808     ///     0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1809     /// );
1810     /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1811     /// ```
1812     #[inline]
1813     fn from(ip: Ipv6Addr) -> u128 {
1814         let ip = ip.octets();
1815         u128::from_be_bytes(ip)
1816     }
1817 }
1818 #[stable(feature = "i128", since = "1.26.0")]
1819 impl From<u128> for Ipv6Addr {
1820     /// Convert a host byte order `u128` into an `Ipv6Addr`.
1821     ///
1822     /// # Examples
1823     ///
1824     /// ```
1825     /// use std::net::Ipv6Addr;
1826     ///
1827     /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1828     /// assert_eq!(
1829     ///     Ipv6Addr::new(
1830     ///         0x1020, 0x3040, 0x5060, 0x7080,
1831     ///         0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1832     ///     ),
1833     ///     addr);
1834     /// ```
1835     #[inline]
1836     fn from(ip: u128) -> Ipv6Addr {
1837         Ipv6Addr::from(ip.to_be_bytes())
1838     }
1839 }
1840
1841 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1842 impl From<[u8; 16]> for Ipv6Addr {
1843     /// Creates an `Ipv6Addr` from a sixteen element byte array.
1844     ///
1845     /// # Examples
1846     ///
1847     /// ```
1848     /// use std::net::Ipv6Addr;
1849     ///
1850     /// let addr = Ipv6Addr::from([
1851     ///     25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1852     ///     17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1853     /// ]);
1854     /// assert_eq!(
1855     ///     Ipv6Addr::new(
1856     ///         0x1918, 0x1716,
1857     ///         0x1514, 0x1312,
1858     ///         0x1110, 0x0f0e,
1859     ///         0x0d0c, 0x0b0a
1860     ///     ),
1861     ///     addr
1862     /// );
1863     /// ```
1864     #[inline]
1865     fn from(octets: [u8; 16]) -> Ipv6Addr {
1866         let inner = c::in6_addr { s6_addr: octets };
1867         Ipv6Addr::from_inner(inner)
1868     }
1869 }
1870
1871 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
1872 impl From<[u16; 8]> for Ipv6Addr {
1873     /// Creates an `Ipv6Addr` from an eight element 16-bit array.
1874     ///
1875     /// # Examples
1876     ///
1877     /// ```
1878     /// use std::net::Ipv6Addr;
1879     ///
1880     /// let addr = Ipv6Addr::from([
1881     ///     525u16, 524u16, 523u16, 522u16,
1882     ///     521u16, 520u16, 519u16, 518u16,
1883     /// ]);
1884     /// assert_eq!(
1885     ///     Ipv6Addr::new(
1886     ///         0x20d, 0x20c,
1887     ///         0x20b, 0x20a,
1888     ///         0x209, 0x208,
1889     ///         0x207, 0x206
1890     ///     ),
1891     ///     addr
1892     /// );
1893     /// ```
1894     #[inline]
1895     fn from(segments: [u16; 8]) -> Ipv6Addr {
1896         let [a, b, c, d, e, f, g, h] = segments;
1897         Ipv6Addr::new(a, b, c, d, e, f, g, h)
1898     }
1899 }
1900
1901 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1902 impl From<[u8; 16]> for IpAddr {
1903     /// Creates an `IpAddr::V6` from a sixteen element byte array.
1904     ///
1905     /// # Examples
1906     ///
1907     /// ```
1908     /// use std::net::{IpAddr, Ipv6Addr};
1909     ///
1910     /// let addr = IpAddr::from([
1911     ///     25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1912     ///     17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1913     /// ]);
1914     /// assert_eq!(
1915     ///     IpAddr::V6(Ipv6Addr::new(
1916     ///         0x1918, 0x1716,
1917     ///         0x1514, 0x1312,
1918     ///         0x1110, 0x0f0e,
1919     ///         0x0d0c, 0x0b0a
1920     ///     )),
1921     ///     addr
1922     /// );
1923     /// ```
1924     #[inline]
1925     fn from(octets: [u8; 16]) -> IpAddr {
1926         IpAddr::V6(Ipv6Addr::from(octets))
1927     }
1928 }
1929
1930 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1931 impl From<[u16; 8]> for IpAddr {
1932     /// Creates an `IpAddr::V6` from an eight element 16-bit array.
1933     ///
1934     /// # Examples
1935     ///
1936     /// ```
1937     /// use std::net::{IpAddr, Ipv6Addr};
1938     ///
1939     /// let addr = IpAddr::from([
1940     ///     525u16, 524u16, 523u16, 522u16,
1941     ///     521u16, 520u16, 519u16, 518u16,
1942     /// ]);
1943     /// assert_eq!(
1944     ///     IpAddr::V6(Ipv6Addr::new(
1945     ///         0x20d, 0x20c,
1946     ///         0x20b, 0x20a,
1947     ///         0x209, 0x208,
1948     ///         0x207, 0x206
1949     ///     )),
1950     ///     addr
1951     /// );
1952     /// ```
1953     #[inline]
1954     fn from(segments: [u16; 8]) -> IpAddr {
1955         IpAddr::V6(Ipv6Addr::from(segments))
1956     }
1957 }