]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/ip.rs
Rollup merge of #100851 - Alexendoo:rpf-width-prec-spans, r=fee1-dead
[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 reachable
624     /// as specified by the [IANA IPv4 Special-Purpose Address Registry].
625     /// Whether or not an address is practically reachable will depend on your network configuration.
626     ///
627     /// Most IPv4 addresses are globally reachable;
628     /// unless they are specifically defined as *not* globally reachable.
629     ///
630     /// Non-exhaustive list of notable addresses that are not globally reachable:
631     ///
632     /// - The [unspecified address] ([`is_unspecified`](Ipv4Addr::is_unspecified))
633     /// - Addresses reserved for private use ([`is_private`](Ipv4Addr::is_private))
634     /// - Addresses in the shared address space ([`is_shared`](Ipv4Addr::is_shared))
635     /// - Loopback addresses ([`is_loopback`](Ipv4Addr::is_loopback))
636     /// - Link-local addresses ([`is_link_local`](Ipv4Addr::is_link_local))
637     /// - Addresses reserved for documentation ([`is_documentation`](Ipv4Addr::is_documentation))
638     /// - Addresses reserved for benchmarking ([`is_benchmarking`](Ipv4Addr::is_benchmarking))
639     /// - Reserved addresses ([`is_reserved`](Ipv4Addr::is_reserved))
640     /// - The [broadcast address] ([`is_broadcast`](Ipv4Addr::is_broadcast))
641     ///
642     /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv4 Special-Purpose Address Registry].
643     ///
644     /// [IANA IPv4 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
645     /// [unspecified address]: Ipv4Addr::UNSPECIFIED
646     /// [broadcast address]: Ipv4Addr::BROADCAST
647
648     ///
649     /// # Examples
650     ///
651     /// ```
652     /// #![feature(ip)]
653     ///
654     /// use std::net::Ipv4Addr;
655     ///
656     /// // Most IPv4 addresses are globally reachable:
657     /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
658     ///
659     /// // However some addresses have been assigned a special meaning
660     /// // that makes them not globally reachable. Some examples are:
661     ///
662     /// // The unspecified address (`0.0.0.0`)
663     /// assert_eq!(Ipv4Addr::UNSPECIFIED.is_global(), false);
664     ///
665     /// // Addresses reserved for private use (`10.0.0.0/8`, `172.16.0.0/12`, 192.168.0.0/16)
666     /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
667     /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
668     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
669     ///
670     /// // Addresses in the shared address space (`100.64.0.0/10`)
671     /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
672     ///
673     /// // The loopback addresses (`127.0.0.0/8`)
674     /// assert_eq!(Ipv4Addr::LOCALHOST.is_global(), false);
675     ///
676     /// // Link-local addresses (`169.254.0.0/16`)
677     /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
678     ///
679     /// // Addresses reserved for documentation (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`)
680     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
681     /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
682     /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
683     ///
684     /// // Addresses reserved for benchmarking (`198.18.0.0/15`)
685     /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
686     ///
687     /// // Reserved addresses (`240.0.0.0/4`)
688     /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
689     ///
690     /// // The broadcast address (`255.255.255.255`)
691     /// assert_eq!(Ipv4Addr::BROADCAST.is_global(), false);
692     ///
693     /// // For a complete overview see the IANA IPv4 Special-Purpose Address Registry.
694     /// ```
695     #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
696     #[unstable(feature = "ip", issue = "27709")]
697     #[must_use]
698     #[inline]
699     pub const fn is_global(&self) -> bool {
700         !(self.octets()[0] == 0 // "This network"
701             || self.is_private()
702             || self.is_shared()
703             || self.is_loopback()
704             || self.is_link_local()
705             // addresses reserved for future protocols (`192.0.0.0/24`)
706             ||(self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0)
707             || self.is_documentation()
708             || self.is_benchmarking()
709             || self.is_reserved()
710             || self.is_broadcast())
711     }
712
713     /// Returns [`true`] if this address is part of the Shared Address Space defined in
714     /// [IETF RFC 6598] (`100.64.0.0/10`).
715     ///
716     /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
717     ///
718     /// # Examples
719     ///
720     /// ```
721     /// #![feature(ip)]
722     /// use std::net::Ipv4Addr;
723     ///
724     /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
725     /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
726     /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
727     /// ```
728     #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
729     #[unstable(feature = "ip", issue = "27709")]
730     #[must_use]
731     #[inline]
732     pub const fn is_shared(&self) -> bool {
733         self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
734     }
735
736     /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
737     /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
738     /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
739     ///
740     /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
741     /// [errata 423]: https://www.rfc-editor.org/errata/eid423
742     ///
743     /// # Examples
744     ///
745     /// ```
746     /// #![feature(ip)]
747     /// use std::net::Ipv4Addr;
748     ///
749     /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
750     /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
751     /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
752     /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
753     /// ```
754     #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
755     #[unstable(feature = "ip", issue = "27709")]
756     #[must_use]
757     #[inline]
758     pub const fn is_benchmarking(&self) -> bool {
759         self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
760     }
761
762     /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
763     /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
764     /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
765     /// it is obviously not reserved for future use.
766     ///
767     /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
768     ///
769     /// # Warning
770     ///
771     /// As IANA assigns new addresses, this method will be
772     /// updated. This may result in non-reserved addresses being
773     /// treated as reserved in code that relies on an outdated version
774     /// of this method.
775     ///
776     /// # Examples
777     ///
778     /// ```
779     /// #![feature(ip)]
780     /// use std::net::Ipv4Addr;
781     ///
782     /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
783     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
784     ///
785     /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
786     /// // The broadcast address is not considered as reserved for future use by this implementation
787     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
788     /// ```
789     #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
790     #[unstable(feature = "ip", issue = "27709")]
791     #[must_use]
792     #[inline]
793     pub const fn is_reserved(&self) -> bool {
794         self.octets()[0] & 240 == 240 && !self.is_broadcast()
795     }
796
797     /// Returns [`true`] if this is a multicast address (`224.0.0.0/4`).
798     ///
799     /// Multicast addresses have a most significant octet between `224` and `239`,
800     /// and is defined by [IETF RFC 5771].
801     ///
802     /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
803     ///
804     /// # Examples
805     ///
806     /// ```
807     /// use std::net::Ipv4Addr;
808     ///
809     /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
810     /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
811     /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
812     /// ```
813     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
814     #[stable(since = "1.7.0", feature = "ip_17")]
815     #[must_use]
816     #[inline]
817     pub const fn is_multicast(&self) -> bool {
818         self.octets()[0] >= 224 && self.octets()[0] <= 239
819     }
820
821     /// Returns [`true`] if this is a broadcast address (`255.255.255.255`).
822     ///
823     /// A broadcast address has all octets set to `255` as defined in [IETF RFC 919].
824     ///
825     /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
826     ///
827     /// # Examples
828     ///
829     /// ```
830     /// use std::net::Ipv4Addr;
831     ///
832     /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
833     /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
834     /// ```
835     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
836     #[stable(since = "1.7.0", feature = "ip_17")]
837     #[must_use]
838     #[inline]
839     pub const fn is_broadcast(&self) -> bool {
840         u32::from_be_bytes(self.octets()) == u32::from_be_bytes(Self::BROADCAST.octets())
841     }
842
843     /// Returns [`true`] if this address is in a range designated for documentation.
844     ///
845     /// This is defined in [IETF RFC 5737]:
846     ///
847     /// - `192.0.2.0/24` (TEST-NET-1)
848     /// - `198.51.100.0/24` (TEST-NET-2)
849     /// - `203.0.113.0/24` (TEST-NET-3)
850     ///
851     /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
852     ///
853     /// # Examples
854     ///
855     /// ```
856     /// use std::net::Ipv4Addr;
857     ///
858     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
859     /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
860     /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
861     /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
862     /// ```
863     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
864     #[stable(since = "1.7.0", feature = "ip_17")]
865     #[must_use]
866     #[inline]
867     pub const fn is_documentation(&self) -> bool {
868         matches!(self.octets(), [192, 0, 2, _] | [198, 51, 100, _] | [203, 0, 113, _])
869     }
870
871     /// Converts this address to an [IPv4-compatible] [`IPv6` address].
872     ///
873     /// `a.b.c.d` becomes `::a.b.c.d`
874     ///
875     /// Note that IPv4-compatible addresses have been officially deprecated.
876     /// If you don't explicitly need an IPv4-compatible address for legacy reasons, consider using `to_ipv6_mapped` instead.
877     ///
878     /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
879     /// [`IPv6` address]: Ipv6Addr
880     ///
881     /// # Examples
882     ///
883     /// ```
884     /// use std::net::{Ipv4Addr, Ipv6Addr};
885     ///
886     /// assert_eq!(
887     ///     Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
888     ///     Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x2ff)
889     /// );
890     /// ```
891     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
892     #[stable(feature = "rust1", since = "1.0.0")]
893     #[must_use = "this returns the result of the operation, \
894                   without modifying the original"]
895     #[inline]
896     pub const fn to_ipv6_compatible(&self) -> Ipv6Addr {
897         let [a, b, c, d] = self.octets();
898         Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] }
899     }
900
901     /// Converts this address to an [IPv4-mapped] [`IPv6` address].
902     ///
903     /// `a.b.c.d` becomes `::ffff:a.b.c.d`
904     ///
905     /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
906     /// [`IPv6` address]: Ipv6Addr
907     ///
908     /// # Examples
909     ///
910     /// ```
911     /// use std::net::{Ipv4Addr, Ipv6Addr};
912     ///
913     /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
914     ///            Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff));
915     /// ```
916     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
917     #[stable(feature = "rust1", since = "1.0.0")]
918     #[must_use = "this returns the result of the operation, \
919                   without modifying the original"]
920     #[inline]
921     pub const fn to_ipv6_mapped(&self) -> Ipv6Addr {
922         let [a, b, c, d] = self.octets();
923         Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] }
924     }
925 }
926
927 #[stable(feature = "ip_addr", since = "1.7.0")]
928 impl fmt::Display for IpAddr {
929     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
930         match self {
931             IpAddr::V4(ip) => ip.fmt(fmt),
932             IpAddr::V6(ip) => ip.fmt(fmt),
933         }
934     }
935 }
936
937 #[stable(feature = "ip_addr", since = "1.7.0")]
938 impl fmt::Debug for IpAddr {
939     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
940         fmt::Display::fmt(self, fmt)
941     }
942 }
943
944 #[stable(feature = "ip_from_ip", since = "1.16.0")]
945 impl From<Ipv4Addr> for IpAddr {
946     /// Copies this address to a new `IpAddr::V4`.
947     ///
948     /// # Examples
949     ///
950     /// ```
951     /// use std::net::{IpAddr, Ipv4Addr};
952     ///
953     /// let addr = Ipv4Addr::new(127, 0, 0, 1);
954     ///
955     /// assert_eq!(
956     ///     IpAddr::V4(addr),
957     ///     IpAddr::from(addr)
958     /// )
959     /// ```
960     #[inline]
961     fn from(ipv4: Ipv4Addr) -> IpAddr {
962         IpAddr::V4(ipv4)
963     }
964 }
965
966 #[stable(feature = "ip_from_ip", since = "1.16.0")]
967 impl From<Ipv6Addr> for IpAddr {
968     /// Copies this address to a new `IpAddr::V6`.
969     ///
970     /// # Examples
971     ///
972     /// ```
973     /// use std::net::{IpAddr, Ipv6Addr};
974     ///
975     /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
976     ///
977     /// assert_eq!(
978     ///     IpAddr::V6(addr),
979     ///     IpAddr::from(addr)
980     /// );
981     /// ```
982     #[inline]
983     fn from(ipv6: Ipv6Addr) -> IpAddr {
984         IpAddr::V6(ipv6)
985     }
986 }
987
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl fmt::Display for Ipv4Addr {
990     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
991         let octets = self.octets();
992
993         // If there are no alignment requirements, write the IP address directly to `f`.
994         // Otherwise, write it to a local buffer and then use `f.pad`.
995         if fmt.precision().is_none() && fmt.width().is_none() {
996             write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
997         } else {
998             const LONGEST_IPV4_ADDR: &str = "255.255.255.255";
999
1000             let mut buf = IpDisplayBuffer::<{ LONGEST_IPV4_ADDR.len() }>::new();
1001             // Buffer is long enough for the longest possible IPv4 address, so this should never fail.
1002             write!(buf, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
1003
1004             fmt.pad(buf.as_str())
1005         }
1006     }
1007 }
1008
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 impl fmt::Debug for Ipv4Addr {
1011     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1012         fmt::Display::fmt(self, fmt)
1013     }
1014 }
1015
1016 #[stable(feature = "ip_cmp", since = "1.16.0")]
1017 impl PartialEq<Ipv4Addr> for IpAddr {
1018     #[inline]
1019     fn eq(&self, other: &Ipv4Addr) -> bool {
1020         match self {
1021             IpAddr::V4(v4) => v4 == other,
1022             IpAddr::V6(_) => false,
1023         }
1024     }
1025 }
1026
1027 #[stable(feature = "ip_cmp", since = "1.16.0")]
1028 impl PartialEq<IpAddr> for Ipv4Addr {
1029     #[inline]
1030     fn eq(&self, other: &IpAddr) -> bool {
1031         match other {
1032             IpAddr::V4(v4) => self == v4,
1033             IpAddr::V6(_) => false,
1034         }
1035     }
1036 }
1037
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 impl PartialOrd for Ipv4Addr {
1040     #[inline]
1041     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1042         Some(self.cmp(other))
1043     }
1044 }
1045
1046 #[stable(feature = "ip_cmp", since = "1.16.0")]
1047 impl PartialOrd<Ipv4Addr> for IpAddr {
1048     #[inline]
1049     fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1050         match self {
1051             IpAddr::V4(v4) => v4.partial_cmp(other),
1052             IpAddr::V6(_) => Some(Ordering::Greater),
1053         }
1054     }
1055 }
1056
1057 #[stable(feature = "ip_cmp", since = "1.16.0")]
1058 impl PartialOrd<IpAddr> for Ipv4Addr {
1059     #[inline]
1060     fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1061         match other {
1062             IpAddr::V4(v4) => self.partial_cmp(v4),
1063             IpAddr::V6(_) => Some(Ordering::Less),
1064         }
1065     }
1066 }
1067
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 impl Ord for Ipv4Addr {
1070     #[inline]
1071     fn cmp(&self, other: &Ipv4Addr) -> Ordering {
1072         self.octets.cmp(&other.octets)
1073     }
1074 }
1075
1076 impl IntoInner<c::in_addr> for Ipv4Addr {
1077     #[inline]
1078     fn into_inner(self) -> c::in_addr {
1079         // `s_addr` is stored as BE on all machines and the array is in BE order.
1080         // So the native endian conversion method is used so that it's never swapped.
1081         c::in_addr { s_addr: u32::from_ne_bytes(self.octets) }
1082     }
1083 }
1084 impl FromInner<c::in_addr> for Ipv4Addr {
1085     fn from_inner(addr: c::in_addr) -> Ipv4Addr {
1086         Ipv4Addr { octets: addr.s_addr.to_ne_bytes() }
1087     }
1088 }
1089
1090 #[stable(feature = "ip_u32", since = "1.1.0")]
1091 impl From<Ipv4Addr> for u32 {
1092     /// Converts an `Ipv4Addr` into a host byte order `u32`.
1093     ///
1094     /// # Examples
1095     ///
1096     /// ```
1097     /// use std::net::Ipv4Addr;
1098     ///
1099     /// let addr = Ipv4Addr::new(0x12, 0x34, 0x56, 0x78);
1100     /// assert_eq!(0x12345678, u32::from(addr));
1101     /// ```
1102     #[inline]
1103     fn from(ip: Ipv4Addr) -> u32 {
1104         u32::from_be_bytes(ip.octets)
1105     }
1106 }
1107
1108 #[stable(feature = "ip_u32", since = "1.1.0")]
1109 impl From<u32> for Ipv4Addr {
1110     /// Converts a host byte order `u32` into an `Ipv4Addr`.
1111     ///
1112     /// # Examples
1113     ///
1114     /// ```
1115     /// use std::net::Ipv4Addr;
1116     ///
1117     /// let addr = Ipv4Addr::from(0x12345678);
1118     /// assert_eq!(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78), addr);
1119     /// ```
1120     #[inline]
1121     fn from(ip: u32) -> Ipv4Addr {
1122         Ipv4Addr { octets: ip.to_be_bytes() }
1123     }
1124 }
1125
1126 #[stable(feature = "from_slice_v4", since = "1.9.0")]
1127 impl From<[u8; 4]> for Ipv4Addr {
1128     /// Creates an `Ipv4Addr` from a four element byte array.
1129     ///
1130     /// # Examples
1131     ///
1132     /// ```
1133     /// use std::net::Ipv4Addr;
1134     ///
1135     /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1136     /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1137     /// ```
1138     #[inline]
1139     fn from(octets: [u8; 4]) -> Ipv4Addr {
1140         Ipv4Addr { octets }
1141     }
1142 }
1143
1144 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1145 impl From<[u8; 4]> for IpAddr {
1146     /// Creates an `IpAddr::V4` from a four element byte array.
1147     ///
1148     /// # Examples
1149     ///
1150     /// ```
1151     /// use std::net::{IpAddr, Ipv4Addr};
1152     ///
1153     /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1154     /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1155     /// ```
1156     #[inline]
1157     fn from(octets: [u8; 4]) -> IpAddr {
1158         IpAddr::V4(Ipv4Addr::from(octets))
1159     }
1160 }
1161
1162 impl Ipv6Addr {
1163     /// Creates a new IPv6 address from eight 16-bit segments.
1164     ///
1165     /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1166     ///
1167     /// # Examples
1168     ///
1169     /// ```
1170     /// use std::net::Ipv6Addr;
1171     ///
1172     /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1173     /// ```
1174     #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
1175     #[stable(feature = "rust1", since = "1.0.0")]
1176     #[must_use]
1177     #[inline]
1178     pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1179         let addr16 = [
1180             a.to_be(),
1181             b.to_be(),
1182             c.to_be(),
1183             d.to_be(),
1184             e.to_be(),
1185             f.to_be(),
1186             g.to_be(),
1187             h.to_be(),
1188         ];
1189         Ipv6Addr {
1190             // All elements in `addr16` are big endian.
1191             // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1192             octets: unsafe { transmute::<_, [u8; 16]>(addr16) },
1193         }
1194     }
1195
1196     /// An IPv6 address representing localhost: `::1`.
1197     ///
1198     /// # Examples
1199     ///
1200     /// ```
1201     /// use std::net::Ipv6Addr;
1202     ///
1203     /// let addr = Ipv6Addr::LOCALHOST;
1204     /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1205     /// ```
1206     #[stable(feature = "ip_constructors", since = "1.30.0")]
1207     pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1208
1209     /// An IPv6 address representing the unspecified address: `::`
1210     ///
1211     /// # Examples
1212     ///
1213     /// ```
1214     /// use std::net::Ipv6Addr;
1215     ///
1216     /// let addr = Ipv6Addr::UNSPECIFIED;
1217     /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1218     /// ```
1219     #[stable(feature = "ip_constructors", since = "1.30.0")]
1220     pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1221
1222     /// Returns the eight 16-bit segments that make up this address.
1223     ///
1224     /// # Examples
1225     ///
1226     /// ```
1227     /// use std::net::Ipv6Addr;
1228     ///
1229     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1230     ///            [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1231     /// ```
1232     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1233     #[stable(feature = "rust1", since = "1.0.0")]
1234     #[must_use]
1235     #[inline]
1236     pub const fn segments(&self) -> [u16; 8] {
1237         // All elements in `self.octets` must be big endian.
1238         // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1239         let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.octets) };
1240         // We want native endian u16
1241         [
1242             u16::from_be(a),
1243             u16::from_be(b),
1244             u16::from_be(c),
1245             u16::from_be(d),
1246             u16::from_be(e),
1247             u16::from_be(f),
1248             u16::from_be(g),
1249             u16::from_be(h),
1250         ]
1251     }
1252
1253     /// Returns [`true`] for the special 'unspecified' address (`::`).
1254     ///
1255     /// This property is defined in [IETF RFC 4291].
1256     ///
1257     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1258     ///
1259     /// # Examples
1260     ///
1261     /// ```
1262     /// use std::net::Ipv6Addr;
1263     ///
1264     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1265     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1266     /// ```
1267     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1268     #[stable(since = "1.7.0", feature = "ip_17")]
1269     #[must_use]
1270     #[inline]
1271     pub const fn is_unspecified(&self) -> bool {
1272         u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1273     }
1274
1275     /// Returns [`true`] if this is the [loopback address] (`::1`),
1276     /// as defined in [IETF RFC 4291 section 2.5.3].
1277     ///
1278     /// Contrary to IPv4, in IPv6 there is only one loopback address.
1279     ///
1280     /// [loopback address]: Ipv6Addr::LOCALHOST
1281     /// [IETF RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1282     ///
1283     /// # Examples
1284     ///
1285     /// ```
1286     /// use std::net::Ipv6Addr;
1287     ///
1288     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1289     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1290     /// ```
1291     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1292     #[stable(since = "1.7.0", feature = "ip_17")]
1293     #[must_use]
1294     #[inline]
1295     pub const fn is_loopback(&self) -> bool {
1296         u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1297     }
1298
1299     /// Returns [`true`] if the address appears to be globally reachable
1300     /// as specified by the [IANA IPv6 Special-Purpose Address Registry].
1301     /// Whether or not an address is practically reachable will depend on your network configuration.
1302     ///
1303     /// Most IPv6 addresses are globally reachable;
1304     /// unless they are specifically defined as *not* globally reachable.
1305     ///
1306     /// Non-exhaustive list of notable addresses that are not globally reachable:
1307     /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified))
1308     /// - The [loopback address] ([`is_loopback`](Ipv6Addr::is_loopback))
1309     /// - IPv4-mapped addresses
1310     /// - Addresses reserved for benchmarking
1311     /// - Addresses reserved for documentation ([`is_documentation`](Ipv6Addr::is_documentation))
1312     /// - Unique local addresses ([`is_unique_local`](Ipv6Addr::is_unique_local))
1313     /// - Unicast addresses with link-local scope ([`is_unicast_link_local`](Ipv6Addr::is_unicast_link_local))
1314     ///
1315     /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv6 Special-Purpose Address Registry].
1316     ///
1317     /// Note that an address having global scope is not the same as being globally reachable,
1318     /// and there is no direct relation between the two concepts: There exist addresses with global scope
1319     /// that are not globally reachable (for example unique local addresses),
1320     /// and addresses that are globally reachable without having global scope
1321     /// (multicast addresses with non-global scope).
1322     ///
1323     /// [IANA IPv6 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
1324     /// [unspecified address]: Ipv6Addr::UNSPECIFIED
1325     /// [loopback address]: Ipv6Addr::LOCALHOST
1326     ///
1327     /// # Examples
1328     ///
1329     /// ```
1330     /// #![feature(ip)]
1331     ///
1332     /// use std::net::Ipv6Addr;
1333     ///
1334     /// // Most IPv6 addresses are globally reachable:
1335     /// assert_eq!(Ipv6Addr::new(0x26, 0, 0x1c9, 0, 0, 0xafc8, 0x10, 0x1).is_global(), true);
1336     ///
1337     /// // However some addresses have been assigned a special meaning
1338     /// // that makes them not globally reachable. Some examples are:
1339     ///
1340     /// // The unspecified address (`::`)
1341     /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_global(), false);
1342     ///
1343     /// // The loopback address (`::1`)
1344     /// assert_eq!(Ipv6Addr::LOCALHOST.is_global(), false);
1345     ///
1346     /// // IPv4-mapped addresses (`::ffff:0:0/96`)
1347     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), false);
1348     ///
1349     /// // Addresses reserved for benchmarking (`2001:2::/48`)
1350     /// assert_eq!(Ipv6Addr::new(0x2001, 2, 0, 0, 0, 0, 0, 1,).is_global(), false);
1351     ///
1352     /// // Addresses reserved for documentation (`2001:db8::/32`)
1353     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).is_global(), false);
1354     ///
1355     /// // Unique local addresses (`fc00::/7`)
1356     /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1357     ///
1358     /// // Unicast addresses with link-local scope (`fe80::/10`)
1359     /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1360     ///
1361     /// // For a complete overview see the IANA IPv6 Special-Purpose Address Registry.
1362     /// ```
1363     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1364     #[unstable(feature = "ip", issue = "27709")]
1365     #[must_use]
1366     #[inline]
1367     pub const fn is_global(&self) -> bool {
1368         !(self.is_unspecified()
1369             || self.is_loopback()
1370             // IPv4-mapped Address (`::ffff:0:0/96`)
1371             || matches!(self.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
1372             // IPv4-IPv6 Translat. (`64:ff9b:1::/48`)
1373             || matches!(self.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
1374             // Discard-Only Address Block (`100::/64`)
1375             || matches!(self.segments(), [0x100, 0, 0, 0, _, _, _, _])
1376             // IETF Protocol Assignments (`2001::/23`)
1377             || (matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
1378                 && !(
1379                     // Port Control Protocol Anycast (`2001:1::1`)
1380                     u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
1381                     // Traversal Using Relays around NAT Anycast (`2001:1::2`)
1382                     || u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
1383                     // AMT (`2001:3::/32`)
1384                     || matches!(self.segments(), [0x2001, 3, _, _, _, _, _, _])
1385                     // AS112-v6 (`2001:4:112::/48`)
1386                     || matches!(self.segments(), [0x2001, 4, 0x112, _, _, _, _, _])
1387                     // ORCHIDv2 (`2001:20::/28`)
1388                     || matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b >= 0x20 && b <= 0x2F)
1389                 ))
1390             || self.is_documentation()
1391             || self.is_unique_local()
1392             || self.is_unicast_link_local())
1393     }
1394
1395     /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1396     ///
1397     /// This property is defined in [IETF RFC 4193].
1398     ///
1399     /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1400     ///
1401     /// # Examples
1402     ///
1403     /// ```
1404     /// #![feature(ip)]
1405     ///
1406     /// use std::net::Ipv6Addr;
1407     ///
1408     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1409     /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1410     /// ```
1411     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1412     #[unstable(feature = "ip", issue = "27709")]
1413     #[must_use]
1414     #[inline]
1415     pub const fn is_unique_local(&self) -> bool {
1416         (self.segments()[0] & 0xfe00) == 0xfc00
1417     }
1418
1419     /// Returns [`true`] if this is a unicast address, as defined by [IETF RFC 4291].
1420     /// Any address that is not a [multicast address] (`ff00::/8`) is unicast.
1421     ///
1422     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1423     /// [multicast address]: Ipv6Addr::is_multicast
1424     ///
1425     /// # Examples
1426     ///
1427     /// ```
1428     /// #![feature(ip)]
1429     ///
1430     /// use std::net::Ipv6Addr;
1431     ///
1432     /// // The unspecified and loopback addresses are unicast.
1433     /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_unicast(), true);
1434     /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast(), true);
1435     ///
1436     /// // Any address that is not a multicast address (`ff00::/8`) is unicast.
1437     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast(), true);
1438     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_unicast(), false);
1439     /// ```
1440     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1441     #[unstable(feature = "ip", issue = "27709")]
1442     #[must_use]
1443     #[inline]
1444     pub const fn is_unicast(&self) -> bool {
1445         !self.is_multicast()
1446     }
1447
1448     /// Returns `true` if the address is a unicast address with link-local scope,
1449     /// as defined in [RFC 4291].
1450     ///
1451     /// A unicast address has link-local scope if it has the prefix `fe80::/10`, as per [RFC 4291 section 2.4].
1452     /// Note that this encompasses more addresses than those defined in [RFC 4291 section 2.5.6],
1453     /// which describes "Link-Local IPv6 Unicast Addresses" as having the following stricter format:
1454     ///
1455     /// ```text
1456     /// | 10 bits  |         54 bits         |          64 bits           |
1457     /// +----------+-------------------------+----------------------------+
1458     /// |1111111010|           0             |       interface ID         |
1459     /// +----------+-------------------------+----------------------------+
1460     /// ```
1461     /// So while currently the only addresses with link-local scope an application will encounter are all in `fe80::/64`,
1462     /// this might change in the future with the publication of new standards. More addresses in `fe80::/10` could be allocated,
1463     /// and those addresses will have link-local scope.
1464     ///
1465     /// 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",
1466     /// this does not mean that the loopback address actually has link-local scope and this method will return `false` on it.
1467     ///
1468     /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
1469     /// [RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1470     /// [RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1471     /// [RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1472     /// [loopback address]: Ipv6Addr::LOCALHOST
1473     ///
1474     /// # Examples
1475     ///
1476     /// ```
1477     /// #![feature(ip)]
1478     ///
1479     /// use std::net::Ipv6Addr;
1480     ///
1481     /// // The loopback address (`::1`) does not actually have link-local scope.
1482     /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast_link_local(), false);
1483     ///
1484     /// // Only addresses in `fe80::/10` have link-local scope.
1485     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), false);
1486     /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1487     ///
1488     /// // Addresses outside the stricter `fe80::/64` also have link-local scope.
1489     /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0).is_unicast_link_local(), true);
1490     /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1491     /// ```
1492     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1493     #[unstable(feature = "ip", issue = "27709")]
1494     #[must_use]
1495     #[inline]
1496     pub const fn is_unicast_link_local(&self) -> bool {
1497         (self.segments()[0] & 0xffc0) == 0xfe80
1498     }
1499
1500     /// Returns [`true`] if this is an address reserved for documentation
1501     /// (`2001:db8::/32`).
1502     ///
1503     /// This property is defined in [IETF RFC 3849].
1504     ///
1505     /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1506     ///
1507     /// # Examples
1508     ///
1509     /// ```
1510     /// #![feature(ip)]
1511     ///
1512     /// use std::net::Ipv6Addr;
1513     ///
1514     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1515     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), 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_documentation(&self) -> bool {
1522         (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1523     }
1524
1525     /// Returns [`true`] if this is an address reserved for benchmarking (`2001:2::/48`).
1526     ///
1527     /// This property is defined in [IETF RFC 5180], where it is mistakenly specified as covering the range `2001:0200::/48`.
1528     /// This is corrected in [IETF RFC Errata 1752] to `2001:0002::/48`.
1529     ///
1530     /// [IETF RFC 5180]: https://tools.ietf.org/html/rfc5180
1531     /// [IETF RFC Errata 1752]: https://www.rfc-editor.org/errata_search.php?eid=1752
1532     ///
1533     /// ```
1534     /// #![feature(ip)]
1535     ///
1536     /// use std::net::Ipv6Addr;
1537     ///
1538     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc613, 0x0).is_benchmarking(), false);
1539     /// assert_eq!(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0).is_benchmarking(), true);
1540     /// ```
1541     #[unstable(feature = "ip", issue = "27709")]
1542     #[must_use]
1543     #[inline]
1544     pub const fn is_benchmarking(&self) -> bool {
1545         (self.segments()[0] == 0x2001) && (self.segments()[1] == 0x2) && (self.segments()[2] == 0)
1546     }
1547
1548     /// Returns [`true`] if the address is a globally routable unicast address.
1549     ///
1550     /// The following return false:
1551     ///
1552     /// - the loopback address
1553     /// - the link-local addresses
1554     /// - unique local addresses
1555     /// - the unspecified address
1556     /// - the address range reserved for documentation
1557     ///
1558     /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1559     ///
1560     /// ```no_rust
1561     /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1562     /// be supported in new implementations (i.e., new implementations must treat this prefix as
1563     /// Global Unicast).
1564     /// ```
1565     ///
1566     /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1567     ///
1568     /// # Examples
1569     ///
1570     /// ```
1571     /// #![feature(ip)]
1572     ///
1573     /// use std::net::Ipv6Addr;
1574     ///
1575     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1576     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1577     /// ```
1578     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1579     #[unstable(feature = "ip", issue = "27709")]
1580     #[must_use]
1581     #[inline]
1582     pub const fn is_unicast_global(&self) -> bool {
1583         self.is_unicast()
1584             && !self.is_loopback()
1585             && !self.is_unicast_link_local()
1586             && !self.is_unique_local()
1587             && !self.is_unspecified()
1588             && !self.is_documentation()
1589             && !self.is_benchmarking()
1590     }
1591
1592     /// Returns the address's multicast scope if the address is multicast.
1593     ///
1594     /// # Examples
1595     ///
1596     /// ```
1597     /// #![feature(ip)]
1598     ///
1599     /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1600     ///
1601     /// assert_eq!(
1602     ///     Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1603     ///     Some(Ipv6MulticastScope::Global)
1604     /// );
1605     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1606     /// ```
1607     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1608     #[unstable(feature = "ip", issue = "27709")]
1609     #[must_use]
1610     #[inline]
1611     pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1612         if self.is_multicast() {
1613             match self.segments()[0] & 0x000f {
1614                 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1615                 2 => Some(Ipv6MulticastScope::LinkLocal),
1616                 3 => Some(Ipv6MulticastScope::RealmLocal),
1617                 4 => Some(Ipv6MulticastScope::AdminLocal),
1618                 5 => Some(Ipv6MulticastScope::SiteLocal),
1619                 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1620                 14 => Some(Ipv6MulticastScope::Global),
1621                 _ => None,
1622             }
1623         } else {
1624             None
1625         }
1626     }
1627
1628     /// Returns [`true`] if this is a multicast address (`ff00::/8`).
1629     ///
1630     /// This property is defined by [IETF RFC 4291].
1631     ///
1632     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1633     ///
1634     /// # Examples
1635     ///
1636     /// ```
1637     /// use std::net::Ipv6Addr;
1638     ///
1639     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1640     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1641     /// ```
1642     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1643     #[stable(since = "1.7.0", feature = "ip_17")]
1644     #[must_use]
1645     #[inline]
1646     pub const fn is_multicast(&self) -> bool {
1647         (self.segments()[0] & 0xff00) == 0xff00
1648     }
1649
1650     /// Converts this address to an [`IPv4` address] if it's an [IPv4-mapped] address,
1651     /// as defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1652     ///
1653     /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1654     /// All addresses *not* starting with `::ffff` will return `None`.
1655     ///
1656     /// [`IPv4` address]: Ipv4Addr
1657     /// [IPv4-mapped]: Ipv6Addr
1658     /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1659     ///
1660     /// # Examples
1661     ///
1662     /// ```
1663     /// use std::net::{Ipv4Addr, Ipv6Addr};
1664     ///
1665     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1666     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1667     ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1668     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1669     /// ```
1670     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1671     #[stable(feature = "ipv6_to_ipv4_mapped", since = "1.63.0")]
1672     #[must_use = "this returns the result of the operation, \
1673                   without modifying the original"]
1674     #[inline]
1675     pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1676         match self.octets() {
1677             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1678                 Some(Ipv4Addr::new(a, b, c, d))
1679             }
1680             _ => None,
1681         }
1682     }
1683
1684     /// Converts this address to an [`IPv4` address] if it is either
1685     /// an [IPv4-compatible] address as defined in [IETF RFC 4291 section 2.5.5.1],
1686     /// or an [IPv4-mapped] address as defined in [IETF RFC 4291 section 2.5.5.2],
1687     /// otherwise returns [`None`].
1688     ///
1689     /// Note that this will return an [`IPv4` address] for the IPv6 loopback address `::1`. Use
1690     /// [`Ipv6Addr::to_ipv4_mapped`] to avoid this.
1691     ///
1692     /// `::a.b.c.d` and `::ffff:a.b.c.d` become `a.b.c.d`. `::1` becomes `0.0.0.1`.
1693     /// All addresses *not* starting with either all zeroes or `::ffff` will return `None`.
1694     ///
1695     /// [`IPv4` address]: Ipv4Addr
1696     /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
1697     /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
1698     /// [IETF RFC 4291 section 2.5.5.1]: https://tools.ietf.org/html/rfc4291#section-2.5.5.1
1699     /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1700     ///
1701     /// # Examples
1702     ///
1703     /// ```
1704     /// use std::net::{Ipv4Addr, Ipv6Addr};
1705     ///
1706     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1707     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1708     ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1709     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1710     ///            Some(Ipv4Addr::new(0, 0, 0, 1)));
1711     /// ```
1712     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1713     #[stable(feature = "rust1", since = "1.0.0")]
1714     #[must_use = "this returns the result of the operation, \
1715                   without modifying the original"]
1716     #[inline]
1717     pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1718         if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1719             let [a, b] = ab.to_be_bytes();
1720             let [c, d] = cd.to_be_bytes();
1721             Some(Ipv4Addr::new(a, b, c, d))
1722         } else {
1723             None
1724         }
1725     }
1726
1727     /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped addresses, otherwise it
1728     /// returns self wrapped in an `IpAddr::V6`.
1729     ///
1730     /// # Examples
1731     ///
1732     /// ```
1733     /// #![feature(ip)]
1734     /// use std::net::Ipv6Addr;
1735     ///
1736     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).is_loopback(), false);
1737     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).to_canonical().is_loopback(), true);
1738     /// ```
1739     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1740     #[unstable(feature = "ip", issue = "27709")]
1741     #[must_use = "this returns the result of the operation, \
1742                   without modifying the original"]
1743     #[inline]
1744     pub const fn to_canonical(&self) -> IpAddr {
1745         if let Some(mapped) = self.to_ipv4_mapped() {
1746             return IpAddr::V4(mapped);
1747         }
1748         IpAddr::V6(*self)
1749     }
1750
1751     /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1752     ///
1753     /// ```
1754     /// use std::net::Ipv6Addr;
1755     ///
1756     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1757     ///            [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1758     /// ```
1759     #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
1760     #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1761     #[must_use]
1762     #[inline]
1763     pub const fn octets(&self) -> [u8; 16] {
1764         self.octets
1765     }
1766 }
1767
1768 /// Write an Ipv6Addr, conforming to the canonical style described by
1769 /// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 impl fmt::Display for Ipv6Addr {
1772     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1773         // If there are no alignment requirements, write the IP address directly to `f`.
1774         // Otherwise, write it to a local buffer and then use `f.pad`.
1775         if f.precision().is_none() && f.width().is_none() {
1776             let segments = self.segments();
1777
1778             // Special case for :: and ::1; otherwise they get written with the
1779             // IPv4 formatter
1780             if self.is_unspecified() {
1781                 f.write_str("::")
1782             } else if self.is_loopback() {
1783                 f.write_str("::1")
1784             } else if let Some(ipv4) = self.to_ipv4() {
1785                 match segments[5] {
1786                     // IPv4 Compatible address
1787                     0 => write!(f, "::{}", ipv4),
1788                     // IPv4 Mapped address
1789                     0xffff => write!(f, "::ffff:{}", ipv4),
1790                     _ => unreachable!(),
1791                 }
1792             } else {
1793                 #[derive(Copy, Clone, Default)]
1794                 struct Span {
1795                     start: usize,
1796                     len: usize,
1797                 }
1798
1799                 // Find the inner 0 span
1800                 let zeroes = {
1801                     let mut longest = Span::default();
1802                     let mut current = Span::default();
1803
1804                     for (i, &segment) in segments.iter().enumerate() {
1805                         if segment == 0 {
1806                             if current.len == 0 {
1807                                 current.start = i;
1808                             }
1809
1810                             current.len += 1;
1811
1812                             if current.len > longest.len {
1813                                 longest = current;
1814                             }
1815                         } else {
1816                             current = Span::default();
1817                         }
1818                     }
1819
1820                     longest
1821                 };
1822
1823                 /// Write a colon-separated part of the address
1824                 #[inline]
1825                 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1826                     if let Some((first, tail)) = chunk.split_first() {
1827                         write!(f, "{:x}", first)?;
1828                         for segment in tail {
1829                             f.write_char(':')?;
1830                             write!(f, "{:x}", segment)?;
1831                         }
1832                     }
1833                     Ok(())
1834                 }
1835
1836                 if zeroes.len > 1 {
1837                     fmt_subslice(f, &segments[..zeroes.start])?;
1838                     f.write_str("::")?;
1839                     fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1840                 } else {
1841                     fmt_subslice(f, &segments)
1842                 }
1843             }
1844         } else {
1845             const LONGEST_IPV6_ADDR: &str = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
1846
1847             let mut buf = IpDisplayBuffer::<{ LONGEST_IPV6_ADDR.len() }>::new();
1848             // Buffer is long enough for the longest possible IPv6 address, so this should never fail.
1849             write!(buf, "{}", self).unwrap();
1850
1851             f.pad(buf.as_str())
1852         }
1853     }
1854 }
1855
1856 #[stable(feature = "rust1", since = "1.0.0")]
1857 impl fmt::Debug for Ipv6Addr {
1858     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1859         fmt::Display::fmt(self, fmt)
1860     }
1861 }
1862
1863 #[stable(feature = "ip_cmp", since = "1.16.0")]
1864 impl PartialEq<IpAddr> for Ipv6Addr {
1865     #[inline]
1866     fn eq(&self, other: &IpAddr) -> bool {
1867         match other {
1868             IpAddr::V4(_) => false,
1869             IpAddr::V6(v6) => self == v6,
1870         }
1871     }
1872 }
1873
1874 #[stable(feature = "ip_cmp", since = "1.16.0")]
1875 impl PartialEq<Ipv6Addr> for IpAddr {
1876     #[inline]
1877     fn eq(&self, other: &Ipv6Addr) -> bool {
1878         match self {
1879             IpAddr::V4(_) => false,
1880             IpAddr::V6(v6) => v6 == other,
1881         }
1882     }
1883 }
1884
1885 #[stable(feature = "rust1", since = "1.0.0")]
1886 impl PartialOrd for Ipv6Addr {
1887     #[inline]
1888     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1889         Some(self.cmp(other))
1890     }
1891 }
1892
1893 #[stable(feature = "ip_cmp", since = "1.16.0")]
1894 impl PartialOrd<Ipv6Addr> for IpAddr {
1895     #[inline]
1896     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1897         match self {
1898             IpAddr::V4(_) => Some(Ordering::Less),
1899             IpAddr::V6(v6) => v6.partial_cmp(other),
1900         }
1901     }
1902 }
1903
1904 #[stable(feature = "ip_cmp", since = "1.16.0")]
1905 impl PartialOrd<IpAddr> for Ipv6Addr {
1906     #[inline]
1907     fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1908         match other {
1909             IpAddr::V4(_) => Some(Ordering::Greater),
1910             IpAddr::V6(v6) => self.partial_cmp(v6),
1911         }
1912     }
1913 }
1914
1915 #[stable(feature = "rust1", since = "1.0.0")]
1916 impl Ord for Ipv6Addr {
1917     #[inline]
1918     fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1919         self.segments().cmp(&other.segments())
1920     }
1921 }
1922
1923 impl IntoInner<c::in6_addr> for Ipv6Addr {
1924     fn into_inner(self) -> c::in6_addr {
1925         c::in6_addr { s6_addr: self.octets }
1926     }
1927 }
1928 impl FromInner<c::in6_addr> for Ipv6Addr {
1929     #[inline]
1930     fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1931         Ipv6Addr { octets: addr.s6_addr }
1932     }
1933 }
1934
1935 #[stable(feature = "i128", since = "1.26.0")]
1936 impl From<Ipv6Addr> for u128 {
1937     /// Convert an `Ipv6Addr` into a host byte order `u128`.
1938     ///
1939     /// # Examples
1940     ///
1941     /// ```
1942     /// use std::net::Ipv6Addr;
1943     ///
1944     /// let addr = Ipv6Addr::new(
1945     ///     0x1020, 0x3040, 0x5060, 0x7080,
1946     ///     0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1947     /// );
1948     /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1949     /// ```
1950     #[inline]
1951     fn from(ip: Ipv6Addr) -> u128 {
1952         u128::from_be_bytes(ip.octets)
1953     }
1954 }
1955 #[stable(feature = "i128", since = "1.26.0")]
1956 impl From<u128> for Ipv6Addr {
1957     /// Convert a host byte order `u128` into an `Ipv6Addr`.
1958     ///
1959     /// # Examples
1960     ///
1961     /// ```
1962     /// use std::net::Ipv6Addr;
1963     ///
1964     /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1965     /// assert_eq!(
1966     ///     Ipv6Addr::new(
1967     ///         0x1020, 0x3040, 0x5060, 0x7080,
1968     ///         0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1969     ///     ),
1970     ///     addr);
1971     /// ```
1972     #[inline]
1973     fn from(ip: u128) -> Ipv6Addr {
1974         Ipv6Addr::from(ip.to_be_bytes())
1975     }
1976 }
1977
1978 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1979 impl From<[u8; 16]> for Ipv6Addr {
1980     /// Creates an `Ipv6Addr` from a sixteen element byte array.
1981     ///
1982     /// # Examples
1983     ///
1984     /// ```
1985     /// use std::net::Ipv6Addr;
1986     ///
1987     /// let addr = Ipv6Addr::from([
1988     ///     25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1989     ///     17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1990     /// ]);
1991     /// assert_eq!(
1992     ///     Ipv6Addr::new(
1993     ///         0x1918, 0x1716,
1994     ///         0x1514, 0x1312,
1995     ///         0x1110, 0x0f0e,
1996     ///         0x0d0c, 0x0b0a
1997     ///     ),
1998     ///     addr
1999     /// );
2000     /// ```
2001     #[inline]
2002     fn from(octets: [u8; 16]) -> Ipv6Addr {
2003         Ipv6Addr { octets }
2004     }
2005 }
2006
2007 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
2008 impl From<[u16; 8]> for Ipv6Addr {
2009     /// Creates an `Ipv6Addr` from an eight element 16-bit array.
2010     ///
2011     /// # Examples
2012     ///
2013     /// ```
2014     /// use std::net::Ipv6Addr;
2015     ///
2016     /// let addr = Ipv6Addr::from([
2017     ///     525u16, 524u16, 523u16, 522u16,
2018     ///     521u16, 520u16, 519u16, 518u16,
2019     /// ]);
2020     /// assert_eq!(
2021     ///     Ipv6Addr::new(
2022     ///         0x20d, 0x20c,
2023     ///         0x20b, 0x20a,
2024     ///         0x209, 0x208,
2025     ///         0x207, 0x206
2026     ///     ),
2027     ///     addr
2028     /// );
2029     /// ```
2030     #[inline]
2031     fn from(segments: [u16; 8]) -> Ipv6Addr {
2032         let [a, b, c, d, e, f, g, h] = segments;
2033         Ipv6Addr::new(a, b, c, d, e, f, g, h)
2034     }
2035 }
2036
2037 #[stable(feature = "ip_from_slice", since = "1.17.0")]
2038 impl From<[u8; 16]> for IpAddr {
2039     /// Creates an `IpAddr::V6` from a sixteen element byte array.
2040     ///
2041     /// # Examples
2042     ///
2043     /// ```
2044     /// use std::net::{IpAddr, Ipv6Addr};
2045     ///
2046     /// let addr = IpAddr::from([
2047     ///     25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
2048     ///     17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
2049     /// ]);
2050     /// assert_eq!(
2051     ///     IpAddr::V6(Ipv6Addr::new(
2052     ///         0x1918, 0x1716,
2053     ///         0x1514, 0x1312,
2054     ///         0x1110, 0x0f0e,
2055     ///         0x0d0c, 0x0b0a
2056     ///     )),
2057     ///     addr
2058     /// );
2059     /// ```
2060     #[inline]
2061     fn from(octets: [u8; 16]) -> IpAddr {
2062         IpAddr::V6(Ipv6Addr::from(octets))
2063     }
2064 }
2065
2066 #[stable(feature = "ip_from_slice", since = "1.17.0")]
2067 impl From<[u16; 8]> for IpAddr {
2068     /// Creates an `IpAddr::V6` from an eight element 16-bit array.
2069     ///
2070     /// # Examples
2071     ///
2072     /// ```
2073     /// use std::net::{IpAddr, Ipv6Addr};
2074     ///
2075     /// let addr = IpAddr::from([
2076     ///     525u16, 524u16, 523u16, 522u16,
2077     ///     521u16, 520u16, 519u16, 518u16,
2078     /// ]);
2079     /// assert_eq!(
2080     ///     IpAddr::V6(Ipv6Addr::new(
2081     ///         0x20d, 0x20c,
2082     ///         0x20b, 0x20a,
2083     ///         0x209, 0x208,
2084     ///         0x207, 0x206
2085     ///     )),
2086     ///     addr
2087     /// );
2088     /// ```
2089     #[inline]
2090     fn from(segments: [u16; 8]) -> IpAddr {
2091         IpAddr::V6(Ipv6Addr::from(segments))
2092     }
2093 }