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