1 // Tests for this module
2 #[cfg(all(test, not(target_os = "emscripten")))]
5 use crate::cmp::Ordering;
6 use crate::fmt::{self, Write as FmtWrite};
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};
13 /// An IP address, either IPv4 or IPv6.
15 /// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
16 /// respective documentation for more details.
18 /// The size of an `IpAddr` instance may vary depending on the target operating
24 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
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));
29 /// assert_eq!("127.0.0.1".parse(), Ok(localhost_v4));
30 /// assert_eq!("::1".parse(), Ok(localhost_v6));
32 /// assert_eq!(localhost_v4.is_ipv6(), false);
33 /// assert_eq!(localhost_v4.is_ipv4(), true);
35 #[stable(feature = "ip_addr", since = "1.7.0")]
36 #[derive(Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
39 #[stable(feature = "ip_addr", since = "1.7.0")]
40 V4(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv4Addr),
42 #[stable(feature = "ip_addr", since = "1.7.0")]
43 V6(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv6Addr),
48 /// IPv4 addresses are defined as 32-bit integers in [IETF RFC 791].
49 /// They are usually represented as four octets.
51 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
53 /// The size of an `Ipv4Addr` struct may vary depending on the target operating
56 /// [IETF RFC 791]: https://tools.ietf.org/html/rfc791
58 /// # Textual representation
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 and hexadecimal numbers are not allowed per [IETF RFC 6943].
64 /// [IETF RFC 6943]: https://tools.ietf.org/html/rfc6943#section-3.1.1
65 /// [`FromStr`]: crate::str::FromStr
70 /// use std::net::Ipv4Addr;
72 /// let localhost = Ipv4Addr::new(127, 0, 0, 1);
73 /// assert_eq!("127.0.0.1".parse(), Ok(localhost));
74 /// assert_eq!(localhost.is_loopback(), true);
77 #[stable(feature = "rust1", since = "1.0.0")]
84 /// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
85 /// They are usually represented as eight 16-bit segments.
87 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
89 /// The size of an `Ipv6Addr` struct may vary depending on the target operating
92 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
94 /// # Textual representation
96 /// `Ipv6Addr` provides a [`FromStr`] implementation. There are many ways to represent
97 /// an IPv6 address in text, but in general, each segments is written in hexadecimal
98 /// notation, and segments are separated by `:`. For more information, see
101 /// [`FromStr`]: crate::str::FromStr
102 /// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952
107 /// use std::net::Ipv6Addr;
109 /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
110 /// assert_eq!("::1".parse(), Ok(localhost));
111 /// assert_eq!(localhost.is_loopback(), true);
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub struct Ipv6Addr {
119 /// Scope of an [IPv6 multicast address] as defined in [IETF RFC 7346 section 2].
121 /// # Stability Guarantees
123 /// Not all possible values for a multicast scope have been assigned.
124 /// Future RFCs may introduce new scopes, which will be added as variants to this enum;
125 /// because of this the enum is marked as `#[non_exhaustive]`.
131 /// use std::net::Ipv6Addr;
132 /// use std::net::Ipv6MulticastScope::*;
134 /// // An IPv6 multicast address with global scope (`ff0e::`).
135 /// let address = Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0);
137 /// // Will print "Global scope".
138 /// match address.multicast_scope() {
139 /// Some(InterfaceLocal) => println!("Interface-Local scope"),
140 /// Some(LinkLocal) => println!("Link-Local scope"),
141 /// Some(RealmLocal) => println!("Realm-Local scope"),
142 /// Some(AdminLocal) => println!("Admin-Local scope"),
143 /// Some(SiteLocal) => println!("Site-Local scope"),
144 /// Some(OrganizationLocal) => println!("Organization-Local scope"),
145 /// Some(Global) => println!("Global scope"),
146 /// Some(_) => println!("Unknown scope"),
147 /// None => println!("Not a multicast address!")
152 /// [IPv6 multicast address]: Ipv6Addr
153 /// [IETF RFC 7346 section 2]: https://tools.ietf.org/html/rfc7346#section-2
154 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
155 #[unstable(feature = "ip", issue = "27709")]
157 pub enum Ipv6MulticastScope {
158 /// Interface-Local scope.
160 /// Link-Local scope.
162 /// Realm-Local scope.
164 /// Admin-Local scope.
166 /// Site-Local scope.
168 /// Organization-Local scope.
175 /// Returns [`true`] for the special 'unspecified' address.
177 /// See the documentation for [`Ipv4Addr::is_unspecified()`] and
178 /// [`Ipv6Addr::is_unspecified()`] for more details.
183 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
185 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
186 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
188 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
189 #[stable(feature = "ip_shared", since = "1.12.0")]
191 pub const fn is_unspecified(&self) -> bool {
193 IpAddr::V4(ip) => ip.is_unspecified(),
194 IpAddr::V6(ip) => ip.is_unspecified(),
198 /// Returns [`true`] if this is a loopback address.
200 /// See the documentation for [`Ipv4Addr::is_loopback()`] and
201 /// [`Ipv6Addr::is_loopback()`] for more details.
206 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
208 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
209 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
211 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
212 #[stable(feature = "ip_shared", since = "1.12.0")]
214 pub const fn is_loopback(&self) -> bool {
216 IpAddr::V4(ip) => ip.is_loopback(),
217 IpAddr::V6(ip) => ip.is_loopback(),
221 /// Returns [`true`] if the address appears to be globally routable.
223 /// See the documentation for [`Ipv4Addr::is_global()`] and
224 /// [`Ipv6Addr::is_global()`] for more details.
231 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
233 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true);
234 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true);
236 #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
237 #[unstable(feature = "ip", issue = "27709")]
239 pub const fn is_global(&self) -> bool {
241 IpAddr::V4(ip) => ip.is_global(),
242 IpAddr::V6(ip) => ip.is_global(),
246 /// Returns [`true`] if this is a multicast address.
248 /// See the documentation for [`Ipv4Addr::is_multicast()`] and
249 /// [`Ipv6Addr::is_multicast()`] for more details.
254 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
256 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
257 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
259 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
260 #[stable(feature = "ip_shared", since = "1.12.0")]
262 pub const fn is_multicast(&self) -> bool {
264 IpAddr::V4(ip) => ip.is_multicast(),
265 IpAddr::V6(ip) => ip.is_multicast(),
269 /// Returns [`true`] if this address is in a range designated for documentation.
271 /// See the documentation for [`Ipv4Addr::is_documentation()`] and
272 /// [`Ipv6Addr::is_documentation()`] for more details.
279 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
281 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
283 /// IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(),
287 #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
288 #[unstable(feature = "ip", issue = "27709")]
290 pub const fn is_documentation(&self) -> bool {
292 IpAddr::V4(ip) => ip.is_documentation(),
293 IpAddr::V6(ip) => ip.is_documentation(),
297 /// Returns [`true`] if this address is an [`IPv4` address], and [`false`]
300 /// [`IPv4` address]: IpAddr::V4
305 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
307 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
308 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false);
310 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
311 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
313 pub const fn is_ipv4(&self) -> bool {
314 matches!(self, IpAddr::V4(_))
317 /// Returns [`true`] if this address is an [`IPv6` address], and [`false`]
320 /// [`IPv6` address]: IpAddr::V6
325 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
327 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
328 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true);
330 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
331 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
333 pub const fn is_ipv6(&self) -> bool {
334 matches!(self, IpAddr::V6(_))
339 /// Creates a new IPv4 address from four eight-bit octets.
341 /// The result will represent the IP address `a`.`b`.`c`.`d`.
346 /// use std::net::Ipv4Addr;
348 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
350 #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
351 #[stable(feature = "rust1", since = "1.0.0")]
353 pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
354 // `s_addr` is stored as BE on all machine and the array is in BE order.
355 // So the native endian conversion method is used so that it's never swapped.
356 Ipv4Addr { inner: c::in_addr { s_addr: u32::from_ne_bytes([a, b, c, d]) } }
359 /// An IPv4 address with the address pointing to localhost: `127.0.0.1`
364 /// use std::net::Ipv4Addr;
366 /// let addr = Ipv4Addr::LOCALHOST;
367 /// assert_eq!(addr, Ipv4Addr::new(127, 0, 0, 1));
369 #[stable(feature = "ip_constructors", since = "1.30.0")]
370 pub const LOCALHOST: Self = Ipv4Addr::new(127, 0, 0, 1);
372 /// An IPv4 address representing an unspecified address: `0.0.0.0`
374 /// This corresponds to the constant `INADDR_ANY` in other languages.
379 /// use std::net::Ipv4Addr;
381 /// let addr = Ipv4Addr::UNSPECIFIED;
382 /// assert_eq!(addr, Ipv4Addr::new(0, 0, 0, 0));
384 #[doc(alias = "INADDR_ANY")]
385 #[stable(feature = "ip_constructors", since = "1.30.0")]
386 pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0);
388 /// An IPv4 address representing the broadcast address: `255.255.255.255`
393 /// use std::net::Ipv4Addr;
395 /// let addr = Ipv4Addr::BROADCAST;
396 /// assert_eq!(addr, Ipv4Addr::new(255, 255, 255, 255));
398 #[stable(feature = "ip_constructors", since = "1.30.0")]
399 pub const BROADCAST: Self = Ipv4Addr::new(255, 255, 255, 255);
401 /// Returns the four eight-bit integers that make up this address.
406 /// use std::net::Ipv4Addr;
408 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
409 /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
411 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
412 #[stable(feature = "rust1", since = "1.0.0")]
414 pub const fn octets(&self) -> [u8; 4] {
415 // This returns the order we want because s_addr is stored in big-endian.
416 self.inner.s_addr.to_ne_bytes()
419 /// Returns [`true`] for the special 'unspecified' address (`0.0.0.0`).
421 /// This property is defined in _UNIX Network Programming, Second Edition_,
422 /// W. Richard Stevens, p. 891; see also [ip7].
424 /// [ip7]: https://man7.org/linux/man-pages/man7/ip.7.html
429 /// use std::net::Ipv4Addr;
431 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
432 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
434 #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
435 #[stable(feature = "ip_shared", since = "1.12.0")]
437 pub const fn is_unspecified(&self) -> bool {
438 self.inner.s_addr == 0
441 /// Returns [`true`] if this is a loopback address (`127.0.0.0/8`).
443 /// This property is defined by [IETF RFC 1122].
445 /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
450 /// use std::net::Ipv4Addr;
452 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
453 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
455 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
456 #[stable(since = "1.7.0", feature = "ip_17")]
458 pub const fn is_loopback(&self) -> bool {
459 self.octets()[0] == 127
462 /// Returns [`true`] if this is a private address.
464 /// The private address ranges are defined in [IETF RFC 1918] and include:
467 /// - `172.16.0.0/12`
468 /// - `192.168.0.0/16`
470 /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
475 /// use std::net::Ipv4Addr;
477 /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
478 /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
479 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
480 /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
481 /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
482 /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
483 /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
485 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
486 #[stable(since = "1.7.0", feature = "ip_17")]
488 pub const fn is_private(&self) -> bool {
489 match self.octets() {
491 [172, b, ..] if b >= 16 && b <= 31 => true,
492 [192, 168, ..] => true,
497 /// Returns [`true`] if the address is link-local (`169.254.0.0/16`).
499 /// This property is defined by [IETF RFC 3927].
501 /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
506 /// use std::net::Ipv4Addr;
508 /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
509 /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
510 /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
512 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
513 #[stable(since = "1.7.0", feature = "ip_17")]
515 pub const fn is_link_local(&self) -> bool {
516 matches!(self.octets(), [169, 254, ..])
519 /// Returns [`true`] if the address appears to be globally routable.
520 /// See [iana-ipv4-special-registry][ipv4-sr].
522 /// The following return [`false`]:
524 /// - private addresses (see [`Ipv4Addr::is_private()`])
525 /// - the loopback address (see [`Ipv4Addr::is_loopback()`])
526 /// - the link-local address (see [`Ipv4Addr::is_link_local()`])
527 /// - the broadcast address (see [`Ipv4Addr::is_broadcast()`])
528 /// - addresses used for documentation (see [`Ipv4Addr::is_documentation()`])
529 /// - the unspecified address (see [`Ipv4Addr::is_unspecified()`]), and the whole
530 /// `0.0.0.0/8` block
531 /// - addresses reserved for future protocols (see
532 /// [`Ipv4Addr::is_ietf_protocol_assignment()`], except
533 /// `192.0.0.9/32` and `192.0.0.10/32` which are globally routable
534 /// - addresses reserved for future use (see [`Ipv4Addr::is_reserved()`]
535 /// - addresses reserved for networking devices benchmarking (see
536 /// [`Ipv4Addr::is_benchmarking()`])
538 /// [ipv4-sr]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
545 /// use std::net::Ipv4Addr;
547 /// // private addresses are not global
548 /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
549 /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
550 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
552 /// // the 0.0.0.0/8 block is not global
553 /// assert_eq!(Ipv4Addr::new(0, 1, 2, 3).is_global(), false);
554 /// // in particular, the unspecified address is not global
555 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_global(), false);
557 /// // the loopback address is not global
558 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_global(), false);
560 /// // link local addresses are not global
561 /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
563 /// // the broadcast address is not global
564 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_global(), false);
566 /// // the address space designated for documentation is not global
567 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
568 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
569 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
571 /// // shared addresses are not global
572 /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
574 /// // addresses reserved for protocol assignment are not global
575 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_global(), false);
576 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_global(), false);
578 /// // addresses reserved for future use are not global
579 /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
581 /// // addresses reserved for network devices benchmarking are not global
582 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
584 /// // All the other addresses are global
585 /// assert_eq!(Ipv4Addr::new(1, 1, 1, 1).is_global(), true);
586 /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
588 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
589 #[unstable(feature = "ip", issue = "27709")]
591 pub const fn is_global(&self) -> bool {
592 // check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two
593 // globally routable addresses in the 192.0.0.0/24 range.
594 if u32::from_be_bytes(self.octets()) == 0xc0000009
595 || u32::from_be_bytes(self.octets()) == 0xc000000a
600 && !self.is_loopback()
601 && !self.is_link_local()
602 && !self.is_broadcast()
603 && !self.is_documentation()
605 && !self.is_ietf_protocol_assignment()
606 && !self.is_reserved()
607 && !self.is_benchmarking()
608 // Make sure the address is not in 0.0.0.0/8
609 && self.octets()[0] != 0
612 /// Returns [`true`] if this address is part of the Shared Address Space defined in
613 /// [IETF RFC 6598] (`100.64.0.0/10`).
615 /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
621 /// use std::net::Ipv4Addr;
623 /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
624 /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
625 /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
627 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
628 #[unstable(feature = "ip", issue = "27709")]
630 pub const fn is_shared(&self) -> bool {
631 self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
634 /// Returns [`true`] if this address is part of `192.0.0.0/24`, which is reserved to
635 /// IANA for IETF protocol assignments, as documented in [IETF RFC 6890].
637 /// Note that parts of this block are in use:
639 /// - `192.0.0.8/32` is the "IPv4 dummy address" (see [IETF RFC 7600])
640 /// - `192.0.0.9/32` is the "Port Control Protocol Anycast" (see [IETF RFC 7723])
641 /// - `192.0.0.10/32` is used for NAT traversal (see [IETF RFC 8155])
643 /// [IETF RFC 6890]: https://tools.ietf.org/html/rfc6890
644 /// [IETF RFC 7600]: https://tools.ietf.org/html/rfc7600
645 /// [IETF RFC 7723]: https://tools.ietf.org/html/rfc7723
646 /// [IETF RFC 8155]: https://tools.ietf.org/html/rfc8155
652 /// use std::net::Ipv4Addr;
654 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_ietf_protocol_assignment(), true);
655 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 8).is_ietf_protocol_assignment(), true);
656 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 9).is_ietf_protocol_assignment(), true);
657 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_ietf_protocol_assignment(), true);
658 /// assert_eq!(Ipv4Addr::new(192, 0, 1, 0).is_ietf_protocol_assignment(), false);
659 /// assert_eq!(Ipv4Addr::new(191, 255, 255, 255).is_ietf_protocol_assignment(), false);
661 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
662 #[unstable(feature = "ip", issue = "27709")]
664 pub const fn is_ietf_protocol_assignment(&self) -> bool {
665 self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0
668 /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
669 /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
670 /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
672 /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
673 /// [errata 423]: https://www.rfc-editor.org/errata/eid423
679 /// use std::net::Ipv4Addr;
681 /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
682 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
683 /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
684 /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
686 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
687 #[unstable(feature = "ip", issue = "27709")]
689 pub const fn is_benchmarking(&self) -> bool {
690 self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
693 /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
694 /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
695 /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
696 /// it is obviously not reserved for future use.
698 /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
702 /// As IANA assigns new addresses, this method will be
703 /// updated. This may result in non-reserved addresses being
704 /// treated as reserved in code that relies on an outdated version
711 /// use std::net::Ipv4Addr;
713 /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
714 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
716 /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
717 /// // The broadcast address is not considered as reserved for future use by this implementation
718 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
720 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
721 #[unstable(feature = "ip", issue = "27709")]
723 pub const fn is_reserved(&self) -> bool {
724 self.octets()[0] & 240 == 240 && !self.is_broadcast()
727 /// Returns [`true`] if this is a multicast address (`224.0.0.0/4`).
729 /// Multicast addresses have a most significant octet between `224` and `239`,
730 /// and is defined by [IETF RFC 5771].
732 /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
737 /// use std::net::Ipv4Addr;
739 /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
740 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
741 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
743 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
744 #[stable(since = "1.7.0", feature = "ip_17")]
746 pub const fn is_multicast(&self) -> bool {
747 self.octets()[0] >= 224 && self.octets()[0] <= 239
750 /// Returns [`true`] if this is a broadcast address (`255.255.255.255`).
752 /// A broadcast address has all octets set to `255` as defined in [IETF RFC 919].
754 /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
759 /// use std::net::Ipv4Addr;
761 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
762 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
764 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
765 #[stable(since = "1.7.0", feature = "ip_17")]
767 pub const fn is_broadcast(&self) -> bool {
768 u32::from_be_bytes(self.octets()) == u32::from_be_bytes(Self::BROADCAST.octets())
771 /// Returns [`true`] if this address is in a range designated for documentation.
773 /// This is defined in [IETF RFC 5737]:
775 /// - `192.0.2.0/24` (TEST-NET-1)
776 /// - `198.51.100.0/24` (TEST-NET-2)
777 /// - `203.0.113.0/24` (TEST-NET-3)
779 /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
784 /// use std::net::Ipv4Addr;
786 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
787 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
788 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
789 /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
791 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
792 #[stable(since = "1.7.0", feature = "ip_17")]
794 pub const fn is_documentation(&self) -> bool {
795 match self.octets() {
796 [192, 0, 2, _] => true,
797 [198, 51, 100, _] => true,
798 [203, 0, 113, _] => true,
803 /// Converts this address to an IPv4-compatible [`IPv6` address].
805 /// `a.b.c.d` becomes `::a.b.c.d`
807 /// This isn't typically the method you want; these addresses don't typically
808 /// function on modern systems. Use `to_ipv6_mapped` instead.
810 /// [`IPv6` address]: Ipv6Addr
815 /// use std::net::{Ipv4Addr, Ipv6Addr};
818 /// Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
819 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x2ff)
822 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
823 #[stable(feature = "rust1", since = "1.0.0")]
825 pub const fn to_ipv6_compatible(&self) -> Ipv6Addr {
826 let [a, b, c, d] = self.octets();
828 inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] },
832 /// Converts this address to an IPv4-mapped [`IPv6` address].
834 /// `a.b.c.d` becomes `::ffff:a.b.c.d`
836 /// [`IPv6` address]: Ipv6Addr
841 /// use std::net::{Ipv4Addr, Ipv6Addr};
843 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
844 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff));
846 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
847 #[stable(feature = "rust1", since = "1.0.0")]
849 pub const fn to_ipv6_mapped(&self) -> Ipv6Addr {
850 let [a, b, c, d] = self.octets();
852 inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] },
857 #[stable(feature = "ip_addr", since = "1.7.0")]
858 impl fmt::Display for IpAddr {
859 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
861 IpAddr::V4(ip) => ip.fmt(fmt),
862 IpAddr::V6(ip) => ip.fmt(fmt),
867 #[stable(feature = "ip_addr", since = "1.7.0")]
868 impl fmt::Debug for IpAddr {
869 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
870 fmt::Display::fmt(self, fmt)
874 #[stable(feature = "ip_from_ip", since = "1.16.0")]
875 impl From<Ipv4Addr> for IpAddr {
876 /// Copies this address to a new `IpAddr::V4`.
881 /// use std::net::{IpAddr, Ipv4Addr};
883 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
886 /// IpAddr::V4(addr),
887 /// IpAddr::from(addr)
891 fn from(ipv4: Ipv4Addr) -> IpAddr {
896 #[stable(feature = "ip_from_ip", since = "1.16.0")]
897 impl From<Ipv6Addr> for IpAddr {
898 /// Copies this address to a new `IpAddr::V6`.
903 /// use std::net::{IpAddr, Ipv6Addr};
905 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
908 /// IpAddr::V6(addr),
909 /// IpAddr::from(addr)
913 fn from(ipv6: Ipv6Addr) -> IpAddr {
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl fmt::Display for Ipv4Addr {
920 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
921 let octets = self.octets();
922 // Fast Path: if there's no alignment stuff, write directly to the buffer
923 if fmt.precision().is_none() && fmt.width().is_none() {
924 write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
926 const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
927 let mut buf = [0u8; IPV4_BUF_LEN];
928 let mut buf_slice = &mut buf[..];
930 // Note: The call to write should never fail, hence the unwrap
931 write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
932 let len = IPV4_BUF_LEN - buf_slice.len();
934 // This unsafe is OK because we know what is being written to the buffer
935 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
941 #[stable(feature = "rust1", since = "1.0.0")]
942 impl fmt::Debug for Ipv4Addr {
943 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
944 fmt::Display::fmt(self, fmt)
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl Clone for Ipv4Addr {
951 fn clone(&self) -> Ipv4Addr {
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl PartialEq for Ipv4Addr {
959 fn eq(&self, other: &Ipv4Addr) -> bool {
960 self.inner.s_addr == other.inner.s_addr
964 #[stable(feature = "ip_cmp", since = "1.16.0")]
965 impl PartialEq<Ipv4Addr> for IpAddr {
967 fn eq(&self, other: &Ipv4Addr) -> bool {
969 IpAddr::V4(v4) => v4 == other,
970 IpAddr::V6(_) => false,
975 #[stable(feature = "ip_cmp", since = "1.16.0")]
976 impl PartialEq<IpAddr> for Ipv4Addr {
978 fn eq(&self, other: &IpAddr) -> bool {
980 IpAddr::V4(v4) => self == v4,
981 IpAddr::V6(_) => false,
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl Eq for Ipv4Addr {}
989 #[stable(feature = "rust1", since = "1.0.0")]
990 impl hash::Hash for Ipv4Addr {
992 fn hash<H: hash::Hasher>(&self, s: &mut H) {
994 // * hash in big endian order
995 // * in netbsd, `in_addr` has `repr(packed)`, we need to
996 // copy `s_addr` to avoid unsafe borrowing
997 { self.inner.s_addr }.hash(s)
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl PartialOrd for Ipv4Addr {
1004 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1005 Some(self.cmp(other))
1009 #[stable(feature = "ip_cmp", since = "1.16.0")]
1010 impl PartialOrd<Ipv4Addr> for IpAddr {
1012 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1014 IpAddr::V4(v4) => v4.partial_cmp(other),
1015 IpAddr::V6(_) => Some(Ordering::Greater),
1020 #[stable(feature = "ip_cmp", since = "1.16.0")]
1021 impl PartialOrd<IpAddr> for Ipv4Addr {
1023 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1025 IpAddr::V4(v4) => self.partial_cmp(v4),
1026 IpAddr::V6(_) => Some(Ordering::Less),
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 impl Ord for Ipv4Addr {
1034 fn cmp(&self, other: &Ipv4Addr) -> Ordering {
1035 // Compare as native endian
1036 u32::from_be(self.inner.s_addr).cmp(&u32::from_be(other.inner.s_addr))
1040 impl IntoInner<c::in_addr> for Ipv4Addr {
1042 fn into_inner(self) -> c::in_addr {
1047 #[stable(feature = "ip_u32", since = "1.1.0")]
1048 impl From<Ipv4Addr> for u32 {
1049 /// Converts an `Ipv4Addr` into a host byte order `u32`.
1054 /// use std::net::Ipv4Addr;
1056 /// let addr = Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe);
1057 /// assert_eq!(0xcafebabe, u32::from(addr));
1060 fn from(ip: Ipv4Addr) -> u32 {
1061 let ip = ip.octets();
1062 u32::from_be_bytes(ip)
1066 #[stable(feature = "ip_u32", since = "1.1.0")]
1067 impl From<u32> for Ipv4Addr {
1068 /// Converts a host byte order `u32` into an `Ipv4Addr`.
1073 /// use std::net::Ipv4Addr;
1075 /// let addr = Ipv4Addr::from(0xcafebabe);
1076 /// assert_eq!(Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe), addr);
1079 fn from(ip: u32) -> Ipv4Addr {
1080 Ipv4Addr::from(ip.to_be_bytes())
1084 #[stable(feature = "from_slice_v4", since = "1.9.0")]
1085 impl From<[u8; 4]> for Ipv4Addr {
1086 /// Creates an `Ipv4Addr` from a four element byte array.
1091 /// use std::net::Ipv4Addr;
1093 /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1094 /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1097 fn from(octets: [u8; 4]) -> Ipv4Addr {
1098 Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])
1102 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1103 impl From<[u8; 4]> for IpAddr {
1104 /// Creates an `IpAddr::V4` from a four element byte array.
1109 /// use std::net::{IpAddr, Ipv4Addr};
1111 /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1112 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1115 fn from(octets: [u8; 4]) -> IpAddr {
1116 IpAddr::V4(Ipv4Addr::from(octets))
1121 /// Creates a new IPv6 address from eight 16-bit segments.
1123 /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1128 /// use std::net::Ipv6Addr;
1130 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1132 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1133 #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1134 #[stable(feature = "rust1", since = "1.0.0")]
1136 pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1148 inner: c::in6_addr {
1149 // All elements in `addr16` are big endian.
1150 // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1151 // rustc_allow_const_fn_unstable: the transmute could be written as stable const
1152 // code, but that leads to worse code generation (#75085)
1153 s6_addr: unsafe { transmute::<_, [u8; 16]>(addr16) },
1158 /// An IPv6 address representing localhost: `::1`.
1163 /// use std::net::Ipv6Addr;
1165 /// let addr = Ipv6Addr::LOCALHOST;
1166 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1168 #[stable(feature = "ip_constructors", since = "1.30.0")]
1169 pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1171 /// An IPv6 address representing the unspecified address: `::`
1176 /// use std::net::Ipv6Addr;
1178 /// let addr = Ipv6Addr::UNSPECIFIED;
1179 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1181 #[stable(feature = "ip_constructors", since = "1.30.0")]
1182 pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1184 /// Returns the eight 16-bit segments that make up this address.
1189 /// use std::net::Ipv6Addr;
1191 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1192 /// [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1194 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1195 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1196 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub const fn segments(&self) -> [u16; 8] {
1199 // All elements in `s6_addr` must be big endian.
1200 // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1201 // rustc_allow_const_fn_unstable: the transmute could be written as stable const code, but
1202 // that leads to worse code generation (#75085)
1203 let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.inner.s6_addr) };
1204 // We want native endian u16
1217 /// Returns [`true`] for the special 'unspecified' address (`::`).
1219 /// This property is defined in [IETF RFC 4291].
1221 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1226 /// use std::net::Ipv6Addr;
1228 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1229 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1231 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1232 #[stable(since = "1.7.0", feature = "ip_17")]
1234 pub const fn is_unspecified(&self) -> bool {
1235 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1238 /// Returns [`true`] if this is a loopback address (::1).
1240 /// This property is defined in [IETF RFC 4291].
1242 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1247 /// use std::net::Ipv6Addr;
1249 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1250 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1252 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1253 #[stable(since = "1.7.0", feature = "ip_17")]
1255 pub const fn is_loopback(&self) -> bool {
1256 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1259 /// Returns [`true`] if the address appears to be globally routable.
1261 /// The following return [`false`]:
1263 /// - the loopback address
1264 /// - link-local and unique local unicast addresses
1265 /// - interface-, link-, realm-, admin- and site-local multicast addresses
1272 /// use std::net::Ipv6Addr;
1274 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), true);
1275 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_global(), false);
1276 /// assert_eq!(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1).is_global(), true);
1278 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1279 #[unstable(feature = "ip", issue = "27709")]
1281 pub const fn is_global(&self) -> bool {
1282 match self.multicast_scope() {
1283 Some(Ipv6MulticastScope::Global) => true,
1284 None => self.is_unicast_global(),
1289 /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1291 /// This property is defined in [IETF RFC 4193].
1293 /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1300 /// use std::net::Ipv6Addr;
1302 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1303 /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1305 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1306 #[unstable(feature = "ip", issue = "27709")]
1308 pub const fn is_unique_local(&self) -> bool {
1309 (self.segments()[0] & 0xfe00) == 0xfc00
1312 /// Returns [`true`] if this is a unicast address, as defined by [IETF RFC 4291].
1313 /// Any address that is not a [multicast address] (`ff00::/8`) is unicast.
1315 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1316 /// [multicast address]: Ipv6Addr::is_multicast
1323 /// use std::net::Ipv6Addr;
1325 /// // The unspecified and loopback addresses are unicast.
1326 /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_unicast(), true);
1327 /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast(), true);
1329 /// // Any address that is not a multicast address (`ff00::/8`) is unicast.
1330 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast(), true);
1331 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_unicast(), false);
1333 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1334 #[unstable(feature = "ip", issue = "27709")]
1336 pub const fn is_unicast(&self) -> bool {
1337 !self.is_multicast()
1340 /// Returns `true` if the address is a unicast address with link-local scope,
1341 /// as defined in [RFC 4291].
1343 /// A unicast address has link-local scope if it has the prefix `fe80::/10`, as per [RFC 4291 section 2.4].
1344 /// Note that this encompasses more addresses than those defined in [RFC 4291 section 2.5.6],
1345 /// which describes "Link-Local IPv6 Unicast Addresses" as having the following stricter format:
1348 /// | 10 bits | 54 bits | 64 bits |
1349 /// +----------+-------------------------+----------------------------+
1350 /// |1111111010| 0 | interface ID |
1351 /// +----------+-------------------------+----------------------------+
1353 /// So while currently the only addresses with link-local scope an application will encounter are all in `fe80::/64`,
1354 /// this might change in the future with the publication of new standards. More addresses in `fe80::/10` could be allocated,
1355 /// and those addresses will have link-local scope.
1357 /// 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",
1358 /// this does not mean that the loopback address actually has link-local scope and this method will return `false` on it.
1360 /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
1361 /// [RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1362 /// [RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1363 /// [RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1364 /// [loopback address]: Ipv6Addr::LOCALHOST
1371 /// use std::net::Ipv6Addr;
1373 /// // The loopback address (`::1`) does not actually have link-local scope.
1374 /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast_link_local(), false);
1376 /// // Only addresses in `fe80::/10` have link-local scope.
1377 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), false);
1378 /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1380 /// // Addresses outside the stricter `fe80::/64` also have link-local scope.
1381 /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0).is_unicast_link_local(), true);
1382 /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1384 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1385 #[unstable(feature = "ip", issue = "27709")]
1387 pub const fn is_unicast_link_local(&self) -> bool {
1388 (self.segments()[0] & 0xffc0) == 0xfe80
1391 /// Returns [`true`] if this is an address reserved for documentation
1392 /// (`2001:db8::/32`).
1394 /// This property is defined in [IETF RFC 3849].
1396 /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1403 /// use std::net::Ipv6Addr;
1405 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1406 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1408 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1409 #[unstable(feature = "ip", issue = "27709")]
1411 pub const fn is_documentation(&self) -> bool {
1412 (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1415 /// Returns [`true`] if the address is a globally routable unicast address.
1417 /// The following return false:
1419 /// - the loopback address
1420 /// - the link-local addresses
1421 /// - unique local addresses
1422 /// - the unspecified address
1423 /// - the address range reserved for documentation
1425 /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1428 /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1429 /// be supported in new implementations (i.e., new implementations must treat this prefix as
1430 /// Global Unicast).
1433 /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1440 /// use std::net::Ipv6Addr;
1442 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1443 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1445 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1446 #[unstable(feature = "ip", issue = "27709")]
1448 pub const fn is_unicast_global(&self) -> bool {
1450 && !self.is_loopback()
1451 && !self.is_unicast_link_local()
1452 && !self.is_unique_local()
1453 && !self.is_unspecified()
1454 && !self.is_documentation()
1457 /// Returns the address's multicast scope if the address is multicast.
1464 /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1467 /// Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1468 /// Some(Ipv6MulticastScope::Global)
1470 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1472 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1473 #[unstable(feature = "ip", issue = "27709")]
1475 pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1476 if self.is_multicast() {
1477 match self.segments()[0] & 0x000f {
1478 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1479 2 => Some(Ipv6MulticastScope::LinkLocal),
1480 3 => Some(Ipv6MulticastScope::RealmLocal),
1481 4 => Some(Ipv6MulticastScope::AdminLocal),
1482 5 => Some(Ipv6MulticastScope::SiteLocal),
1483 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1484 14 => Some(Ipv6MulticastScope::Global),
1492 /// Returns [`true`] if this is a multicast address (`ff00::/8`).
1494 /// This property is defined by [IETF RFC 4291].
1496 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1501 /// use std::net::Ipv6Addr;
1503 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1504 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1506 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1507 #[stable(since = "1.7.0", feature = "ip_17")]
1509 pub const fn is_multicast(&self) -> bool {
1510 (self.segments()[0] & 0xff00) == 0xff00
1513 /// Converts this address to an [`IPv4` address] if it's an "IPv4-mapped IPv6 address"
1514 /// defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1516 /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1517 /// All addresses *not* starting with `::ffff` will return `None`.
1519 /// [`IPv4` address]: Ipv4Addr
1520 /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1527 /// use std::net::{Ipv4Addr, Ipv6Addr};
1529 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1530 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1531 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1532 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1534 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1535 #[unstable(feature = "ip", issue = "27709")]
1537 pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1538 match self.octets() {
1539 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1540 Some(Ipv4Addr::new(a, b, c, d))
1546 /// Converts this address to an [`IPv4` address]. Returns [`None`] if this address is
1547 /// neither IPv4-compatible or IPv4-mapped.
1549 /// `::a.b.c.d` and `::ffff:a.b.c.d` become `a.b.c.d`
1551 /// [`IPv4` address]: Ipv4Addr
1556 /// use std::net::{Ipv4Addr, Ipv6Addr};
1558 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1559 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1560 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1561 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1562 /// Some(Ipv4Addr::new(0, 0, 0, 1)));
1564 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1565 #[stable(feature = "rust1", since = "1.0.0")]
1567 pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1568 if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1569 let [a, b] = ab.to_be_bytes();
1570 let [c, d] = cd.to_be_bytes();
1571 Some(Ipv4Addr::new(a, b, c, d))
1577 /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1580 /// use std::net::Ipv6Addr;
1582 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1583 /// [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1585 #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1586 #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1588 pub const fn octets(&self) -> [u8; 16] {
1593 /// Write an Ipv6Addr, conforming to the canonical style described by
1594 /// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1595 #[stable(feature = "rust1", since = "1.0.0")]
1596 impl fmt::Display for Ipv6Addr {
1597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1598 // If there are no alignment requirements, write out the IP address to
1599 // f. Otherwise, write it to a local buffer, then use f.pad.
1600 if f.precision().is_none() && f.width().is_none() {
1601 let segments = self.segments();
1603 // Special case for :: and ::1; otherwise they get written with the
1605 if self.is_unspecified() {
1607 } else if self.is_loopback() {
1609 } else if let Some(ipv4) = self.to_ipv4() {
1611 // IPv4 Compatible address
1612 0 => write!(f, "::{}", ipv4),
1613 // IPv4 Mapped address
1614 0xffff => write!(f, "::ffff:{}", ipv4),
1615 _ => unreachable!(),
1618 #[derive(Copy, Clone, Default)]
1624 // Find the inner 0 span
1626 let mut longest = Span::default();
1627 let mut current = Span::default();
1629 for (i, &segment) in segments.iter().enumerate() {
1631 if current.len == 0 {
1637 if current.len > longest.len {
1641 current = Span::default();
1648 /// Write a colon-separated part of the address
1650 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1651 if let Some((first, tail)) = chunk.split_first() {
1652 write!(f, "{:x}", first)?;
1653 for segment in tail {
1655 write!(f, "{:x}", segment)?;
1662 fmt_subslice(f, &segments[..zeroes.start])?;
1664 fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1666 fmt_subslice(f, &segments)
1670 // Slow path: write the address to a local buffer, the use f.pad.
1671 // Defined recursively by using the fast path to write to the
1674 // This is the largest possible size of an IPv6 address
1675 const IPV6_BUF_LEN: usize = (4 * 8) + 7;
1676 let mut buf = [0u8; IPV6_BUF_LEN];
1677 let mut buf_slice = &mut buf[..];
1679 // Note: This call to write should never fail, so unwrap is okay.
1680 write!(buf_slice, "{}", self).unwrap();
1681 let len = IPV6_BUF_LEN - buf_slice.len();
1683 // This is safe because we know exactly what can be in this buffer
1684 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 impl fmt::Debug for Ipv6Addr {
1692 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1693 fmt::Display::fmt(self, fmt)
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl Clone for Ipv6Addr {
1700 fn clone(&self) -> Ipv6Addr {
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 impl PartialEq for Ipv6Addr {
1708 fn eq(&self, other: &Ipv6Addr) -> bool {
1709 self.inner.s6_addr == other.inner.s6_addr
1713 #[stable(feature = "ip_cmp", since = "1.16.0")]
1714 impl PartialEq<IpAddr> for Ipv6Addr {
1716 fn eq(&self, other: &IpAddr) -> bool {
1718 IpAddr::V4(_) => false,
1719 IpAddr::V6(v6) => self == v6,
1724 #[stable(feature = "ip_cmp", since = "1.16.0")]
1725 impl PartialEq<Ipv6Addr> for IpAddr {
1727 fn eq(&self, other: &Ipv6Addr) -> bool {
1729 IpAddr::V4(_) => false,
1730 IpAddr::V6(v6) => v6 == other,
1735 #[stable(feature = "rust1", since = "1.0.0")]
1736 impl Eq for Ipv6Addr {}
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 impl hash::Hash for Ipv6Addr {
1741 fn hash<H: hash::Hasher>(&self, s: &mut H) {
1742 self.inner.s6_addr.hash(s)
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 impl PartialOrd for Ipv6Addr {
1749 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1750 Some(self.cmp(other))
1754 #[stable(feature = "ip_cmp", since = "1.16.0")]
1755 impl PartialOrd<Ipv6Addr> for IpAddr {
1757 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1759 IpAddr::V4(_) => Some(Ordering::Less),
1760 IpAddr::V6(v6) => v6.partial_cmp(other),
1765 #[stable(feature = "ip_cmp", since = "1.16.0")]
1766 impl PartialOrd<IpAddr> for Ipv6Addr {
1768 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1770 IpAddr::V4(_) => Some(Ordering::Greater),
1771 IpAddr::V6(v6) => self.partial_cmp(v6),
1776 #[stable(feature = "rust1", since = "1.0.0")]
1777 impl Ord for Ipv6Addr {
1779 fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1780 self.segments().cmp(&other.segments())
1784 impl AsInner<c::in6_addr> for Ipv6Addr {
1786 fn as_inner(&self) -> &c::in6_addr {
1790 impl FromInner<c::in6_addr> for Ipv6Addr {
1792 fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1793 Ipv6Addr { inner: addr }
1797 #[stable(feature = "i128", since = "1.26.0")]
1798 impl From<Ipv6Addr> for u128 {
1799 /// Convert an `Ipv6Addr` into a host byte order `u128`.
1804 /// use std::net::Ipv6Addr;
1806 /// let addr = Ipv6Addr::new(
1807 /// 0x1020, 0x3040, 0x5060, 0x7080,
1808 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1810 /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1813 fn from(ip: Ipv6Addr) -> u128 {
1814 let ip = ip.octets();
1815 u128::from_be_bytes(ip)
1818 #[stable(feature = "i128", since = "1.26.0")]
1819 impl From<u128> for Ipv6Addr {
1820 /// Convert a host byte order `u128` into an `Ipv6Addr`.
1825 /// use std::net::Ipv6Addr;
1827 /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1830 /// 0x1020, 0x3040, 0x5060, 0x7080,
1831 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1836 fn from(ip: u128) -> Ipv6Addr {
1837 Ipv6Addr::from(ip.to_be_bytes())
1841 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1842 impl From<[u8; 16]> for Ipv6Addr {
1843 /// Creates an `Ipv6Addr` from a sixteen element byte array.
1848 /// use std::net::Ipv6Addr;
1850 /// let addr = Ipv6Addr::from([
1851 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1852 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1865 fn from(octets: [u8; 16]) -> Ipv6Addr {
1866 let inner = c::in6_addr { s6_addr: octets };
1867 Ipv6Addr::from_inner(inner)
1871 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
1872 impl From<[u16; 8]> for Ipv6Addr {
1873 /// Creates an `Ipv6Addr` from an eight element 16-bit array.
1878 /// use std::net::Ipv6Addr;
1880 /// let addr = Ipv6Addr::from([
1881 /// 525u16, 524u16, 523u16, 522u16,
1882 /// 521u16, 520u16, 519u16, 518u16,
1895 fn from(segments: [u16; 8]) -> Ipv6Addr {
1896 let [a, b, c, d, e, f, g, h] = segments;
1897 Ipv6Addr::new(a, b, c, d, e, f, g, h)
1901 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1902 impl From<[u8; 16]> for IpAddr {
1903 /// Creates an `IpAddr::V6` from a sixteen element byte array.
1908 /// use std::net::{IpAddr, Ipv6Addr};
1910 /// let addr = IpAddr::from([
1911 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1912 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1915 /// IpAddr::V6(Ipv6Addr::new(
1925 fn from(octets: [u8; 16]) -> IpAddr {
1926 IpAddr::V6(Ipv6Addr::from(octets))
1930 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1931 impl From<[u16; 8]> for IpAddr {
1932 /// Creates an `IpAddr::V6` from an eight element 16-bit array.
1937 /// use std::net::{IpAddr, Ipv6Addr};
1939 /// let addr = IpAddr::from([
1940 /// 525u16, 524u16, 523u16, 522u16,
1941 /// 521u16, 520u16, 519u16, 518u16,
1944 /// IpAddr::V6(Ipv6Addr::new(
1954 fn from(segments: [u16; 8]) -> IpAddr {
1955 IpAddr::V6(Ipv6Addr::from(segments))