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