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