]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/ip_addr.rs
Rollup merge of #106566 - clubby789:contiguous-weird-unicode, r=cjgillot
[rust.git] / library / std / src / net / ip_addr.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 use super::display_buffer::DisplayBuffer;
12
13 /// An IP address, either IPv4 or IPv6.
14 ///
15 /// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
16 /// respective documentation for more details.
17 ///
18 /// # Examples
19 ///
20 /// ```
21 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
22 ///
23 /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
24 /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
25 ///
26 /// assert_eq!("127.0.0.1".parse(), Ok(localhost_v4));
27 /// assert_eq!("::1".parse(), Ok(localhost_v6));
28 ///
29 /// assert_eq!(localhost_v4.is_ipv6(), false);
30 /// assert_eq!(localhost_v4.is_ipv4(), true);
31 /// ```
32 #[cfg_attr(not(test), rustc_diagnostic_item = "IpAddr")]
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 = DisplayBuffer::<{ 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     /// This corresponds to constant `IN6ADDR_LOOPBACK_INIT` or `in6addr_loopback` in other
1199     /// languages.
1200     ///
1201     /// # Examples
1202     ///
1203     /// ```
1204     /// use std::net::Ipv6Addr;
1205     ///
1206     /// let addr = Ipv6Addr::LOCALHOST;
1207     /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1208     /// ```
1209     #[doc(alias = "IN6ADDR_LOOPBACK_INIT")]
1210     #[doc(alias = "in6addr_loopback")]
1211     #[stable(feature = "ip_constructors", since = "1.30.0")]
1212     pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1213
1214     /// An IPv6 address representing the unspecified address: `::`
1215     ///
1216     /// This corresponds to constant `IN6ADDR_ANY_INIT` or `in6addr_any` in other languages.
1217     ///
1218     /// # Examples
1219     ///
1220     /// ```
1221     /// use std::net::Ipv6Addr;
1222     ///
1223     /// let addr = Ipv6Addr::UNSPECIFIED;
1224     /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1225     /// ```
1226     #[doc(alias = "IN6ADDR_ANY_INIT")]
1227     #[doc(alias = "in6addr_any")]
1228     #[stable(feature = "ip_constructors", since = "1.30.0")]
1229     pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1230
1231     /// Returns the eight 16-bit segments that make up this address.
1232     ///
1233     /// # Examples
1234     ///
1235     /// ```
1236     /// use std::net::Ipv6Addr;
1237     ///
1238     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1239     ///            [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1240     /// ```
1241     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1242     #[stable(feature = "rust1", since = "1.0.0")]
1243     #[must_use]
1244     #[inline]
1245     pub const fn segments(&self) -> [u16; 8] {
1246         // All elements in `self.octets` must be big endian.
1247         // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1248         let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.octets) };
1249         // We want native endian u16
1250         [
1251             u16::from_be(a),
1252             u16::from_be(b),
1253             u16::from_be(c),
1254             u16::from_be(d),
1255             u16::from_be(e),
1256             u16::from_be(f),
1257             u16::from_be(g),
1258             u16::from_be(h),
1259         ]
1260     }
1261
1262     /// Returns [`true`] for the special 'unspecified' address (`::`).
1263     ///
1264     /// This property is defined in [IETF RFC 4291].
1265     ///
1266     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1267     ///
1268     /// # Examples
1269     ///
1270     /// ```
1271     /// use std::net::Ipv6Addr;
1272     ///
1273     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1274     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1275     /// ```
1276     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1277     #[stable(since = "1.7.0", feature = "ip_17")]
1278     #[must_use]
1279     #[inline]
1280     pub const fn is_unspecified(&self) -> bool {
1281         u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1282     }
1283
1284     /// Returns [`true`] if this is the [loopback address] (`::1`),
1285     /// as defined in [IETF RFC 4291 section 2.5.3].
1286     ///
1287     /// Contrary to IPv4, in IPv6 there is only one loopback address.
1288     ///
1289     /// [loopback address]: Ipv6Addr::LOCALHOST
1290     /// [IETF RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1291     ///
1292     /// # Examples
1293     ///
1294     /// ```
1295     /// use std::net::Ipv6Addr;
1296     ///
1297     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1298     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1299     /// ```
1300     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1301     #[stable(since = "1.7.0", feature = "ip_17")]
1302     #[must_use]
1303     #[inline]
1304     pub const fn is_loopback(&self) -> bool {
1305         u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1306     }
1307
1308     /// Returns [`true`] if the address appears to be globally reachable
1309     /// as specified by the [IANA IPv6 Special-Purpose Address Registry].
1310     /// Whether or not an address is practically reachable will depend on your network configuration.
1311     ///
1312     /// Most IPv6 addresses are globally reachable;
1313     /// unless they are specifically defined as *not* globally reachable.
1314     ///
1315     /// Non-exhaustive list of notable addresses that are not globally reachable:
1316     /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified))
1317     /// - The [loopback address] ([`is_loopback`](Ipv6Addr::is_loopback))
1318     /// - IPv4-mapped addresses
1319     /// - Addresses reserved for benchmarking
1320     /// - Addresses reserved for documentation ([`is_documentation`](Ipv6Addr::is_documentation))
1321     /// - Unique local addresses ([`is_unique_local`](Ipv6Addr::is_unique_local))
1322     /// - Unicast addresses with link-local scope ([`is_unicast_link_local`](Ipv6Addr::is_unicast_link_local))
1323     ///
1324     /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv6 Special-Purpose Address Registry].
1325     ///
1326     /// Note that an address having global scope is not the same as being globally reachable,
1327     /// and there is no direct relation between the two concepts: There exist addresses with global scope
1328     /// that are not globally reachable (for example unique local addresses),
1329     /// and addresses that are globally reachable without having global scope
1330     /// (multicast addresses with non-global scope).
1331     ///
1332     /// [IANA IPv6 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
1333     /// [unspecified address]: Ipv6Addr::UNSPECIFIED
1334     /// [loopback address]: Ipv6Addr::LOCALHOST
1335     ///
1336     /// # Examples
1337     ///
1338     /// ```
1339     /// #![feature(ip)]
1340     ///
1341     /// use std::net::Ipv6Addr;
1342     ///
1343     /// // Most IPv6 addresses are globally reachable:
1344     /// assert_eq!(Ipv6Addr::new(0x26, 0, 0x1c9, 0, 0, 0xafc8, 0x10, 0x1).is_global(), true);
1345     ///
1346     /// // However some addresses have been assigned a special meaning
1347     /// // that makes them not globally reachable. Some examples are:
1348     ///
1349     /// // The unspecified address (`::`)
1350     /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_global(), false);
1351     ///
1352     /// // The loopback address (`::1`)
1353     /// assert_eq!(Ipv6Addr::LOCALHOST.is_global(), false);
1354     ///
1355     /// // IPv4-mapped addresses (`::ffff:0:0/96`)
1356     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), false);
1357     ///
1358     /// // Addresses reserved for benchmarking (`2001:2::/48`)
1359     /// assert_eq!(Ipv6Addr::new(0x2001, 2, 0, 0, 0, 0, 0, 1,).is_global(), false);
1360     ///
1361     /// // Addresses reserved for documentation (`2001:db8::/32`)
1362     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).is_global(), false);
1363     ///
1364     /// // Unique local addresses (`fc00::/7`)
1365     /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1366     ///
1367     /// // Unicast addresses with link-local scope (`fe80::/10`)
1368     /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1369     ///
1370     /// // For a complete overview see the IANA IPv6 Special-Purpose Address Registry.
1371     /// ```
1372     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1373     #[unstable(feature = "ip", issue = "27709")]
1374     #[must_use]
1375     #[inline]
1376     pub const fn is_global(&self) -> bool {
1377         !(self.is_unspecified()
1378             || self.is_loopback()
1379             // IPv4-mapped Address (`::ffff:0:0/96`)
1380             || matches!(self.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
1381             // IPv4-IPv6 Translat. (`64:ff9b:1::/48`)
1382             || matches!(self.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
1383             // Discard-Only Address Block (`100::/64`)
1384             || matches!(self.segments(), [0x100, 0, 0, 0, _, _, _, _])
1385             // IETF Protocol Assignments (`2001::/23`)
1386             || (matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
1387                 && !(
1388                     // Port Control Protocol Anycast (`2001:1::1`)
1389                     u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
1390                     // Traversal Using Relays around NAT Anycast (`2001:1::2`)
1391                     || u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
1392                     // AMT (`2001:3::/32`)
1393                     || matches!(self.segments(), [0x2001, 3, _, _, _, _, _, _])
1394                     // AS112-v6 (`2001:4:112::/48`)
1395                     || matches!(self.segments(), [0x2001, 4, 0x112, _, _, _, _, _])
1396                     // ORCHIDv2 (`2001:20::/28`)
1397                     || matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b >= 0x20 && b <= 0x2F)
1398                 ))
1399             || self.is_documentation()
1400             || self.is_unique_local()
1401             || self.is_unicast_link_local())
1402     }
1403
1404     /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1405     ///
1406     /// This property is defined in [IETF RFC 4193].
1407     ///
1408     /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1409     ///
1410     /// # Examples
1411     ///
1412     /// ```
1413     /// #![feature(ip)]
1414     ///
1415     /// use std::net::Ipv6Addr;
1416     ///
1417     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1418     /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1419     /// ```
1420     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1421     #[unstable(feature = "ip", issue = "27709")]
1422     #[must_use]
1423     #[inline]
1424     pub const fn is_unique_local(&self) -> bool {
1425         (self.segments()[0] & 0xfe00) == 0xfc00
1426     }
1427
1428     /// Returns [`true`] if this is a unicast address, as defined by [IETF RFC 4291].
1429     /// Any address that is not a [multicast address] (`ff00::/8`) is unicast.
1430     ///
1431     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1432     /// [multicast address]: Ipv6Addr::is_multicast
1433     ///
1434     /// # Examples
1435     ///
1436     /// ```
1437     /// #![feature(ip)]
1438     ///
1439     /// use std::net::Ipv6Addr;
1440     ///
1441     /// // The unspecified and loopback addresses are unicast.
1442     /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_unicast(), true);
1443     /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast(), true);
1444     ///
1445     /// // Any address that is not a multicast address (`ff00::/8`) is unicast.
1446     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast(), true);
1447     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_unicast(), false);
1448     /// ```
1449     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1450     #[unstable(feature = "ip", issue = "27709")]
1451     #[must_use]
1452     #[inline]
1453     pub const fn is_unicast(&self) -> bool {
1454         !self.is_multicast()
1455     }
1456
1457     /// Returns `true` if the address is a unicast address with link-local scope,
1458     /// as defined in [RFC 4291].
1459     ///
1460     /// A unicast address has link-local scope if it has the prefix `fe80::/10`, as per [RFC 4291 section 2.4].
1461     /// Note that this encompasses more addresses than those defined in [RFC 4291 section 2.5.6],
1462     /// which describes "Link-Local IPv6 Unicast Addresses" as having the following stricter format:
1463     ///
1464     /// ```text
1465     /// | 10 bits  |         54 bits         |          64 bits           |
1466     /// +----------+-------------------------+----------------------------+
1467     /// |1111111010|           0             |       interface ID         |
1468     /// +----------+-------------------------+----------------------------+
1469     /// ```
1470     /// So while currently the only addresses with link-local scope an application will encounter are all in `fe80::/64`,
1471     /// this might change in the future with the publication of new standards. More addresses in `fe80::/10` could be allocated,
1472     /// and those addresses will have link-local scope.
1473     ///
1474     /// 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",
1475     /// this does not mean that the loopback address actually has link-local scope and this method will return `false` on it.
1476     ///
1477     /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
1478     /// [RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1479     /// [RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1480     /// [RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1481     /// [loopback address]: Ipv6Addr::LOCALHOST
1482     ///
1483     /// # Examples
1484     ///
1485     /// ```
1486     /// #![feature(ip)]
1487     ///
1488     /// use std::net::Ipv6Addr;
1489     ///
1490     /// // The loopback address (`::1`) does not actually have link-local scope.
1491     /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast_link_local(), false);
1492     ///
1493     /// // Only addresses in `fe80::/10` have link-local scope.
1494     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), false);
1495     /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1496     ///
1497     /// // Addresses outside the stricter `fe80::/64` also have link-local scope.
1498     /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0).is_unicast_link_local(), true);
1499     /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1500     /// ```
1501     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1502     #[unstable(feature = "ip", issue = "27709")]
1503     #[must_use]
1504     #[inline]
1505     pub const fn is_unicast_link_local(&self) -> bool {
1506         (self.segments()[0] & 0xffc0) == 0xfe80
1507     }
1508
1509     /// Returns [`true`] if this is an address reserved for documentation
1510     /// (`2001:db8::/32`).
1511     ///
1512     /// This property is defined in [IETF RFC 3849].
1513     ///
1514     /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1515     ///
1516     /// # Examples
1517     ///
1518     /// ```
1519     /// #![feature(ip)]
1520     ///
1521     /// use std::net::Ipv6Addr;
1522     ///
1523     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1524     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1525     /// ```
1526     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1527     #[unstable(feature = "ip", issue = "27709")]
1528     #[must_use]
1529     #[inline]
1530     pub const fn is_documentation(&self) -> bool {
1531         (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1532     }
1533
1534     /// Returns [`true`] if this is an address reserved for benchmarking (`2001:2::/48`).
1535     ///
1536     /// This property is defined in [IETF RFC 5180], where it is mistakenly specified as covering the range `2001:0200::/48`.
1537     /// This is corrected in [IETF RFC Errata 1752] to `2001:0002::/48`.
1538     ///
1539     /// [IETF RFC 5180]: https://tools.ietf.org/html/rfc5180
1540     /// [IETF RFC Errata 1752]: https://www.rfc-editor.org/errata_search.php?eid=1752
1541     ///
1542     /// ```
1543     /// #![feature(ip)]
1544     ///
1545     /// use std::net::Ipv6Addr;
1546     ///
1547     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc613, 0x0).is_benchmarking(), false);
1548     /// assert_eq!(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0).is_benchmarking(), true);
1549     /// ```
1550     #[unstable(feature = "ip", issue = "27709")]
1551     #[must_use]
1552     #[inline]
1553     pub const fn is_benchmarking(&self) -> bool {
1554         (self.segments()[0] == 0x2001) && (self.segments()[1] == 0x2) && (self.segments()[2] == 0)
1555     }
1556
1557     /// Returns [`true`] if the address is a globally routable unicast address.
1558     ///
1559     /// The following return false:
1560     ///
1561     /// - the loopback address
1562     /// - the link-local addresses
1563     /// - unique local addresses
1564     /// - the unspecified address
1565     /// - the address range reserved for documentation
1566     ///
1567     /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1568     ///
1569     /// ```no_rust
1570     /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1571     /// be supported in new implementations (i.e., new implementations must treat this prefix as
1572     /// Global Unicast).
1573     /// ```
1574     ///
1575     /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1576     ///
1577     /// # Examples
1578     ///
1579     /// ```
1580     /// #![feature(ip)]
1581     ///
1582     /// use std::net::Ipv6Addr;
1583     ///
1584     /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1585     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1586     /// ```
1587     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1588     #[unstable(feature = "ip", issue = "27709")]
1589     #[must_use]
1590     #[inline]
1591     pub const fn is_unicast_global(&self) -> bool {
1592         self.is_unicast()
1593             && !self.is_loopback()
1594             && !self.is_unicast_link_local()
1595             && !self.is_unique_local()
1596             && !self.is_unspecified()
1597             && !self.is_documentation()
1598             && !self.is_benchmarking()
1599     }
1600
1601     /// Returns the address's multicast scope if the address is multicast.
1602     ///
1603     /// # Examples
1604     ///
1605     /// ```
1606     /// #![feature(ip)]
1607     ///
1608     /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1609     ///
1610     /// assert_eq!(
1611     ///     Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1612     ///     Some(Ipv6MulticastScope::Global)
1613     /// );
1614     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1615     /// ```
1616     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1617     #[unstable(feature = "ip", issue = "27709")]
1618     #[must_use]
1619     #[inline]
1620     pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1621         if self.is_multicast() {
1622             match self.segments()[0] & 0x000f {
1623                 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1624                 2 => Some(Ipv6MulticastScope::LinkLocal),
1625                 3 => Some(Ipv6MulticastScope::RealmLocal),
1626                 4 => Some(Ipv6MulticastScope::AdminLocal),
1627                 5 => Some(Ipv6MulticastScope::SiteLocal),
1628                 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1629                 14 => Some(Ipv6MulticastScope::Global),
1630                 _ => None,
1631             }
1632         } else {
1633             None
1634         }
1635     }
1636
1637     /// Returns [`true`] if this is a multicast address (`ff00::/8`).
1638     ///
1639     /// This property is defined by [IETF RFC 4291].
1640     ///
1641     /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1642     ///
1643     /// # Examples
1644     ///
1645     /// ```
1646     /// use std::net::Ipv6Addr;
1647     ///
1648     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1649     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1650     /// ```
1651     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1652     #[stable(since = "1.7.0", feature = "ip_17")]
1653     #[must_use]
1654     #[inline]
1655     pub const fn is_multicast(&self) -> bool {
1656         (self.segments()[0] & 0xff00) == 0xff00
1657     }
1658
1659     /// Converts this address to an [`IPv4` address] if it's an [IPv4-mapped] address,
1660     /// as defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1661     ///
1662     /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1663     /// All addresses *not* starting with `::ffff` will return `None`.
1664     ///
1665     /// [`IPv4` address]: Ipv4Addr
1666     /// [IPv4-mapped]: Ipv6Addr
1667     /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1668     ///
1669     /// # Examples
1670     ///
1671     /// ```
1672     /// use std::net::{Ipv4Addr, Ipv6Addr};
1673     ///
1674     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1675     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1676     ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1677     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1678     /// ```
1679     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1680     #[stable(feature = "ipv6_to_ipv4_mapped", since = "1.63.0")]
1681     #[must_use = "this returns the result of the operation, \
1682                   without modifying the original"]
1683     #[inline]
1684     pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1685         match self.octets() {
1686             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1687                 Some(Ipv4Addr::new(a, b, c, d))
1688             }
1689             _ => None,
1690         }
1691     }
1692
1693     /// Converts this address to an [`IPv4` address] if it is either
1694     /// an [IPv4-compatible] address as defined in [IETF RFC 4291 section 2.5.5.1],
1695     /// or an [IPv4-mapped] address as defined in [IETF RFC 4291 section 2.5.5.2],
1696     /// otherwise returns [`None`].
1697     ///
1698     /// Note that this will return an [`IPv4` address] for the IPv6 loopback address `::1`. Use
1699     /// [`Ipv6Addr::to_ipv4_mapped`] to avoid this.
1700     ///
1701     /// `::a.b.c.d` and `::ffff:a.b.c.d` become `a.b.c.d`. `::1` becomes `0.0.0.1`.
1702     /// All addresses *not* starting with either all zeroes or `::ffff` will return `None`.
1703     ///
1704     /// [`IPv4` address]: Ipv4Addr
1705     /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
1706     /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
1707     /// [IETF RFC 4291 section 2.5.5.1]: https://tools.ietf.org/html/rfc4291#section-2.5.5.1
1708     /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1709     ///
1710     /// # Examples
1711     ///
1712     /// ```
1713     /// use std::net::{Ipv4Addr, Ipv6Addr};
1714     ///
1715     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1716     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1717     ///            Some(Ipv4Addr::new(192, 10, 2, 255)));
1718     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1719     ///            Some(Ipv4Addr::new(0, 0, 0, 1)));
1720     /// ```
1721     #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1722     #[stable(feature = "rust1", since = "1.0.0")]
1723     #[must_use = "this returns the result of the operation, \
1724                   without modifying the original"]
1725     #[inline]
1726     pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1727         if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1728             let [a, b] = ab.to_be_bytes();
1729             let [c, d] = cd.to_be_bytes();
1730             Some(Ipv4Addr::new(a, b, c, d))
1731         } else {
1732             None
1733         }
1734     }
1735
1736     /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped addresses, otherwise it
1737     /// returns self wrapped in an `IpAddr::V6`.
1738     ///
1739     /// # Examples
1740     ///
1741     /// ```
1742     /// #![feature(ip)]
1743     /// use std::net::Ipv6Addr;
1744     ///
1745     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).is_loopback(), false);
1746     /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).to_canonical().is_loopback(), true);
1747     /// ```
1748     #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1749     #[unstable(feature = "ip", issue = "27709")]
1750     #[must_use = "this returns the result of the operation, \
1751                   without modifying the original"]
1752     #[inline]
1753     pub const fn to_canonical(&self) -> IpAddr {
1754         if let Some(mapped) = self.to_ipv4_mapped() {
1755             return IpAddr::V4(mapped);
1756         }
1757         IpAddr::V6(*self)
1758     }
1759
1760     /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1761     ///
1762     /// ```
1763     /// use std::net::Ipv6Addr;
1764     ///
1765     /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1766     ///            [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1767     /// ```
1768     #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
1769     #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1770     #[must_use]
1771     #[inline]
1772     pub const fn octets(&self) -> [u8; 16] {
1773         self.octets
1774     }
1775 }
1776
1777 /// Write an Ipv6Addr, conforming to the canonical style described by
1778 /// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1779 #[stable(feature = "rust1", since = "1.0.0")]
1780 impl fmt::Display for Ipv6Addr {
1781     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1782         // If there are no alignment requirements, write the IP address directly to `f`.
1783         // Otherwise, write it to a local buffer and then use `f.pad`.
1784         if f.precision().is_none() && f.width().is_none() {
1785             let segments = self.segments();
1786
1787             // Special case for :: and ::1; otherwise they get written with the
1788             // IPv4 formatter
1789             if self.is_unspecified() {
1790                 f.write_str("::")
1791             } else if self.is_loopback() {
1792                 f.write_str("::1")
1793             } else if let Some(ipv4) = self.to_ipv4() {
1794                 match segments[5] {
1795                     // IPv4 Compatible address
1796                     0 => write!(f, "::{}", ipv4),
1797                     // IPv4 Mapped address
1798                     0xffff => write!(f, "::ffff:{}", ipv4),
1799                     _ => unreachable!(),
1800                 }
1801             } else {
1802                 #[derive(Copy, Clone, Default)]
1803                 struct Span {
1804                     start: usize,
1805                     len: usize,
1806                 }
1807
1808                 // Find the inner 0 span
1809                 let zeroes = {
1810                     let mut longest = Span::default();
1811                     let mut current = Span::default();
1812
1813                     for (i, &segment) in segments.iter().enumerate() {
1814                         if segment == 0 {
1815                             if current.len == 0 {
1816                                 current.start = i;
1817                             }
1818
1819                             current.len += 1;
1820
1821                             if current.len > longest.len {
1822                                 longest = current;
1823                             }
1824                         } else {
1825                             current = Span::default();
1826                         }
1827                     }
1828
1829                     longest
1830                 };
1831
1832                 /// Write a colon-separated part of the address
1833                 #[inline]
1834                 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1835                     if let Some((first, tail)) = chunk.split_first() {
1836                         write!(f, "{:x}", first)?;
1837                         for segment in tail {
1838                             f.write_char(':')?;
1839                             write!(f, "{:x}", segment)?;
1840                         }
1841                     }
1842                     Ok(())
1843                 }
1844
1845                 if zeroes.len > 1 {
1846                     fmt_subslice(f, &segments[..zeroes.start])?;
1847                     f.write_str("::")?;
1848                     fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1849                 } else {
1850                     fmt_subslice(f, &segments)
1851                 }
1852             }
1853         } else {
1854             const LONGEST_IPV6_ADDR: &str = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
1855
1856             let mut buf = DisplayBuffer::<{ LONGEST_IPV6_ADDR.len() }>::new();
1857             // Buffer is long enough for the longest possible IPv6 address, so this should never fail.
1858             write!(buf, "{}", self).unwrap();
1859
1860             f.pad(buf.as_str())
1861         }
1862     }
1863 }
1864
1865 #[stable(feature = "rust1", since = "1.0.0")]
1866 impl fmt::Debug for Ipv6Addr {
1867     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1868         fmt::Display::fmt(self, fmt)
1869     }
1870 }
1871
1872 #[stable(feature = "ip_cmp", since = "1.16.0")]
1873 impl PartialEq<IpAddr> for Ipv6Addr {
1874     #[inline]
1875     fn eq(&self, other: &IpAddr) -> bool {
1876         match other {
1877             IpAddr::V4(_) => false,
1878             IpAddr::V6(v6) => self == v6,
1879         }
1880     }
1881 }
1882
1883 #[stable(feature = "ip_cmp", since = "1.16.0")]
1884 impl PartialEq<Ipv6Addr> for IpAddr {
1885     #[inline]
1886     fn eq(&self, other: &Ipv6Addr) -> bool {
1887         match self {
1888             IpAddr::V4(_) => false,
1889             IpAddr::V6(v6) => v6 == other,
1890         }
1891     }
1892 }
1893
1894 #[stable(feature = "rust1", since = "1.0.0")]
1895 impl PartialOrd for Ipv6Addr {
1896     #[inline]
1897     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1898         Some(self.cmp(other))
1899     }
1900 }
1901
1902 #[stable(feature = "ip_cmp", since = "1.16.0")]
1903 impl PartialOrd<Ipv6Addr> for IpAddr {
1904     #[inline]
1905     fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1906         match self {
1907             IpAddr::V4(_) => Some(Ordering::Less),
1908             IpAddr::V6(v6) => v6.partial_cmp(other),
1909         }
1910     }
1911 }
1912
1913 #[stable(feature = "ip_cmp", since = "1.16.0")]
1914 impl PartialOrd<IpAddr> for Ipv6Addr {
1915     #[inline]
1916     fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1917         match other {
1918             IpAddr::V4(_) => Some(Ordering::Greater),
1919             IpAddr::V6(v6) => self.partial_cmp(v6),
1920         }
1921     }
1922 }
1923
1924 #[stable(feature = "rust1", since = "1.0.0")]
1925 impl Ord for Ipv6Addr {
1926     #[inline]
1927     fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1928         self.segments().cmp(&other.segments())
1929     }
1930 }
1931
1932 impl IntoInner<c::in6_addr> for Ipv6Addr {
1933     fn into_inner(self) -> c::in6_addr {
1934         c::in6_addr { s6_addr: self.octets }
1935     }
1936 }
1937 impl FromInner<c::in6_addr> for Ipv6Addr {
1938     #[inline]
1939     fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1940         Ipv6Addr { octets: addr.s6_addr }
1941     }
1942 }
1943
1944 #[stable(feature = "i128", since = "1.26.0")]
1945 impl From<Ipv6Addr> for u128 {
1946     /// Convert an `Ipv6Addr` into a host byte order `u128`.
1947     ///
1948     /// # Examples
1949     ///
1950     /// ```
1951     /// use std::net::Ipv6Addr;
1952     ///
1953     /// let addr = Ipv6Addr::new(
1954     ///     0x1020, 0x3040, 0x5060, 0x7080,
1955     ///     0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1956     /// );
1957     /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1958     /// ```
1959     #[inline]
1960     fn from(ip: Ipv6Addr) -> u128 {
1961         u128::from_be_bytes(ip.octets)
1962     }
1963 }
1964 #[stable(feature = "i128", since = "1.26.0")]
1965 impl From<u128> for Ipv6Addr {
1966     /// Convert a host byte order `u128` into an `Ipv6Addr`.
1967     ///
1968     /// # Examples
1969     ///
1970     /// ```
1971     /// use std::net::Ipv6Addr;
1972     ///
1973     /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1974     /// assert_eq!(
1975     ///     Ipv6Addr::new(
1976     ///         0x1020, 0x3040, 0x5060, 0x7080,
1977     ///         0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1978     ///     ),
1979     ///     addr);
1980     /// ```
1981     #[inline]
1982     fn from(ip: u128) -> Ipv6Addr {
1983         Ipv6Addr::from(ip.to_be_bytes())
1984     }
1985 }
1986
1987 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1988 impl From<[u8; 16]> for Ipv6Addr {
1989     /// Creates an `Ipv6Addr` from a sixteen element byte array.
1990     ///
1991     /// # Examples
1992     ///
1993     /// ```
1994     /// use std::net::Ipv6Addr;
1995     ///
1996     /// let addr = Ipv6Addr::from([
1997     ///     25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1998     ///     17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1999     /// ]);
2000     /// assert_eq!(
2001     ///     Ipv6Addr::new(
2002     ///         0x1918, 0x1716,
2003     ///         0x1514, 0x1312,
2004     ///         0x1110, 0x0f0e,
2005     ///         0x0d0c, 0x0b0a
2006     ///     ),
2007     ///     addr
2008     /// );
2009     /// ```
2010     #[inline]
2011     fn from(octets: [u8; 16]) -> Ipv6Addr {
2012         Ipv6Addr { octets }
2013     }
2014 }
2015
2016 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
2017 impl From<[u16; 8]> for Ipv6Addr {
2018     /// Creates an `Ipv6Addr` from an eight element 16-bit array.
2019     ///
2020     /// # Examples
2021     ///
2022     /// ```
2023     /// use std::net::Ipv6Addr;
2024     ///
2025     /// let addr = Ipv6Addr::from([
2026     ///     525u16, 524u16, 523u16, 522u16,
2027     ///     521u16, 520u16, 519u16, 518u16,
2028     /// ]);
2029     /// assert_eq!(
2030     ///     Ipv6Addr::new(
2031     ///         0x20d, 0x20c,
2032     ///         0x20b, 0x20a,
2033     ///         0x209, 0x208,
2034     ///         0x207, 0x206
2035     ///     ),
2036     ///     addr
2037     /// );
2038     /// ```
2039     #[inline]
2040     fn from(segments: [u16; 8]) -> Ipv6Addr {
2041         let [a, b, c, d, e, f, g, h] = segments;
2042         Ipv6Addr::new(a, b, c, d, e, f, g, h)
2043     }
2044 }
2045
2046 #[stable(feature = "ip_from_slice", since = "1.17.0")]
2047 impl From<[u8; 16]> for IpAddr {
2048     /// Creates an `IpAddr::V6` from a sixteen element byte array.
2049     ///
2050     /// # Examples
2051     ///
2052     /// ```
2053     /// use std::net::{IpAddr, Ipv6Addr};
2054     ///
2055     /// let addr = IpAddr::from([
2056     ///     25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
2057     ///     17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
2058     /// ]);
2059     /// assert_eq!(
2060     ///     IpAddr::V6(Ipv6Addr::new(
2061     ///         0x1918, 0x1716,
2062     ///         0x1514, 0x1312,
2063     ///         0x1110, 0x0f0e,
2064     ///         0x0d0c, 0x0b0a
2065     ///     )),
2066     ///     addr
2067     /// );
2068     /// ```
2069     #[inline]
2070     fn from(octets: [u8; 16]) -> IpAddr {
2071         IpAddr::V6(Ipv6Addr::from(octets))
2072     }
2073 }
2074
2075 #[stable(feature = "ip_from_slice", since = "1.17.0")]
2076 impl From<[u16; 8]> for IpAddr {
2077     /// Creates an `IpAddr::V6` from an eight element 16-bit array.
2078     ///
2079     /// # Examples
2080     ///
2081     /// ```
2082     /// use std::net::{IpAddr, Ipv6Addr};
2083     ///
2084     /// let addr = IpAddr::from([
2085     ///     525u16, 524u16, 523u16, 522u16,
2086     ///     521u16, 520u16, 519u16, 518u16,
2087     /// ]);
2088     /// assert_eq!(
2089     ///     IpAddr::V6(Ipv6Addr::new(
2090     ///         0x20d, 0x20c,
2091     ///         0x20b, 0x20a,
2092     ///         0x209, 0x208,
2093     ///         0x207, 0x206
2094     ///     )),
2095     ///     addr
2096     /// );
2097     /// ```
2098     #[inline]
2099     fn from(segments: [u16; 8]) -> IpAddr {
2100         IpAddr::V6(Ipv6Addr::from(segments))
2101     }
2102 }