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