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").
71 /// [`FromStr`]: crate::str::FromStr
76 /// use std::net::Ipv4Addr;
78 /// let localhost = Ipv4Addr::new(127, 0, 0, 1);
79 /// assert_eq!("127.0.0.1".parse(), Ok(localhost));
80 /// assert_eq!(localhost.is_loopback(), true);
83 #[stable(feature = "rust1", since = "1.0.0")]
90 /// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
91 /// They are usually represented as eight 16-bit segments.
93 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
95 /// The size of an `Ipv6Addr` struct may vary depending on the target operating
98 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
100 /// # Textual representation
102 /// `Ipv6Addr` provides a [`FromStr`] implementation. There are many ways to represent
103 /// an IPv6 address in text, but in general, each segments is written in hexadecimal
104 /// notation, and segments are separated by `:`. For more information, see
107 /// [`FromStr`]: crate::str::FromStr
108 /// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952
113 /// use std::net::Ipv6Addr;
115 /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
116 /// assert_eq!("::1".parse(), Ok(localhost));
117 /// assert_eq!(localhost.is_loopback(), true);
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub struct Ipv6Addr {
125 #[allow(missing_docs)]
126 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
127 pub enum Ipv6MulticastScope {
138 /// Returns [`true`] for the special 'unspecified' address.
140 /// See the documentation for [`Ipv4Addr::is_unspecified()`] and
141 /// [`Ipv6Addr::is_unspecified()`] for more details.
146 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
148 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
149 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
151 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
152 #[stable(feature = "ip_shared", since = "1.12.0")]
154 pub const fn is_unspecified(&self) -> bool {
156 IpAddr::V4(ip) => ip.is_unspecified(),
157 IpAddr::V6(ip) => ip.is_unspecified(),
161 /// Returns [`true`] if this is a loopback address.
163 /// See the documentation for [`Ipv4Addr::is_loopback()`] and
164 /// [`Ipv6Addr::is_loopback()`] for more details.
169 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
171 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
172 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
174 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
175 #[stable(feature = "ip_shared", since = "1.12.0")]
177 pub const fn is_loopback(&self) -> bool {
179 IpAddr::V4(ip) => ip.is_loopback(),
180 IpAddr::V6(ip) => ip.is_loopback(),
184 /// Returns [`true`] if the address appears to be globally routable.
186 /// See the documentation for [`Ipv4Addr::is_global()`] and
187 /// [`Ipv6Addr::is_global()`] for more details.
194 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
196 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true);
197 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true);
199 #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
201 pub const fn is_global(&self) -> bool {
203 IpAddr::V4(ip) => ip.is_global(),
204 IpAddr::V6(ip) => ip.is_global(),
208 /// Returns [`true`] if this is a multicast address.
210 /// See the documentation for [`Ipv4Addr::is_multicast()`] and
211 /// [`Ipv6Addr::is_multicast()`] for more details.
216 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
218 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
219 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
221 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
222 #[stable(feature = "ip_shared", since = "1.12.0")]
224 pub const fn is_multicast(&self) -> bool {
226 IpAddr::V4(ip) => ip.is_multicast(),
227 IpAddr::V6(ip) => ip.is_multicast(),
231 /// Returns [`true`] if this address is in a range designated for documentation.
233 /// See the documentation for [`Ipv4Addr::is_documentation()`] and
234 /// [`Ipv6Addr::is_documentation()`] for more details.
241 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
243 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
245 /// IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(),
249 #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
251 pub const fn is_documentation(&self) -> bool {
253 IpAddr::V4(ip) => ip.is_documentation(),
254 IpAddr::V6(ip) => ip.is_documentation(),
258 /// Returns [`true`] if this address is an [`IPv4` address], and [`false`]
261 /// [`IPv4` address]: IpAddr::V4
266 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
268 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
269 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false);
271 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
272 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
274 pub const fn is_ipv4(&self) -> bool {
275 matches!(self, IpAddr::V4(_))
278 /// Returns [`true`] if this address is an [`IPv6` address], and [`false`]
281 /// [`IPv6` address]: IpAddr::V6
286 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
288 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
289 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true);
291 #[rustc_const_stable(feature = "const_ip", since = "1.50.0")]
292 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
294 pub const fn is_ipv6(&self) -> bool {
295 matches!(self, IpAddr::V6(_))
300 /// Creates a new IPv4 address from four eight-bit octets.
302 /// The result will represent the IP address `a`.`b`.`c`.`d`.
307 /// use std::net::Ipv4Addr;
309 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
311 #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
312 #[stable(feature = "rust1", since = "1.0.0")]
314 pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
315 // `s_addr` is stored as BE on all machine and the array is in BE order.
316 // So the native endian conversion method is used so that it's never swapped.
317 Ipv4Addr { inner: c::in_addr { s_addr: u32::from_ne_bytes([a, b, c, d]) } }
320 /// An IPv4 address with the address pointing to localhost: 127.0.0.1.
325 /// use std::net::Ipv4Addr;
327 /// let addr = Ipv4Addr::LOCALHOST;
328 /// assert_eq!(addr, Ipv4Addr::new(127, 0, 0, 1));
330 #[stable(feature = "ip_constructors", since = "1.30.0")]
331 pub const LOCALHOST: Self = Ipv4Addr::new(127, 0, 0, 1);
333 /// An IPv4 address representing an unspecified address: 0.0.0.0
338 /// use std::net::Ipv4Addr;
340 /// let addr = Ipv4Addr::UNSPECIFIED;
341 /// assert_eq!(addr, Ipv4Addr::new(0, 0, 0, 0));
343 #[stable(feature = "ip_constructors", since = "1.30.0")]
344 pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0);
346 /// An IPv4 address representing the broadcast address: 255.255.255.255
351 /// use std::net::Ipv4Addr;
353 /// let addr = Ipv4Addr::BROADCAST;
354 /// assert_eq!(addr, Ipv4Addr::new(255, 255, 255, 255));
356 #[stable(feature = "ip_constructors", since = "1.30.0")]
357 pub const BROADCAST: Self = Ipv4Addr::new(255, 255, 255, 255);
359 /// Returns the four eight-bit integers that make up this address.
364 /// use std::net::Ipv4Addr;
366 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
367 /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
369 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
370 #[stable(feature = "rust1", since = "1.0.0")]
372 pub const fn octets(&self) -> [u8; 4] {
373 // This returns the order we want because s_addr is stored in big-endian.
374 self.inner.s_addr.to_ne_bytes()
377 /// Returns [`true`] for the special 'unspecified' address (0.0.0.0).
379 /// This property is defined in _UNIX Network Programming, Second Edition_,
380 /// W. Richard Stevens, p. 891; see also [ip7].
382 /// [ip7]: http://man7.org/linux/man-pages/man7/ip.7.html
387 /// use std::net::Ipv4Addr;
389 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
390 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
392 #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
393 #[stable(feature = "ip_shared", since = "1.12.0")]
395 pub const fn is_unspecified(&self) -> bool {
396 self.inner.s_addr == 0
399 /// Returns [`true`] if this is a loopback address (127.0.0.0/8).
401 /// This property is defined by [IETF RFC 1122].
403 /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
408 /// use std::net::Ipv4Addr;
410 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
411 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
413 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
414 #[stable(since = "1.7.0", feature = "ip_17")]
416 pub const fn is_loopback(&self) -> bool {
417 self.octets()[0] == 127
420 /// Returns [`true`] if this is a private address.
422 /// The private address ranges are defined in [IETF RFC 1918] and include:
428 /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
433 /// use std::net::Ipv4Addr;
435 /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
436 /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
437 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
438 /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
439 /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
440 /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
441 /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
443 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
444 #[stable(since = "1.7.0", feature = "ip_17")]
446 pub const fn is_private(&self) -> bool {
447 match self.octets() {
449 [172, b, ..] if b >= 16 && b <= 31 => true,
450 [192, 168, ..] => true,
455 /// Returns [`true`] if the address is link-local (169.254.0.0/16).
457 /// This property is defined by [IETF RFC 3927].
459 /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
464 /// use std::net::Ipv4Addr;
466 /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
467 /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
468 /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
470 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
471 #[stable(since = "1.7.0", feature = "ip_17")]
473 pub const fn is_link_local(&self) -> bool {
474 matches!(self.octets(), [169, 254, ..])
477 /// Returns [`true`] if the address appears to be globally routable.
478 /// See [iana-ipv4-special-registry][ipv4-sr].
480 /// The following return [`false`]:
482 /// - private addresses (see [`Ipv4Addr::is_private()`])
483 /// - the loopback address (see [`Ipv4Addr::is_loopback()`])
484 /// - the link-local address (see [`Ipv4Addr::is_link_local()`])
485 /// - the broadcast address (see [`Ipv4Addr::is_broadcast()`])
486 /// - addresses used for documentation (see [`Ipv4Addr::is_documentation()`])
487 /// - the unspecified address (see [`Ipv4Addr::is_unspecified()`]), and the whole
489 /// - addresses reserved for future protocols (see
490 /// [`Ipv4Addr::is_ietf_protocol_assignment()`], except
491 /// `192.0.0.9/32` and `192.0.0.10/32` which are globally routable
492 /// - addresses reserved for future use (see [`Ipv4Addr::is_reserved()`]
493 /// - addresses reserved for networking devices benchmarking (see
494 /// [`Ipv4Addr::is_benchmarking()`])
496 /// [ipv4-sr]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
503 /// use std::net::Ipv4Addr;
505 /// // private addresses are not global
506 /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
507 /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
508 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
510 /// // the 0.0.0.0/8 block is not global
511 /// assert_eq!(Ipv4Addr::new(0, 1, 2, 3).is_global(), false);
512 /// // in particular, the unspecified address is not global
513 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_global(), false);
515 /// // the loopback address is not global
516 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_global(), false);
518 /// // link local addresses are not global
519 /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
521 /// // the broadcast address is not global
522 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_global(), false);
524 /// // the address space designated for documentation is not global
525 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
526 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
527 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
529 /// // shared addresses are not global
530 /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
532 /// // addresses reserved for protocol assignment are not global
533 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_global(), false);
534 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_global(), false);
536 /// // addresses reserved for future use are not global
537 /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
539 /// // addresses reserved for network devices benchmarking are not global
540 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
542 /// // All the other addresses are global
543 /// assert_eq!(Ipv4Addr::new(1, 1, 1, 1).is_global(), true);
544 /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
546 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
548 pub const fn is_global(&self) -> bool {
549 // check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two
550 // globally routable addresses in the 192.0.0.0/24 range.
551 if u32::from_be_bytes(self.octets()) == 0xc0000009
552 || u32::from_be_bytes(self.octets()) == 0xc000000a
557 && !self.is_loopback()
558 && !self.is_link_local()
559 && !self.is_broadcast()
560 && !self.is_documentation()
562 && !self.is_ietf_protocol_assignment()
563 && !self.is_reserved()
564 && !self.is_benchmarking()
565 // Make sure the address is not in 0.0.0.0/8
566 && self.octets()[0] != 0
569 /// Returns [`true`] if this address is part of the Shared Address Space defined in
570 /// [IETF RFC 6598] (`100.64.0.0/10`).
572 /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
578 /// use std::net::Ipv4Addr;
580 /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
581 /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
582 /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
584 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
586 pub const fn is_shared(&self) -> bool {
587 self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
590 /// Returns [`true`] if this address is part of `192.0.0.0/24`, which is reserved to
591 /// IANA for IETF protocol assignments, as documented in [IETF RFC 6890].
593 /// Note that parts of this block are in use:
595 /// - `192.0.0.8/32` is the "IPv4 dummy address" (see [IETF RFC 7600])
596 /// - `192.0.0.9/32` is the "Port Control Protocol Anycast" (see [IETF RFC 7723])
597 /// - `192.0.0.10/32` is used for NAT traversal (see [IETF RFC 8155])
599 /// [IETF RFC 6890]: https://tools.ietf.org/html/rfc6890
600 /// [IETF RFC 7600]: https://tools.ietf.org/html/rfc7600
601 /// [IETF RFC 7723]: https://tools.ietf.org/html/rfc7723
602 /// [IETF RFC 8155]: https://tools.ietf.org/html/rfc8155
608 /// use std::net::Ipv4Addr;
610 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_ietf_protocol_assignment(), true);
611 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 8).is_ietf_protocol_assignment(), true);
612 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 9).is_ietf_protocol_assignment(), true);
613 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_ietf_protocol_assignment(), true);
614 /// assert_eq!(Ipv4Addr::new(192, 0, 1, 0).is_ietf_protocol_assignment(), false);
615 /// assert_eq!(Ipv4Addr::new(191, 255, 255, 255).is_ietf_protocol_assignment(), false);
617 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
619 pub const fn is_ietf_protocol_assignment(&self) -> bool {
620 self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0
623 /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
624 /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
625 /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
627 /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
628 /// [errata 423]: https://www.rfc-editor.org/errata/eid423
634 /// use std::net::Ipv4Addr;
636 /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
637 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
638 /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
639 /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
641 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
643 pub const fn is_benchmarking(&self) -> bool {
644 self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
647 /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
648 /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
649 /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
650 /// it is obviously not reserved for future use.
652 /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
656 /// As IANA assigns new addresses, this method will be
657 /// updated. This may result in non-reserved addresses being
658 /// treated as reserved in code that relies on an outdated version
665 /// use std::net::Ipv4Addr;
667 /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
668 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
670 /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
671 /// // The broadcast address is not considered as reserved for future use by this implementation
672 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
674 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
676 pub const fn is_reserved(&self) -> bool {
677 self.octets()[0] & 240 == 240 && !self.is_broadcast()
680 /// Returns [`true`] if this is a multicast address (224.0.0.0/4).
682 /// Multicast addresses have a most significant octet between 224 and 239,
683 /// and is defined by [IETF RFC 5771].
685 /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
690 /// use std::net::Ipv4Addr;
692 /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
693 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
694 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
696 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
697 #[stable(since = "1.7.0", feature = "ip_17")]
699 pub const fn is_multicast(&self) -> bool {
700 self.octets()[0] >= 224 && self.octets()[0] <= 239
703 /// Returns [`true`] if this is a broadcast address (255.255.255.255).
705 /// A broadcast address has all octets set to 255 as defined in [IETF RFC 919].
707 /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
712 /// use std::net::Ipv4Addr;
714 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
715 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
717 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
718 #[stable(since = "1.7.0", feature = "ip_17")]
720 pub const fn is_broadcast(&self) -> bool {
721 u32::from_be_bytes(self.octets()) == u32::from_be_bytes(Self::BROADCAST.octets())
724 /// Returns [`true`] if this address is in a range designated for documentation.
726 /// This is defined in [IETF RFC 5737]:
728 /// - 192.0.2.0/24 (TEST-NET-1)
729 /// - 198.51.100.0/24 (TEST-NET-2)
730 /// - 203.0.113.0/24 (TEST-NET-3)
732 /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
737 /// use std::net::Ipv4Addr;
739 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
740 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
741 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
742 /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
744 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
745 #[stable(since = "1.7.0", feature = "ip_17")]
747 pub const fn is_documentation(&self) -> bool {
748 match self.octets() {
749 [192, 0, 2, _] => true,
750 [198, 51, 100, _] => true,
751 [203, 0, 113, _] => true,
756 /// Converts this address to an IPv4-compatible [`IPv6` address].
758 /// a.b.c.d becomes ::a.b.c.d
760 /// This isn't typically the method you want; these addresses don't typically
761 /// function on modern systems. Use `to_ipv6_mapped` instead.
763 /// [`IPv6` address]: Ipv6Addr
768 /// use std::net::{Ipv4Addr, Ipv6Addr};
771 /// Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
772 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 767)
775 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
776 #[stable(feature = "rust1", since = "1.0.0")]
778 pub const fn to_ipv6_compatible(&self) -> Ipv6Addr {
779 let [a, b, c, d] = self.octets();
781 inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] },
785 /// Converts this address to an IPv4-mapped [`IPv6` address].
787 /// a.b.c.d becomes ::ffff:a.b.c.d
789 /// [`IPv6` address]: Ipv6Addr
794 /// use std::net::{Ipv4Addr, Ipv6Addr};
796 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
797 /// Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 49152, 767));
799 #[rustc_const_stable(feature = "const_ipv4", since = "1.50.0")]
800 #[stable(feature = "rust1", since = "1.0.0")]
802 pub const fn to_ipv6_mapped(&self) -> Ipv6Addr {
803 let [a, b, c, d] = self.octets();
805 inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] },
810 #[stable(feature = "ip_addr", since = "1.7.0")]
811 impl fmt::Display for IpAddr {
812 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
814 IpAddr::V4(ip) => ip.fmt(fmt),
815 IpAddr::V6(ip) => ip.fmt(fmt),
820 #[stable(feature = "ip_addr", since = "1.7.0")]
821 impl fmt::Debug for IpAddr {
822 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
823 fmt::Display::fmt(self, fmt)
827 #[stable(feature = "ip_from_ip", since = "1.16.0")]
828 impl From<Ipv4Addr> for IpAddr {
829 /// Copies this address to a new `IpAddr::V4`.
834 /// use std::net::{IpAddr, Ipv4Addr};
836 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
839 /// IpAddr::V4(addr),
840 /// IpAddr::from(addr)
844 fn from(ipv4: Ipv4Addr) -> IpAddr {
849 #[stable(feature = "ip_from_ip", since = "1.16.0")]
850 impl From<Ipv6Addr> for IpAddr {
851 /// Copies this address to a new `IpAddr::V6`.
856 /// use std::net::{IpAddr, Ipv6Addr};
858 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
861 /// IpAddr::V6(addr),
862 /// IpAddr::from(addr)
866 fn from(ipv6: Ipv6Addr) -> IpAddr {
871 #[stable(feature = "rust1", since = "1.0.0")]
872 impl fmt::Display for Ipv4Addr {
873 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
874 let octets = self.octets();
875 // Fast Path: if there's no alignment stuff, write directly to the buffer
876 if fmt.precision().is_none() && fmt.width().is_none() {
877 write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
879 const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
880 let mut buf = [0u8; IPV4_BUF_LEN];
881 let mut buf_slice = &mut buf[..];
883 // Note: The call to write should never fail, hence the unwrap
884 write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
885 let len = IPV4_BUF_LEN - buf_slice.len();
887 // This unsafe is OK because we know what is being written to the buffer
888 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl fmt::Debug for Ipv4Addr {
896 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
897 fmt::Display::fmt(self, fmt)
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl Clone for Ipv4Addr {
904 fn clone(&self) -> Ipv4Addr {
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl PartialEq for Ipv4Addr {
912 fn eq(&self, other: &Ipv4Addr) -> bool {
913 self.inner.s_addr == other.inner.s_addr
917 #[stable(feature = "ip_cmp", since = "1.16.0")]
918 impl PartialEq<Ipv4Addr> for IpAddr {
920 fn eq(&self, other: &Ipv4Addr) -> bool {
922 IpAddr::V4(v4) => v4 == other,
923 IpAddr::V6(_) => false,
928 #[stable(feature = "ip_cmp", since = "1.16.0")]
929 impl PartialEq<IpAddr> for Ipv4Addr {
931 fn eq(&self, other: &IpAddr) -> bool {
933 IpAddr::V4(v4) => self == v4,
934 IpAddr::V6(_) => false,
939 #[stable(feature = "rust1", since = "1.0.0")]
940 impl Eq for Ipv4Addr {}
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl hash::Hash for Ipv4Addr {
945 fn hash<H: hash::Hasher>(&self, s: &mut H) {
947 // * hash in big endian order
948 // * in netbsd, `in_addr` has `repr(packed)`, we need to
949 // copy `s_addr` to avoid unsafe borrowing
950 { self.inner.s_addr }.hash(s)
954 #[stable(feature = "rust1", since = "1.0.0")]
955 impl PartialOrd for Ipv4Addr {
957 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
958 Some(self.cmp(other))
962 #[stable(feature = "ip_cmp", since = "1.16.0")]
963 impl PartialOrd<Ipv4Addr> for IpAddr {
965 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
967 IpAddr::V4(v4) => v4.partial_cmp(other),
968 IpAddr::V6(_) => Some(Ordering::Greater),
973 #[stable(feature = "ip_cmp", since = "1.16.0")]
974 impl PartialOrd<IpAddr> for Ipv4Addr {
976 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
978 IpAddr::V4(v4) => self.partial_cmp(v4),
979 IpAddr::V6(_) => Some(Ordering::Less),
984 #[stable(feature = "rust1", since = "1.0.0")]
985 impl Ord for Ipv4Addr {
987 fn cmp(&self, other: &Ipv4Addr) -> Ordering {
988 // Compare as native endian
989 u32::from_be(self.inner.s_addr).cmp(&u32::from_be(other.inner.s_addr))
993 impl IntoInner<c::in_addr> for Ipv4Addr {
994 fn into_inner(self) -> c::in_addr {
999 #[stable(feature = "ip_u32", since = "1.1.0")]
1000 impl From<Ipv4Addr> for u32 {
1001 /// Converts an `Ipv4Addr` into a host byte order `u32`.
1006 /// use std::net::Ipv4Addr;
1008 /// let addr = Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe);
1009 /// assert_eq!(0xcafebabe, u32::from(addr));
1012 fn from(ip: Ipv4Addr) -> u32 {
1013 let ip = ip.octets();
1014 u32::from_be_bytes(ip)
1018 #[stable(feature = "ip_u32", since = "1.1.0")]
1019 impl From<u32> for Ipv4Addr {
1020 /// Converts a host byte order `u32` into an `Ipv4Addr`.
1025 /// use std::net::Ipv4Addr;
1027 /// let addr = Ipv4Addr::from(0xcafebabe);
1028 /// assert_eq!(Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe), addr);
1031 fn from(ip: u32) -> Ipv4Addr {
1032 Ipv4Addr::from(ip.to_be_bytes())
1036 #[stable(feature = "from_slice_v4", since = "1.9.0")]
1037 impl From<[u8; 4]> for Ipv4Addr {
1038 /// Creates an `Ipv4Addr` from a four element byte array.
1043 /// use std::net::Ipv4Addr;
1045 /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1046 /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1049 fn from(octets: [u8; 4]) -> Ipv4Addr {
1050 Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])
1054 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1055 impl From<[u8; 4]> for IpAddr {
1056 /// Creates an `IpAddr::V4` from a four element byte array.
1061 /// use std::net::{IpAddr, Ipv4Addr};
1063 /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1064 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1067 fn from(octets: [u8; 4]) -> IpAddr {
1068 IpAddr::V4(Ipv4Addr::from(octets))
1073 /// Creates a new IPv6 address from eight 16-bit segments.
1075 /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1080 /// use std::net::Ipv6Addr;
1082 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1084 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1085 #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1086 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1100 inner: c::in6_addr {
1101 // All elements in `addr16` are big endian.
1102 // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1103 // rustc_allow_const_fn_unstable: the transmute could be written as stable const
1104 // code, but that leads to worse code generation (#75085)
1105 s6_addr: unsafe { transmute::<_, [u8; 16]>(addr16) },
1110 /// An IPv6 address representing localhost: `::1`.
1115 /// use std::net::Ipv6Addr;
1117 /// let addr = Ipv6Addr::LOCALHOST;
1118 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1120 #[stable(feature = "ip_constructors", since = "1.30.0")]
1121 pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1123 /// An IPv6 address representing the unspecified address: `::`
1128 /// use std::net::Ipv6Addr;
1130 /// let addr = Ipv6Addr::UNSPECIFIED;
1131 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1133 #[stable(feature = "ip_constructors", since = "1.30.0")]
1134 pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1136 /// Returns the eight 16-bit segments that make up this address.
1141 /// use std::net::Ipv6Addr;
1143 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1144 /// [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1146 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
1147 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1148 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub const fn segments(&self) -> [u16; 8] {
1151 // All elements in `s6_addr` must be big endian.
1152 // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1153 // rustc_allow_const_fn_unstable: the transmute could be written as stable const code, but
1154 // that leads to worse code generation (#75085)
1155 let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.inner.s6_addr) };
1156 // We want native endian u16
1169 /// Returns [`true`] for the special 'unspecified' address (::).
1171 /// This property is defined in [IETF RFC 4291].
1173 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1178 /// use std::net::Ipv6Addr;
1180 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1181 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1183 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1184 #[stable(since = "1.7.0", feature = "ip_17")]
1186 pub const fn is_unspecified(&self) -> bool {
1187 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1190 /// Returns [`true`] if this is a loopback address (::1).
1192 /// This property is defined in [IETF RFC 4291].
1194 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1199 /// use std::net::Ipv6Addr;
1201 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1202 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1204 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1205 #[stable(since = "1.7.0", feature = "ip_17")]
1207 pub const fn is_loopback(&self) -> bool {
1208 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1211 /// Returns [`true`] if the address appears to be globally routable.
1213 /// The following return [`false`]:
1215 /// - the loopback address
1216 /// - link-local and unique local unicast addresses
1217 /// - interface-, link-, realm-, admin- and site-local multicast addresses
1224 /// use std::net::Ipv6Addr;
1226 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), true);
1227 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_global(), false);
1228 /// assert_eq!(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1).is_global(), true);
1230 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1232 pub const fn is_global(&self) -> bool {
1233 match self.multicast_scope() {
1234 Some(Ipv6MulticastScope::Global) => true,
1235 None => self.is_unicast_global(),
1240 /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1242 /// This property is defined in [IETF RFC 4193].
1244 /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1251 /// use std::net::Ipv6Addr;
1253 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1254 /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1256 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1258 pub const fn is_unique_local(&self) -> bool {
1259 (self.segments()[0] & 0xfe00) == 0xfc00
1262 /// Returns [`true`] if the address is a unicast link-local address (`fe80::/64`).
1264 /// A common misconception is to think that "unicast link-local addresses start with
1265 /// `fe80::`", but [IETF RFC 4291] actually defines a stricter format for these addresses:
1269 /// | bits | 54 bits | 64 bits |
1270 /// +----------+-------------------------+----------------------------+
1271 /// |1111111010| 0 | interface ID |
1272 /// +----------+-------------------------+----------------------------+
1275 /// This method validates the format defined in the RFC and won't recognize addresses
1276 /// like `fe80:0:0:1::` or `fe81::` as unicast link-local addresses.
1277 /// If you need a less strict validation, use [`Ipv6Addr::is_unicast_link_local()`] instead.
1284 /// use std::net::Ipv6Addr;
1286 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0);
1287 /// assert!(ip.is_unicast_link_local_strict());
1289 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff);
1290 /// assert!(ip.is_unicast_link_local_strict());
1292 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0);
1293 /// assert!(!ip.is_unicast_link_local_strict());
1294 /// assert!(ip.is_unicast_link_local());
1296 /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0);
1297 /// assert!(!ip.is_unicast_link_local_strict());
1298 /// assert!(ip.is_unicast_link_local());
1303 /// - [IETF RFC 4291 section 2.5.6]
1304 /// - [RFC 4291 errata 4406] (which has been rejected but provides useful
1306 /// - [`Ipv6Addr::is_unicast_link_local()`]
1308 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1309 /// [IETF RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1310 /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406
1311 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1313 pub const fn is_unicast_link_local_strict(&self) -> bool {
1314 matches!(self.segments(), [0xfe80, 0, 0, 0, ..])
1317 /// Returns [`true`] if the address is a unicast link-local address (`fe80::/10`).
1319 /// This method returns [`true`] for addresses in the range reserved by [RFC 4291 section 2.4],
1320 /// i.e. addresses with the following format:
1324 /// | bits | 54 bits | 64 bits |
1325 /// +----------+-------------------------+----------------------------+
1326 /// |1111111010| arbitratry value | interface ID |
1327 /// +----------+-------------------------+----------------------------+
1330 /// As a result, this method considers addresses such as `fe80:0:0:1::` or `fe81::` to be
1331 /// unicast link-local addresses, whereas [`Ipv6Addr::is_unicast_link_local_strict()`] does not.
1332 /// If you need a strict validation fully compliant with the RFC, use
1333 /// [`Ipv6Addr::is_unicast_link_local_strict()`] instead.
1340 /// use std::net::Ipv6Addr;
1342 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0);
1343 /// assert!(ip.is_unicast_link_local());
1345 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff);
1346 /// assert!(ip.is_unicast_link_local());
1348 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0);
1349 /// assert!(ip.is_unicast_link_local());
1350 /// assert!(!ip.is_unicast_link_local_strict());
1352 /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0);
1353 /// assert!(ip.is_unicast_link_local());
1354 /// assert!(!ip.is_unicast_link_local_strict());
1359 /// - [IETF RFC 4291 section 2.4]
1360 /// - [RFC 4291 errata 4406] (which has been rejected but provides useful
1363 /// [IETF RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1364 /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406
1365 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1367 pub const fn is_unicast_link_local(&self) -> bool {
1368 (self.segments()[0] & 0xffc0) == 0xfe80
1371 /// Returns [`true`] if this is a deprecated unicast site-local address (fec0::/10). The
1372 /// unicast site-local address format is defined in [RFC 4291 section 2.5.7] as:
1376 /// | bits | 54 bits | 64 bits |
1377 /// +----------+-------------------------+----------------------------+
1378 /// |1111111011| subnet ID | interface ID |
1379 /// +----------+-------------------------+----------------------------+
1382 /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1389 /// use std::net::Ipv6Addr;
1392 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_site_local(),
1395 /// assert_eq!(Ipv6Addr::new(0xfec2, 0, 0, 0, 0, 0, 0, 0).is_unicast_site_local(), true);
1400 /// As per [RFC 3879], the whole `FEC0::/10` prefix is
1401 /// deprecated. New software must not support site-local
1404 /// [RFC 3879]: https://tools.ietf.org/html/rfc3879
1405 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1407 pub const fn is_unicast_site_local(&self) -> bool {
1408 (self.segments()[0] & 0xffc0) == 0xfec0
1411 /// Returns [`true`] if this is an address reserved for documentation
1412 /// (`2001:db8::/32`).
1414 /// This property is defined in [IETF RFC 3849].
1416 /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1423 /// use std::net::Ipv6Addr;
1425 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1426 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1428 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1430 pub const fn is_documentation(&self) -> bool {
1431 (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1434 /// Returns [`true`] if the address is a globally routable unicast address.
1436 /// The following return false:
1438 /// - the loopback address
1439 /// - the link-local addresses
1440 /// - unique local addresses
1441 /// - the unspecified address
1442 /// - the address range reserved for documentation
1444 /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1447 /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1448 /// be supported in new implementations (i.e., new implementations must treat this prefix as
1449 /// Global Unicast).
1452 /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1459 /// use std::net::Ipv6Addr;
1461 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1462 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1464 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1466 pub const fn is_unicast_global(&self) -> bool {
1467 !self.is_multicast()
1468 && !self.is_loopback()
1469 && !self.is_unicast_link_local()
1470 && !self.is_unique_local()
1471 && !self.is_unspecified()
1472 && !self.is_documentation()
1475 /// Returns the address's multicast scope if the address is multicast.
1482 /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1485 /// Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1486 /// Some(Ipv6MulticastScope::Global)
1488 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1490 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1492 pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1493 if self.is_multicast() {
1494 match self.segments()[0] & 0x000f {
1495 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1496 2 => Some(Ipv6MulticastScope::LinkLocal),
1497 3 => Some(Ipv6MulticastScope::RealmLocal),
1498 4 => Some(Ipv6MulticastScope::AdminLocal),
1499 5 => Some(Ipv6MulticastScope::SiteLocal),
1500 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1501 14 => Some(Ipv6MulticastScope::Global),
1509 /// Returns [`true`] if this is a multicast address (ff00::/8).
1511 /// This property is defined by [IETF RFC 4291].
1513 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1518 /// use std::net::Ipv6Addr;
1520 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1521 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1523 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1524 #[stable(since = "1.7.0", feature = "ip_17")]
1526 pub const fn is_multicast(&self) -> bool {
1527 (self.segments()[0] & 0xff00) == 0xff00
1530 /// Converts this address to an [`IPv4` address] if it's an "IPv4-mapped IPv6 address"
1531 /// defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1533 /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1534 /// All addresses *not* starting with `::ffff` will return `None`.
1536 /// [`IPv4` address]: Ipv4Addr
1537 /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1544 /// use std::net::{Ipv4Addr, Ipv6Addr};
1546 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1547 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1548 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1549 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1551 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1553 pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1554 match self.octets() {
1555 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1556 Some(Ipv4Addr::new(a, b, c, d))
1562 /// Converts this address to an [`IPv4` address]. Returns [`None`] if this address is
1563 /// neither IPv4-compatible or IPv4-mapped.
1565 /// ::a.b.c.d and ::ffff:a.b.c.d become a.b.c.d
1567 /// [`IPv4` address]: Ipv4Addr
1572 /// use std::net::{Ipv4Addr, Ipv6Addr};
1574 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1575 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1576 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1577 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1578 /// Some(Ipv4Addr::new(0, 0, 0, 1)));
1580 #[rustc_const_stable(feature = "const_ipv6", since = "1.50.0")]
1581 #[stable(feature = "rust1", since = "1.0.0")]
1583 pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1584 if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1585 let [a, b] = ab.to_be_bytes();
1586 let [c, d] = cd.to_be_bytes();
1587 Some(Ipv4Addr::new(a, b, c, d))
1593 /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1596 /// use std::net::Ipv6Addr;
1598 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1599 /// [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1601 #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1602 #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1604 pub const fn octets(&self) -> [u8; 16] {
1609 /// Write an Ipv6Addr, conforming to the canonical style described by
1610 /// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1611 #[stable(feature = "rust1", since = "1.0.0")]
1612 impl fmt::Display for Ipv6Addr {
1613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1614 // If there are no alignment requirements, write out the IP address to
1615 // f. Otherwise, write it to a local buffer, then use f.pad.
1616 if f.precision().is_none() && f.width().is_none() {
1617 let segments = self.segments();
1619 // Special case for :: and ::1; otherwise they get written with the
1621 if self.is_unspecified() {
1623 } else if self.is_loopback() {
1625 } else if let Some(ipv4) = self.to_ipv4() {
1627 // IPv4 Compatible address
1628 0 => write!(f, "::{}", ipv4),
1629 // IPv4 Mapped address
1630 0xffff => write!(f, "::ffff:{}", ipv4),
1631 _ => unreachable!(),
1634 #[derive(Copy, Clone, Default)]
1640 // Find the inner 0 span
1642 let mut longest = Span::default();
1643 let mut current = Span::default();
1645 for (i, &segment) in segments.iter().enumerate() {
1647 if current.len == 0 {
1653 if current.len > longest.len {
1657 current = Span::default();
1664 /// Write a colon-separated part of the address
1666 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1667 if let Some((first, tail)) = chunk.split_first() {
1668 write!(f, "{:x}", first)?;
1669 for segment in tail {
1671 write!(f, "{:x}", segment)?;
1678 fmt_subslice(f, &segments[..zeroes.start])?;
1680 fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1682 fmt_subslice(f, &segments)
1686 // Slow path: write the address to a local buffer, the use f.pad.
1687 // Defined recursively by using the fast path to write to the
1690 // This is the largest possible size of an IPv6 address
1691 const IPV6_BUF_LEN: usize = (4 * 8) + 7;
1692 let mut buf = [0u8; IPV6_BUF_LEN];
1693 let mut buf_slice = &mut buf[..];
1695 // Note: This call to write should never fail, so unwrap is okay.
1696 write!(buf_slice, "{}", self).unwrap();
1697 let len = IPV6_BUF_LEN - buf_slice.len();
1699 // This is safe because we know exactly what can be in this buffer
1700 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1706 #[stable(feature = "rust1", since = "1.0.0")]
1707 impl fmt::Debug for Ipv6Addr {
1708 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1709 fmt::Display::fmt(self, fmt)
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 impl Clone for Ipv6Addr {
1716 fn clone(&self) -> Ipv6Addr {
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 impl PartialEq for Ipv6Addr {
1724 fn eq(&self, other: &Ipv6Addr) -> bool {
1725 self.inner.s6_addr == other.inner.s6_addr
1729 #[stable(feature = "ip_cmp", since = "1.16.0")]
1730 impl PartialEq<IpAddr> for Ipv6Addr {
1732 fn eq(&self, other: &IpAddr) -> bool {
1734 IpAddr::V4(_) => false,
1735 IpAddr::V6(v6) => self == v6,
1740 #[stable(feature = "ip_cmp", since = "1.16.0")]
1741 impl PartialEq<Ipv6Addr> for IpAddr {
1743 fn eq(&self, other: &Ipv6Addr) -> bool {
1745 IpAddr::V4(_) => false,
1746 IpAddr::V6(v6) => v6 == other,
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 impl Eq for Ipv6Addr {}
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 impl hash::Hash for Ipv6Addr {
1757 fn hash<H: hash::Hasher>(&self, s: &mut H) {
1758 self.inner.s6_addr.hash(s)
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl PartialOrd for Ipv6Addr {
1765 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1766 Some(self.cmp(other))
1770 #[stable(feature = "ip_cmp", since = "1.16.0")]
1771 impl PartialOrd<Ipv6Addr> for IpAddr {
1773 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1775 IpAddr::V4(_) => Some(Ordering::Less),
1776 IpAddr::V6(v6) => v6.partial_cmp(other),
1781 #[stable(feature = "ip_cmp", since = "1.16.0")]
1782 impl PartialOrd<IpAddr> for Ipv6Addr {
1784 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1786 IpAddr::V4(_) => Some(Ordering::Greater),
1787 IpAddr::V6(v6) => self.partial_cmp(v6),
1792 #[stable(feature = "rust1", since = "1.0.0")]
1793 impl Ord for Ipv6Addr {
1795 fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1796 self.segments().cmp(&other.segments())
1800 impl AsInner<c::in6_addr> for Ipv6Addr {
1801 fn as_inner(&self) -> &c::in6_addr {
1805 impl FromInner<c::in6_addr> for Ipv6Addr {
1806 fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1807 Ipv6Addr { inner: addr }
1811 #[stable(feature = "i128", since = "1.26.0")]
1812 impl From<Ipv6Addr> for u128 {
1813 /// Convert an `Ipv6Addr` into a host byte order `u128`.
1818 /// use std::net::Ipv6Addr;
1820 /// let addr = Ipv6Addr::new(
1821 /// 0x1020, 0x3040, 0x5060, 0x7080,
1822 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1824 /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1827 fn from(ip: Ipv6Addr) -> u128 {
1828 let ip = ip.octets();
1829 u128::from_be_bytes(ip)
1832 #[stable(feature = "i128", since = "1.26.0")]
1833 impl From<u128> for Ipv6Addr {
1834 /// Convert a host byte order `u128` into an `Ipv6Addr`.
1839 /// use std::net::Ipv6Addr;
1841 /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1844 /// 0x1020, 0x3040, 0x5060, 0x7080,
1845 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1850 fn from(ip: u128) -> Ipv6Addr {
1851 Ipv6Addr::from(ip.to_be_bytes())
1855 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1856 impl From<[u8; 16]> for Ipv6Addr {
1857 /// Creates an `Ipv6Addr` from a sixteen element byte array.
1862 /// use std::net::Ipv6Addr;
1864 /// let addr = Ipv6Addr::from([
1865 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1866 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1879 fn from(octets: [u8; 16]) -> Ipv6Addr {
1880 let inner = c::in6_addr { s6_addr: octets };
1881 Ipv6Addr::from_inner(inner)
1885 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
1886 impl From<[u16; 8]> for Ipv6Addr {
1887 /// Creates an `Ipv6Addr` from an eight element 16-bit array.
1892 /// use std::net::Ipv6Addr;
1894 /// let addr = Ipv6Addr::from([
1895 /// 525u16, 524u16, 523u16, 522u16,
1896 /// 521u16, 520u16, 519u16, 518u16,
1909 fn from(segments: [u16; 8]) -> Ipv6Addr {
1910 let [a, b, c, d, e, f, g, h] = segments;
1911 Ipv6Addr::new(a, b, c, d, e, f, g, h)
1915 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1916 impl From<[u8; 16]> for IpAddr {
1917 /// Creates an `IpAddr::V6` from a sixteen element byte array.
1922 /// use std::net::{IpAddr, Ipv6Addr};
1924 /// let addr = IpAddr::from([
1925 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1926 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1929 /// IpAddr::V6(Ipv6Addr::new(
1939 fn from(octets: [u8; 16]) -> IpAddr {
1940 IpAddr::V6(Ipv6Addr::from(octets))
1944 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1945 impl From<[u16; 8]> for IpAddr {
1946 /// Creates an `IpAddr::V6` from an eight element 16-bit array.
1951 /// use std::net::{IpAddr, Ipv6Addr};
1953 /// let addr = IpAddr::from([
1954 /// 525u16, 524u16, 523u16, 522u16,
1955 /// 521u16, 520u16, 519u16, 518u16,
1958 /// IpAddr::V6(Ipv6Addr::new(
1968 fn from(segments: [u16; 8]) -> IpAddr {
1969 IpAddr::V6(Ipv6Addr::from(segments))