3 reason = "extra functionality has not been \
4 scrutinized to the level that it should \
9 // Tests for this module
10 #[cfg(all(test, not(target_os = "emscripten")))]
13 use crate::cmp::Ordering;
14 use crate::fmt::{self, Write as FmtWrite};
16 use crate::io::Write as IoWrite;
17 use crate::mem::transmute;
18 use crate::sys::net::netc as c;
19 use crate::sys_common::{AsInner, FromInner, IntoInner};
21 /// An IP address, either IPv4 or IPv6.
23 /// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
24 /// respective documentation for more details.
26 /// The size of an `IpAddr` instance may vary depending on the target operating
32 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
34 /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
35 /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
37 /// assert_eq!("127.0.0.1".parse(), Ok(localhost_v4));
38 /// assert_eq!("::1".parse(), Ok(localhost_v6));
40 /// assert_eq!(localhost_v4.is_ipv6(), false);
41 /// assert_eq!(localhost_v4.is_ipv4(), true);
43 #[stable(feature = "ip_addr", since = "1.7.0")]
44 #[derive(Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
47 #[stable(feature = "ip_addr", since = "1.7.0")]
48 V4(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv4Addr),
50 #[stable(feature = "ip_addr", since = "1.7.0")]
51 V6(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv6Addr),
56 /// IPv4 addresses are defined as 32-bit integers in [IETF RFC 791].
57 /// They are usually represented as four octets.
59 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
61 /// The size of an `Ipv4Addr` struct may vary depending on the target operating
64 /// [IETF RFC 791]: https://tools.ietf.org/html/rfc791
66 /// # Textual representation
68 /// `Ipv4Addr` provides a [`FromStr`] implementation. The four octets are in decimal
69 /// notation, divided by `.` (this is called "dot-decimal notation").
70 /// Notably, octal numbers and hexadecimal numbers are not allowed per [IETF RFC 6943].
72 /// [IETF RFC 6943]: https://tools.ietf.org/html/rfc6943#section-3.1.1
73 /// [`FromStr`]: crate::str::FromStr
78 /// use std::net::Ipv4Addr;
80 /// let localhost = Ipv4Addr::new(127, 0, 0, 1);
81 /// assert_eq!("127.0.0.1".parse(), Ok(localhost));
82 /// assert_eq!(localhost.is_loopback(), true);
85 #[stable(feature = "rust1", since = "1.0.0")]
92 /// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
93 /// They are usually represented as eight 16-bit segments.
95 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
97 /// The size of an `Ipv6Addr` struct may vary depending on the target operating
100 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
102 /// # Textual representation
104 /// `Ipv6Addr` provides a [`FromStr`] implementation. There are many ways to represent
105 /// an IPv6 address in text, but in general, each segments is written in hexadecimal
106 /// notation, and segments are separated by `:`. For more information, see
109 /// [`FromStr`]: crate::str::FromStr
110 /// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952
115 /// use std::net::Ipv6Addr;
117 /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
118 /// assert_eq!("::1".parse(), Ok(localhost));
119 /// assert_eq!(localhost.is_loopback(), true);
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub struct Ipv6Addr {
127 #[allow(missing_docs)]
128 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
129 pub enum Ipv6MulticastScope {
140 /// Returns [`true`] for the special 'unspecified' address.
142 /// See the documentation for [`Ipv4Addr::is_unspecified()`] and
143 /// [`Ipv6Addr::is_unspecified()`] for more details.
148 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
150 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
151 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
153 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
154 #[stable(feature = "ip_shared", since = "1.12.0")]
156 pub const fn is_unspecified(&self) -> bool {
158 IpAddr::V4(ip) => ip.is_unspecified(),
159 IpAddr::V6(ip) => ip.is_unspecified(),
163 /// Returns [`true`] if this is a loopback address.
165 /// See the documentation for [`Ipv4Addr::is_loopback()`] and
166 /// [`Ipv6Addr::is_loopback()`] for more details.
171 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
173 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
174 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
176 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
177 #[stable(feature = "ip_shared", since = "1.12.0")]
179 pub const fn is_loopback(&self) -> bool {
181 IpAddr::V4(ip) => ip.is_loopback(),
182 IpAddr::V6(ip) => ip.is_loopback(),
186 /// Returns [`true`] if the address appears to be globally routable.
188 /// See the documentation for [`Ipv4Addr::is_global()`] and
189 /// [`Ipv6Addr::is_global()`] for more details.
196 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
198 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true);
199 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true);
201 #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
203 pub const fn is_global(&self) -> bool {
205 IpAddr::V4(ip) => ip.is_global(),
206 IpAddr::V6(ip) => ip.is_global(),
210 /// Returns [`true`] if this is a multicast address.
212 /// See the documentation for [`Ipv4Addr::is_multicast()`] and
213 /// [`Ipv6Addr::is_multicast()`] for more details.
218 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
220 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
221 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
223 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
224 #[stable(feature = "ip_shared", since = "1.12.0")]
226 pub const fn is_multicast(&self) -> bool {
228 IpAddr::V4(ip) => ip.is_multicast(),
229 IpAddr::V6(ip) => ip.is_multicast(),
233 /// Returns [`true`] if this address is in a range designated for documentation.
235 /// See the documentation for [`Ipv4Addr::is_documentation()`] and
236 /// [`Ipv6Addr::is_documentation()`] for more details.
243 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
245 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
247 /// IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(),
251 #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
253 pub const fn is_documentation(&self) -> bool {
255 IpAddr::V4(ip) => ip.is_documentation(),
256 IpAddr::V6(ip) => ip.is_documentation(),
260 /// Returns [`true`] if this address is an [`IPv4` address], and [`false`]
263 /// [`IPv4` address]: IpAddr::V4
268 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
270 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
271 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false);
273 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
274 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
276 pub const fn is_ipv4(&self) -> bool {
277 matches!(self, IpAddr::V4(_))
280 /// Returns [`true`] if this address is an [`IPv6` address], and [`false`]
283 /// [`IPv6` address]: IpAddr::V6
288 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
290 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
291 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true);
293 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
294 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
296 pub const fn is_ipv6(&self) -> bool {
297 matches!(self, IpAddr::V6(_))
302 /// Creates a new IPv4 address from four eight-bit octets.
304 /// The result will represent the IP address `a`.`b`.`c`.`d`.
309 /// use std::net::Ipv4Addr;
311 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
313 #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
314 #[stable(feature = "rust1", since = "1.0.0")]
316 pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
317 // `s_addr` is stored as BE on all machine and the array is in BE order.
318 // So the native endian conversion method is used so that it's never swapped.
319 Ipv4Addr { inner: c::in_addr { s_addr: u32::from_ne_bytes([a, b, c, d]) } }
322 /// An IPv4 address with the address pointing to localhost: 127.0.0.1.
327 /// use std::net::Ipv4Addr;
329 /// let addr = Ipv4Addr::LOCALHOST;
330 /// assert_eq!(addr, Ipv4Addr::new(127, 0, 0, 1));
332 #[stable(feature = "ip_constructors", since = "1.30.0")]
333 pub const LOCALHOST: Self = Ipv4Addr::new(127, 0, 0, 1);
335 /// An IPv4 address representing an unspecified address: 0.0.0.0
340 /// use std::net::Ipv4Addr;
342 /// let addr = Ipv4Addr::UNSPECIFIED;
343 /// assert_eq!(addr, Ipv4Addr::new(0, 0, 0, 0));
345 #[stable(feature = "ip_constructors", since = "1.30.0")]
346 pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0);
348 /// An IPv4 address representing the broadcast address: 255.255.255.255
353 /// use std::net::Ipv4Addr;
355 /// let addr = Ipv4Addr::BROADCAST;
356 /// assert_eq!(addr, Ipv4Addr::new(255, 255, 255, 255));
358 #[stable(feature = "ip_constructors", since = "1.30.0")]
359 pub const BROADCAST: Self = Ipv4Addr::new(255, 255, 255, 255);
361 /// Returns the four eight-bit integers that make up this address.
366 /// use std::net::Ipv4Addr;
368 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
369 /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
371 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
372 #[stable(feature = "rust1", since = "1.0.0")]
374 pub const fn octets(&self) -> [u8; 4] {
375 // This returns the order we want because s_addr is stored in big-endian.
376 self.inner.s_addr.to_ne_bytes()
379 /// Returns [`true`] for the special 'unspecified' address (0.0.0.0).
381 /// This property is defined in _UNIX Network Programming, Second Edition_,
382 /// W. Richard Stevens, p. 891; see also [ip7].
384 /// [ip7]: http://man7.org/linux/man-pages/man7/ip.7.html
389 /// use std::net::Ipv4Addr;
391 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
392 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
394 #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
395 #[stable(feature = "ip_shared", since = "1.12.0")]
397 pub const fn is_unspecified(&self) -> bool {
398 self.inner.s_addr == 0
401 /// Returns [`true`] if this is a loopback address (127.0.0.0/8).
403 /// This property is defined by [IETF RFC 1122].
405 /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
410 /// use std::net::Ipv4Addr;
412 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
413 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
415 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
416 #[stable(since = "1.7.0", feature = "ip_17")]
418 pub const fn is_loopback(&self) -> bool {
419 self.octets()[0] == 127
422 /// Returns [`true`] if this is a private address.
424 /// The private address ranges are defined in [IETF RFC 1918] and include:
430 /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
435 /// use std::net::Ipv4Addr;
437 /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
438 /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
439 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
440 /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
441 /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
442 /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
443 /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
445 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
446 #[stable(since = "1.7.0", feature = "ip_17")]
448 pub const fn is_private(&self) -> bool {
449 match self.octets() {
451 [172, b, ..] if b >= 16 && b <= 31 => true,
452 [192, 168, ..] => true,
457 /// Returns [`true`] if the address is link-local (169.254.0.0/16).
459 /// This property is defined by [IETF RFC 3927].
461 /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
466 /// use std::net::Ipv4Addr;
468 /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
469 /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
470 /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
472 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
473 #[stable(since = "1.7.0", feature = "ip_17")]
475 pub const fn is_link_local(&self) -> bool {
476 matches!(self.octets(), [169, 254, ..])
479 /// Returns [`true`] if the address appears to be globally routable.
480 /// See [iana-ipv4-special-registry][ipv4-sr].
482 /// The following return [`false`]:
484 /// - private addresses (see [`Ipv4Addr::is_private()`])
485 /// - the loopback address (see [`Ipv4Addr::is_loopback()`])
486 /// - the link-local address (see [`Ipv4Addr::is_link_local()`])
487 /// - the broadcast address (see [`Ipv4Addr::is_broadcast()`])
488 /// - addresses used for documentation (see [`Ipv4Addr::is_documentation()`])
489 /// - the unspecified address (see [`Ipv4Addr::is_unspecified()`]), and the whole
491 /// - addresses reserved for future protocols (see
492 /// [`Ipv4Addr::is_ietf_protocol_assignment()`], except
493 /// `192.0.0.9/32` and `192.0.0.10/32` which are globally routable
494 /// - addresses reserved for future use (see [`Ipv4Addr::is_reserved()`]
495 /// - addresses reserved for networking devices benchmarking (see
496 /// [`Ipv4Addr::is_benchmarking()`])
498 /// [ipv4-sr]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
505 /// use std::net::Ipv4Addr;
507 /// // private addresses are not global
508 /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
509 /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
510 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
512 /// // the 0.0.0.0/8 block is not global
513 /// assert_eq!(Ipv4Addr::new(0, 1, 2, 3).is_global(), false);
514 /// // in particular, the unspecified address is not global
515 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_global(), false);
517 /// // the loopback address is not global
518 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_global(), false);
520 /// // link local addresses are not global
521 /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
523 /// // the broadcast address is not global
524 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_global(), false);
526 /// // the address space designated for documentation is not global
527 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
528 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
529 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
531 /// // shared addresses are not global
532 /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
534 /// // addresses reserved for protocol assignment are not global
535 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_global(), false);
536 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_global(), false);
538 /// // addresses reserved for future use are not global
539 /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
541 /// // addresses reserved for network devices benchmarking are not global
542 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
544 /// // All the other addresses are global
545 /// assert_eq!(Ipv4Addr::new(1, 1, 1, 1).is_global(), true);
546 /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
548 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
550 pub const fn is_global(&self) -> bool {
551 // check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two
552 // globally routable addresses in the 192.0.0.0/24 range.
553 if u32::from_be_bytes(self.octets()) == 0xc0000009
554 || u32::from_be_bytes(self.octets()) == 0xc000000a
559 && !self.is_loopback()
560 && !self.is_link_local()
561 && !self.is_broadcast()
562 && !self.is_documentation()
564 && !self.is_ietf_protocol_assignment()
565 && !self.is_reserved()
566 && !self.is_benchmarking()
567 // Make sure the address is not in 0.0.0.0/8
568 && self.octets()[0] != 0
571 /// Returns [`true`] if this address is part of the Shared Address Space defined in
572 /// [IETF RFC 6598] (`100.64.0.0/10`).
574 /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
580 /// use std::net::Ipv4Addr;
582 /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
583 /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
584 /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
586 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
588 pub const fn is_shared(&self) -> bool {
589 self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
592 /// Returns [`true`] if this address is part of `192.0.0.0/24`, which is reserved to
593 /// IANA for IETF protocol assignments, as documented in [IETF RFC 6890].
595 /// Note that parts of this block are in use:
597 /// - `192.0.0.8/32` is the "IPv4 dummy address" (see [IETF RFC 7600])
598 /// - `192.0.0.9/32` is the "Port Control Protocol Anycast" (see [IETF RFC 7723])
599 /// - `192.0.0.10/32` is used for NAT traversal (see [IETF RFC 8155])
601 /// [IETF RFC 6890]: https://tools.ietf.org/html/rfc6890
602 /// [IETF RFC 7600]: https://tools.ietf.org/html/rfc7600
603 /// [IETF RFC 7723]: https://tools.ietf.org/html/rfc7723
604 /// [IETF RFC 8155]: https://tools.ietf.org/html/rfc8155
610 /// use std::net::Ipv4Addr;
612 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_ietf_protocol_assignment(), true);
613 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 8).is_ietf_protocol_assignment(), true);
614 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 9).is_ietf_protocol_assignment(), true);
615 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_ietf_protocol_assignment(), true);
616 /// assert_eq!(Ipv4Addr::new(192, 0, 1, 0).is_ietf_protocol_assignment(), false);
617 /// assert_eq!(Ipv4Addr::new(191, 255, 255, 255).is_ietf_protocol_assignment(), false);
619 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
621 pub const fn is_ietf_protocol_assignment(&self) -> bool {
622 self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0
625 /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
626 /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
627 /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
629 /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
630 /// [errata 423]: https://www.rfc-editor.org/errata/eid423
636 /// use std::net::Ipv4Addr;
638 /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
639 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
640 /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
641 /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
643 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
645 pub const fn is_benchmarking(&self) -> bool {
646 self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
649 /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
650 /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
651 /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
652 /// it is obviously not reserved for future use.
654 /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
658 /// As IANA assigns new addresses, this method will be
659 /// updated. This may result in non-reserved addresses being
660 /// treated as reserved in code that relies on an outdated version
667 /// use std::net::Ipv4Addr;
669 /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
670 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
672 /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
673 /// // The broadcast address is not considered as reserved for future use by this implementation
674 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
676 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
678 pub const fn is_reserved(&self) -> bool {
679 self.octets()[0] & 240 == 240 && !self.is_broadcast()
682 /// Returns [`true`] if this is a multicast address (224.0.0.0/4).
684 /// Multicast addresses have a most significant octet between 224 and 239,
685 /// and is defined by [IETF RFC 5771].
687 /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
692 /// use std::net::Ipv4Addr;
694 /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
695 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
696 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
698 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
699 #[stable(since = "1.7.0", feature = "ip_17")]
701 pub const fn is_multicast(&self) -> bool {
702 self.octets()[0] >= 224 && self.octets()[0] <= 239
705 /// Returns [`true`] if this is a broadcast address (255.255.255.255).
707 /// A broadcast address has all octets set to 255 as defined in [IETF RFC 919].
709 /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
714 /// use std::net::Ipv4Addr;
716 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
717 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
719 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
720 #[stable(since = "1.7.0", feature = "ip_17")]
722 pub const fn is_broadcast(&self) -> bool {
723 u32::from_be_bytes(self.octets()) == u32::from_be_bytes(Self::BROADCAST.octets())
726 /// Returns [`true`] if this address is in a range designated for documentation.
728 /// This is defined in [IETF RFC 5737]:
730 /// - 192.0.2.0/24 (TEST-NET-1)
731 /// - 198.51.100.0/24 (TEST-NET-2)
732 /// - 203.0.113.0/24 (TEST-NET-3)
734 /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
739 /// use std::net::Ipv4Addr;
741 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
742 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
743 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
744 /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
746 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
747 #[stable(since = "1.7.0", feature = "ip_17")]
749 pub const fn is_documentation(&self) -> bool {
750 match self.octets() {
751 [192, 0, 2, _] => true,
752 [198, 51, 100, _] => true,
753 [203, 0, 113, _] => true,
758 /// Converts this address to an IPv4-compatible [`IPv6` address].
760 /// a.b.c.d becomes ::a.b.c.d
762 /// This isn't typically the method you want; these addresses don't typically
763 /// function on modern systems. Use `to_ipv6_mapped` instead.
765 /// [`IPv6` address]: Ipv6Addr
770 /// use std::net::{Ipv4Addr, Ipv6Addr};
773 /// Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
774 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 767)
777 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
778 #[stable(feature = "rust1", since = "1.0.0")]
780 pub const fn to_ipv6_compatible(&self) -> Ipv6Addr {
781 let [a, b, c, d] = self.octets();
783 inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] },
787 /// Converts this address to an IPv4-mapped [`IPv6` address].
789 /// a.b.c.d becomes ::ffff:a.b.c.d
791 /// [`IPv6` address]: Ipv6Addr
796 /// use std::net::{Ipv4Addr, Ipv6Addr};
798 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
799 /// Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 49152, 767));
801 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
802 #[stable(feature = "rust1", since = "1.0.0")]
804 pub const fn to_ipv6_mapped(&self) -> Ipv6Addr {
805 let [a, b, c, d] = self.octets();
807 inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] },
812 #[stable(feature = "ip_addr", since = "1.7.0")]
813 impl fmt::Display for IpAddr {
814 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
816 IpAddr::V4(ip) => ip.fmt(fmt),
817 IpAddr::V6(ip) => ip.fmt(fmt),
822 #[stable(feature = "ip_addr", since = "1.7.0")]
823 impl fmt::Debug for IpAddr {
824 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
825 fmt::Display::fmt(self, fmt)
829 #[stable(feature = "ip_from_ip", since = "1.16.0")]
830 impl From<Ipv4Addr> for IpAddr {
831 /// Copies this address to a new `IpAddr::V4`.
836 /// use std::net::{IpAddr, Ipv4Addr};
838 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
841 /// IpAddr::V4(addr),
842 /// IpAddr::from(addr)
846 fn from(ipv4: Ipv4Addr) -> IpAddr {
851 #[stable(feature = "ip_from_ip", since = "1.16.0")]
852 impl From<Ipv6Addr> for IpAddr {
853 /// Copies this address to a new `IpAddr::V6`.
858 /// use std::net::{IpAddr, Ipv6Addr};
860 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
863 /// IpAddr::V6(addr),
864 /// IpAddr::from(addr)
868 fn from(ipv6: Ipv6Addr) -> IpAddr {
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl fmt::Display for Ipv4Addr {
875 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
876 let octets = self.octets();
877 // Fast Path: if there's no alignment stuff, write directly to the buffer
878 if fmt.precision().is_none() && fmt.width().is_none() {
879 write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
881 const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
882 let mut buf = [0u8; IPV4_BUF_LEN];
883 let mut buf_slice = &mut buf[..];
885 // Note: The call to write should never fail, hence the unwrap
886 write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
887 let len = IPV4_BUF_LEN - buf_slice.len();
889 // This unsafe is OK because we know what is being written to the buffer
890 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
896 #[stable(feature = "rust1", since = "1.0.0")]
897 impl fmt::Debug for Ipv4Addr {
898 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
899 fmt::Display::fmt(self, fmt)
903 #[stable(feature = "rust1", since = "1.0.0")]
904 impl Clone for Ipv4Addr {
906 fn clone(&self) -> Ipv4Addr {
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl PartialEq for Ipv4Addr {
914 fn eq(&self, other: &Ipv4Addr) -> bool {
915 self.inner.s_addr == other.inner.s_addr
919 #[stable(feature = "ip_cmp", since = "1.16.0")]
920 impl PartialEq<Ipv4Addr> for IpAddr {
922 fn eq(&self, other: &Ipv4Addr) -> bool {
924 IpAddr::V4(v4) => v4 == other,
925 IpAddr::V6(_) => false,
930 #[stable(feature = "ip_cmp", since = "1.16.0")]
931 impl PartialEq<IpAddr> for Ipv4Addr {
933 fn eq(&self, other: &IpAddr) -> bool {
935 IpAddr::V4(v4) => self == v4,
936 IpAddr::V6(_) => false,
941 #[stable(feature = "rust1", since = "1.0.0")]
942 impl Eq for Ipv4Addr {}
944 #[stable(feature = "rust1", since = "1.0.0")]
945 impl hash::Hash for Ipv4Addr {
947 fn hash<H: hash::Hasher>(&self, s: &mut H) {
949 // * hash in big endian order
950 // * in netbsd, `in_addr` has `repr(packed)`, we need to
951 // copy `s_addr` to avoid unsafe borrowing
952 { self.inner.s_addr }.hash(s)
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl PartialOrd for Ipv4Addr {
959 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
960 Some(self.cmp(other))
964 #[stable(feature = "ip_cmp", since = "1.16.0")]
965 impl PartialOrd<Ipv4Addr> for IpAddr {
967 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
969 IpAddr::V4(v4) => v4.partial_cmp(other),
970 IpAddr::V6(_) => Some(Ordering::Greater),
975 #[stable(feature = "ip_cmp", since = "1.16.0")]
976 impl PartialOrd<IpAddr> for Ipv4Addr {
978 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
980 IpAddr::V4(v4) => self.partial_cmp(v4),
981 IpAddr::V6(_) => Some(Ordering::Less),
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl Ord for Ipv4Addr {
989 fn cmp(&self, other: &Ipv4Addr) -> Ordering {
990 // Compare as native endian
991 u32::from_be(self.inner.s_addr).cmp(&u32::from_be(other.inner.s_addr))
995 impl IntoInner<c::in_addr> for Ipv4Addr {
996 fn into_inner(self) -> c::in_addr {
1001 #[stable(feature = "ip_u32", since = "1.1.0")]
1002 impl From<Ipv4Addr> for u32 {
1003 /// Converts an `Ipv4Addr` into a host byte order `u32`.
1008 /// use std::net::Ipv4Addr;
1010 /// let addr = Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe);
1011 /// assert_eq!(0xcafebabe, u32::from(addr));
1014 fn from(ip: Ipv4Addr) -> u32 {
1015 let ip = ip.octets();
1016 u32::from_be_bytes(ip)
1020 #[stable(feature = "ip_u32", since = "1.1.0")]
1021 impl From<u32> for Ipv4Addr {
1022 /// Converts a host byte order `u32` into an `Ipv4Addr`.
1027 /// use std::net::Ipv4Addr;
1029 /// let addr = Ipv4Addr::from(0xcafebabe);
1030 /// assert_eq!(Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe), addr);
1033 fn from(ip: u32) -> Ipv4Addr {
1034 Ipv4Addr::from(ip.to_be_bytes())
1038 #[stable(feature = "from_slice_v4", since = "1.9.0")]
1039 impl From<[u8; 4]> for Ipv4Addr {
1040 /// Creates an `Ipv4Addr` from a four element byte array.
1045 /// use std::net::Ipv4Addr;
1047 /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1048 /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1051 fn from(octets: [u8; 4]) -> Ipv4Addr {
1052 Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])
1056 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1057 impl From<[u8; 4]> for IpAddr {
1058 /// Creates an `IpAddr::V4` from a four element byte array.
1063 /// use std::net::{IpAddr, Ipv4Addr};
1065 /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1066 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1069 fn from(octets: [u8; 4]) -> IpAddr {
1070 IpAddr::V4(Ipv4Addr::from(octets))
1075 /// Creates a new IPv6 address from eight 16-bit segments.
1077 /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1082 /// use std::net::Ipv6Addr;
1084 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1086 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1087 #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1088 #[stable(feature = "rust1", since = "1.0.0")]
1090 pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1102 inner: c::in6_addr {
1103 // All elements in `addr16` are big endian.
1104 // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1105 // rustc_allow_const_fn_unstable: the transmute could be written as stable const
1106 // code, but that leads to worse code generation (#75085)
1107 s6_addr: unsafe { transmute::<_, [u8; 16]>(addr16) },
1112 /// An IPv6 address representing localhost: `::1`.
1117 /// use std::net::Ipv6Addr;
1119 /// let addr = Ipv6Addr::LOCALHOST;
1120 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1122 #[stable(feature = "ip_constructors", since = "1.30.0")]
1123 pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1125 /// An IPv6 address representing the unspecified address: `::`
1130 /// use std::net::Ipv6Addr;
1132 /// let addr = Ipv6Addr::UNSPECIFIED;
1133 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1135 #[stable(feature = "ip_constructors", since = "1.30.0")]
1136 pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1138 /// Returns the eight 16-bit segments that make up this address.
1143 /// use std::net::Ipv6Addr;
1145 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1146 /// [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1148 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1149 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1150 #[stable(feature = "rust1", since = "1.0.0")]
1152 pub const fn segments(&self) -> [u16; 8] {
1153 // All elements in `s6_addr` must be big endian.
1154 // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1155 // rustc_allow_const_fn_unstable: the transmute could be written as stable const code, but
1156 // that leads to worse code generation (#75085)
1157 let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.inner.s6_addr) };
1158 // We want native endian u16
1171 /// Returns [`true`] for the special 'unspecified' address (::).
1173 /// This property is defined in [IETF RFC 4291].
1175 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1180 /// use std::net::Ipv6Addr;
1182 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1183 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1185 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1186 #[stable(since = "1.7.0", feature = "ip_17")]
1188 pub const fn is_unspecified(&self) -> bool {
1189 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1192 /// Returns [`true`] if this is a loopback address (::1).
1194 /// This property is defined in [IETF RFC 4291].
1196 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1201 /// use std::net::Ipv6Addr;
1203 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1204 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1206 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1207 #[stable(since = "1.7.0", feature = "ip_17")]
1209 pub const fn is_loopback(&self) -> bool {
1210 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1213 /// Returns [`true`] if the address appears to be globally routable.
1215 /// The following return [`false`]:
1217 /// - the loopback address
1218 /// - link-local and unique local unicast addresses
1219 /// - interface-, link-, realm-, admin- and site-local multicast addresses
1226 /// use std::net::Ipv6Addr;
1228 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), true);
1229 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_global(), false);
1230 /// assert_eq!(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1).is_global(), true);
1232 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1234 pub const fn is_global(&self) -> bool {
1235 match self.multicast_scope() {
1236 Some(Ipv6MulticastScope::Global) => true,
1237 None => self.is_unicast_global(),
1242 /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1244 /// This property is defined in [IETF RFC 4193].
1246 /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1253 /// use std::net::Ipv6Addr;
1255 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1256 /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1258 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1260 pub const fn is_unique_local(&self) -> bool {
1261 (self.segments()[0] & 0xfe00) == 0xfc00
1264 /// Returns [`true`] if the address is a unicast link-local address (`fe80::/64`).
1266 /// A common misconception is to think that "unicast link-local addresses start with
1267 /// `fe80::`", but [IETF RFC 4291] actually defines a stricter format for these addresses:
1271 /// | bits | 54 bits | 64 bits |
1272 /// +----------+-------------------------+----------------------------+
1273 /// |1111111010| 0 | interface ID |
1274 /// +----------+-------------------------+----------------------------+
1277 /// This method validates the format defined in the RFC and won't recognize addresses
1278 /// like `fe80:0:0:1::` or `fe81::` as unicast link-local addresses.
1279 /// If you need a less strict validation, use [`Ipv6Addr::is_unicast_link_local()`] instead.
1286 /// use std::net::Ipv6Addr;
1288 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0);
1289 /// assert!(ip.is_unicast_link_local_strict());
1291 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff);
1292 /// assert!(ip.is_unicast_link_local_strict());
1294 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0);
1295 /// assert!(!ip.is_unicast_link_local_strict());
1296 /// assert!(ip.is_unicast_link_local());
1298 /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0);
1299 /// assert!(!ip.is_unicast_link_local_strict());
1300 /// assert!(ip.is_unicast_link_local());
1305 /// - [IETF RFC 4291 section 2.5.6]
1306 /// - [RFC 4291 errata 4406] (which has been rejected but provides useful
1308 /// - [`Ipv6Addr::is_unicast_link_local()`]
1310 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1311 /// [IETF RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1312 /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406
1313 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1315 pub const fn is_unicast_link_local_strict(&self) -> bool {
1316 matches!(self.segments(), [0xfe80, 0, 0, 0, ..])
1319 /// Returns [`true`] if the address is a unicast link-local address (`fe80::/10`).
1321 /// This method returns [`true`] for addresses in the range reserved by [RFC 4291 section 2.4],
1322 /// i.e. addresses with the following format:
1326 /// | bits | 54 bits | 64 bits |
1327 /// +----------+-------------------------+----------------------------+
1328 /// |1111111010| arbitratry value | interface ID |
1329 /// +----------+-------------------------+----------------------------+
1332 /// As a result, this method considers addresses such as `fe80:0:0:1::` or `fe81::` to be
1333 /// unicast link-local addresses, whereas [`Ipv6Addr::is_unicast_link_local_strict()`] does not.
1334 /// If you need a strict validation fully compliant with the RFC, use
1335 /// [`Ipv6Addr::is_unicast_link_local_strict()`] instead.
1342 /// use std::net::Ipv6Addr;
1344 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0);
1345 /// assert!(ip.is_unicast_link_local());
1347 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff);
1348 /// assert!(ip.is_unicast_link_local());
1350 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0);
1351 /// assert!(ip.is_unicast_link_local());
1352 /// assert!(!ip.is_unicast_link_local_strict());
1354 /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0);
1355 /// assert!(ip.is_unicast_link_local());
1356 /// assert!(!ip.is_unicast_link_local_strict());
1361 /// - [IETF RFC 4291 section 2.4]
1362 /// - [RFC 4291 errata 4406] (which has been rejected but provides useful
1365 /// [IETF RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1366 /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406
1367 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1369 pub const fn is_unicast_link_local(&self) -> bool {
1370 (self.segments()[0] & 0xffc0) == 0xfe80
1373 /// Returns [`true`] if this is a deprecated unicast site-local address (fec0::/10). The
1374 /// unicast site-local address format is defined in [RFC 4291 section 2.5.7] as:
1378 /// | bits | 54 bits | 64 bits |
1379 /// +----------+-------------------------+----------------------------+
1380 /// |1111111011| subnet ID | interface ID |
1381 /// +----------+-------------------------+----------------------------+
1384 /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1391 /// use std::net::Ipv6Addr;
1394 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_site_local(),
1397 /// assert_eq!(Ipv6Addr::new(0xfec2, 0, 0, 0, 0, 0, 0, 0).is_unicast_site_local(), true);
1402 /// As per [RFC 3879], the whole `FEC0::/10` prefix is
1403 /// deprecated. New software must not support site-local
1406 /// [RFC 3879]: https://tools.ietf.org/html/rfc3879
1407 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1409 pub const fn is_unicast_site_local(&self) -> bool {
1410 (self.segments()[0] & 0xffc0) == 0xfec0
1413 /// Returns [`true`] if this is an address reserved for documentation
1414 /// (`2001:db8::/32`).
1416 /// This property is defined in [IETF RFC 3849].
1418 /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1425 /// use std::net::Ipv6Addr;
1427 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1428 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1430 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1432 pub const fn is_documentation(&self) -> bool {
1433 (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1436 /// Returns [`true`] if the address is a globally routable unicast address.
1438 /// The following return false:
1440 /// - the loopback address
1441 /// - the link-local addresses
1442 /// - unique local addresses
1443 /// - the unspecified address
1444 /// - the address range reserved for documentation
1446 /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1449 /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1450 /// be supported in new implementations (i.e., new implementations must treat this prefix as
1451 /// Global Unicast).
1454 /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1461 /// use std::net::Ipv6Addr;
1463 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1464 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1466 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1468 pub const fn is_unicast_global(&self) -> bool {
1469 !self.is_multicast()
1470 && !self.is_loopback()
1471 && !self.is_unicast_link_local()
1472 && !self.is_unique_local()
1473 && !self.is_unspecified()
1474 && !self.is_documentation()
1477 /// Returns the address's multicast scope if the address is multicast.
1484 /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1487 /// Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1488 /// Some(Ipv6MulticastScope::Global)
1490 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1492 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1494 pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1495 if self.is_multicast() {
1496 match self.segments()[0] & 0x000f {
1497 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1498 2 => Some(Ipv6MulticastScope::LinkLocal),
1499 3 => Some(Ipv6MulticastScope::RealmLocal),
1500 4 => Some(Ipv6MulticastScope::AdminLocal),
1501 5 => Some(Ipv6MulticastScope::SiteLocal),
1502 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1503 14 => Some(Ipv6MulticastScope::Global),
1511 /// Returns [`true`] if this is a multicast address (ff00::/8).
1513 /// This property is defined by [IETF RFC 4291].
1515 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1520 /// use std::net::Ipv6Addr;
1522 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1523 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1525 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1526 #[stable(since = "1.7.0", feature = "ip_17")]
1528 pub const fn is_multicast(&self) -> bool {
1529 (self.segments()[0] & 0xff00) == 0xff00
1532 /// Converts this address to an [`IPv4` address] if it's an "IPv4-mapped IPv6 address"
1533 /// defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1535 /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1536 /// All addresses *not* starting with `::ffff` will return `None`.
1538 /// [`IPv4` address]: Ipv4Addr
1539 /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1546 /// use std::net::{Ipv4Addr, Ipv6Addr};
1548 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1549 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1550 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1551 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1553 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1555 pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1556 match self.octets() {
1557 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1558 Some(Ipv4Addr::new(a, b, c, d))
1564 /// Converts this address to an [`IPv4` address]. Returns [`None`] if this address is
1565 /// neither IPv4-compatible or IPv4-mapped.
1567 /// ::a.b.c.d and ::ffff:a.b.c.d become a.b.c.d
1569 /// [`IPv4` address]: Ipv4Addr
1574 /// use std::net::{Ipv4Addr, Ipv6Addr};
1576 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1577 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1578 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1579 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1580 /// Some(Ipv4Addr::new(0, 0, 0, 1)));
1582 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1583 #[stable(feature = "rust1", since = "1.0.0")]
1585 pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1586 if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1587 let [a, b] = ab.to_be_bytes();
1588 let [c, d] = cd.to_be_bytes();
1589 Some(Ipv4Addr::new(a, b, c, d))
1595 /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1598 /// use std::net::Ipv6Addr;
1600 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1601 /// [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1603 #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1604 #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1606 pub const fn octets(&self) -> [u8; 16] {
1611 /// Write an Ipv6Addr, conforming to the canonical style described by
1612 /// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 impl fmt::Display for Ipv6Addr {
1615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1616 // If there are no alignment requirements, write out the IP address to
1617 // f. Otherwise, write it to a local buffer, then use f.pad.
1618 if f.precision().is_none() && f.width().is_none() {
1619 let segments = self.segments();
1621 // Special case for :: and ::1; otherwise they get written with the
1623 if self.is_unspecified() {
1625 } else if self.is_loopback() {
1627 } else if let Some(ipv4) = self.to_ipv4() {
1629 // IPv4 Compatible address
1630 0 => write!(f, "::{}", ipv4),
1631 // IPv4 Mapped address
1632 0xffff => write!(f, "::ffff:{}", ipv4),
1633 _ => unreachable!(),
1636 #[derive(Copy, Clone, Default)]
1642 // Find the inner 0 span
1644 let mut longest = Span::default();
1645 let mut current = Span::default();
1647 for (i, &segment) in segments.iter().enumerate() {
1649 if current.len == 0 {
1655 if current.len > longest.len {
1659 current = Span::default();
1666 /// Write a colon-separated part of the address
1668 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1669 if let Some((first, tail)) = chunk.split_first() {
1670 write!(f, "{:x}", first)?;
1671 for segment in tail {
1673 write!(f, "{:x}", segment)?;
1680 fmt_subslice(f, &segments[..zeroes.start])?;
1682 fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1684 fmt_subslice(f, &segments)
1688 // Slow path: write the address to a local buffer, the use f.pad.
1689 // Defined recursively by using the fast path to write to the
1692 // This is the largest possible size of an IPv6 address
1693 const IPV6_BUF_LEN: usize = (4 * 8) + 7;
1694 let mut buf = [0u8; IPV6_BUF_LEN];
1695 let mut buf_slice = &mut buf[..];
1697 // Note: This call to write should never fail, so unwrap is okay.
1698 write!(buf_slice, "{}", self).unwrap();
1699 let len = IPV6_BUF_LEN - buf_slice.len();
1701 // This is safe because we know exactly what can be in this buffer
1702 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl fmt::Debug for Ipv6Addr {
1710 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1711 fmt::Display::fmt(self, fmt)
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl Clone for Ipv6Addr {
1718 fn clone(&self) -> Ipv6Addr {
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 impl PartialEq for Ipv6Addr {
1726 fn eq(&self, other: &Ipv6Addr) -> bool {
1727 self.inner.s6_addr == other.inner.s6_addr
1731 #[stable(feature = "ip_cmp", since = "1.16.0")]
1732 impl PartialEq<IpAddr> for Ipv6Addr {
1734 fn eq(&self, other: &IpAddr) -> bool {
1736 IpAddr::V4(_) => false,
1737 IpAddr::V6(v6) => self == v6,
1742 #[stable(feature = "ip_cmp", since = "1.16.0")]
1743 impl PartialEq<Ipv6Addr> for IpAddr {
1745 fn eq(&self, other: &Ipv6Addr) -> bool {
1747 IpAddr::V4(_) => false,
1748 IpAddr::V6(v6) => v6 == other,
1753 #[stable(feature = "rust1", since = "1.0.0")]
1754 impl Eq for Ipv6Addr {}
1756 #[stable(feature = "rust1", since = "1.0.0")]
1757 impl hash::Hash for Ipv6Addr {
1759 fn hash<H: hash::Hasher>(&self, s: &mut H) {
1760 self.inner.s6_addr.hash(s)
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 impl PartialOrd for Ipv6Addr {
1767 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1768 Some(self.cmp(other))
1772 #[stable(feature = "ip_cmp", since = "1.16.0")]
1773 impl PartialOrd<Ipv6Addr> for IpAddr {
1775 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1777 IpAddr::V4(_) => Some(Ordering::Less),
1778 IpAddr::V6(v6) => v6.partial_cmp(other),
1783 #[stable(feature = "ip_cmp", since = "1.16.0")]
1784 impl PartialOrd<IpAddr> for Ipv6Addr {
1786 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1788 IpAddr::V4(_) => Some(Ordering::Greater),
1789 IpAddr::V6(v6) => self.partial_cmp(v6),
1794 #[stable(feature = "rust1", since = "1.0.0")]
1795 impl Ord for Ipv6Addr {
1797 fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1798 self.segments().cmp(&other.segments())
1802 impl AsInner<c::in6_addr> for Ipv6Addr {
1803 fn as_inner(&self) -> &c::in6_addr {
1807 impl FromInner<c::in6_addr> for Ipv6Addr {
1808 fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1809 Ipv6Addr { inner: addr }
1813 #[stable(feature = "i128", since = "1.26.0")]
1814 impl From<Ipv6Addr> for u128 {
1815 /// Convert an `Ipv6Addr` into a host byte order `u128`.
1820 /// use std::net::Ipv6Addr;
1822 /// let addr = Ipv6Addr::new(
1823 /// 0x1020, 0x3040, 0x5060, 0x7080,
1824 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1826 /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1829 fn from(ip: Ipv6Addr) -> u128 {
1830 let ip = ip.octets();
1831 u128::from_be_bytes(ip)
1834 #[stable(feature = "i128", since = "1.26.0")]
1835 impl From<u128> for Ipv6Addr {
1836 /// Convert a host byte order `u128` into an `Ipv6Addr`.
1841 /// use std::net::Ipv6Addr;
1843 /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1846 /// 0x1020, 0x3040, 0x5060, 0x7080,
1847 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1852 fn from(ip: u128) -> Ipv6Addr {
1853 Ipv6Addr::from(ip.to_be_bytes())
1857 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1858 impl From<[u8; 16]> for Ipv6Addr {
1859 /// Creates an `Ipv6Addr` from a sixteen element byte array.
1864 /// use std::net::Ipv6Addr;
1866 /// let addr = Ipv6Addr::from([
1867 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1868 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1881 fn from(octets: [u8; 16]) -> Ipv6Addr {
1882 let inner = c::in6_addr { s6_addr: octets };
1883 Ipv6Addr::from_inner(inner)
1887 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
1888 impl From<[u16; 8]> for Ipv6Addr {
1889 /// Creates an `Ipv6Addr` from an eight element 16-bit array.
1894 /// use std::net::Ipv6Addr;
1896 /// let addr = Ipv6Addr::from([
1897 /// 525u16, 524u16, 523u16, 522u16,
1898 /// 521u16, 520u16, 519u16, 518u16,
1911 fn from(segments: [u16; 8]) -> Ipv6Addr {
1912 let [a, b, c, d, e, f, g, h] = segments;
1913 Ipv6Addr::new(a, b, c, d, e, f, g, h)
1917 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1918 impl From<[u8; 16]> for IpAddr {
1919 /// Creates an `IpAddr::V6` from a sixteen element byte array.
1924 /// use std::net::{IpAddr, Ipv6Addr};
1926 /// let addr = IpAddr::from([
1927 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1928 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1931 /// IpAddr::V6(Ipv6Addr::new(
1941 fn from(octets: [u8; 16]) -> IpAddr {
1942 IpAddr::V6(Ipv6Addr::from(octets))
1946 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1947 impl From<[u16; 8]> for IpAddr {
1948 /// Creates an `IpAddr::V6` from an eight element 16-bit array.
1953 /// use std::net::{IpAddr, Ipv6Addr};
1955 /// let addr = IpAddr::from([
1956 /// 525u16, 524u16, 523u16, 522u16,
1957 /// 521u16, 520u16, 519u16, 518u16,
1960 /// IpAddr::V6(Ipv6Addr::new(
1970 fn from(segments: [u16; 8]) -> IpAddr {
1971 IpAddr::V6(Ipv6Addr::from(segments))