1 // Tests for this module
2 #[cfg(all(test, not(target_os = "emscripten")))]
5 use crate::cmp::Ordering;
6 use crate::fmt::{self, Write};
7 use crate::mem::transmute;
8 use crate::sys::net::netc as c;
9 use crate::sys_common::{FromInner, IntoInner};
11 use super::display_buffer::DisplayBuffer;
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.
21 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
23 /// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
24 /// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
26 /// assert_eq!("127.0.0.1".parse(), Ok(localhost_v4));
27 /// assert_eq!("::1".parse(), Ok(localhost_v6));
29 /// assert_eq!(localhost_v4.is_ipv6(), false);
30 /// assert_eq!(localhost_v4.is_ipv4(), true);
32 #[cfg_attr(not(test), rustc_diagnostic_item = "IpAddr")]
33 #[stable(feature = "ip_addr", since = "1.7.0")]
34 #[derive(Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
37 #[stable(feature = "ip_addr", since = "1.7.0")]
38 V4(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv4Addr),
40 #[stable(feature = "ip_addr", since = "1.7.0")]
41 V6(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv6Addr),
46 /// IPv4 addresses are defined as 32-bit integers in [IETF RFC 791].
47 /// They are usually represented as four octets.
49 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
51 /// [IETF RFC 791]: https://tools.ietf.org/html/rfc791
53 /// # Textual representation
55 /// `Ipv4Addr` provides a [`FromStr`] implementation. The four octets are in decimal
56 /// notation, divided by `.` (this is called "dot-decimal notation").
57 /// Notably, octal numbers (which are indicated with a leading `0`) and hexadecimal numbers (which
58 /// are indicated with a leading `0x`) are not allowed per [IETF RFC 6943].
60 /// [IETF RFC 6943]: https://tools.ietf.org/html/rfc6943#section-3.1.1
61 /// [`FromStr`]: crate::str::FromStr
66 /// use std::net::Ipv4Addr;
68 /// let localhost = Ipv4Addr::new(127, 0, 0, 1);
69 /// assert_eq!("127.0.0.1".parse(), Ok(localhost));
70 /// assert_eq!(localhost.is_loopback(), true);
71 /// assert!("012.004.002.000".parse::<Ipv4Addr>().is_err()); // all octets are in octal
72 /// assert!("0000000.0.0.0".parse::<Ipv4Addr>().is_err()); // first octet is a zero in octal
73 /// assert!("0xcb.0x0.0x71.0x00".parse::<Ipv4Addr>().is_err()); // all octets are in hex
75 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
76 #[stable(feature = "rust1", since = "1.0.0")]
83 /// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
84 /// They are usually represented as eight 16-bit segments.
86 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
88 /// # Embedding IPv4 Addresses
90 /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
92 /// To assist in the transition from IPv4 to IPv6 two types of IPv6 addresses that embed an IPv4 address were defined:
93 /// IPv4-compatible and IPv4-mapped addresses. Of these IPv4-compatible addresses have been officially deprecated.
95 /// Both types of addresses are not assigned any special meaning by this implementation,
96 /// other than what the relevant standards prescribe. This means that an address like `::ffff:127.0.0.1`,
97 /// while representing an IPv4 loopback address, is not itself an IPv6 loopback address; only `::1` is.
98 /// To handle these so called "IPv4-in-IPv6" addresses, they have to first be converted to their canonical IPv4 address.
100 /// ### IPv4-Compatible IPv6 Addresses
102 /// IPv4-compatible IPv6 addresses are defined in [IETF RFC 4291 Section 2.5.5.1], and have been officially deprecated.
103 /// The RFC describes the format of an "IPv4-Compatible IPv6 address" as follows:
106 /// | 80 bits | 16 | 32 bits |
107 /// +--------------------------------------+--------------------------+
108 /// |0000..............................0000|0000| IPv4 address |
109 /// +--------------------------------------+----+---------------------+
111 /// So `::a.b.c.d` would be an IPv4-compatible IPv6 address representing the IPv4 address `a.b.c.d`.
113 /// To convert from an IPv4 address to an IPv4-compatible IPv6 address, use [`Ipv4Addr::to_ipv6_compatible`].
114 /// Use [`Ipv6Addr::to_ipv4`] to convert an IPv4-compatible IPv6 address to the canonical IPv4 address.
116 /// [IETF RFC 4291 Section 2.5.5.1]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.1
118 /// ### IPv4-Mapped IPv6 Addresses
120 /// IPv4-mapped IPv6 addresses are defined in [IETF RFC 4291 Section 2.5.5.2].
121 /// The RFC describes the format of an "IPv4-Mapped IPv6 address" as follows:
124 /// | 80 bits | 16 | 32 bits |
125 /// +--------------------------------------+--------------------------+
126 /// |0000..............................0000|FFFF| IPv4 address |
127 /// +--------------------------------------+----+---------------------+
129 /// So `::ffff:a.b.c.d` would be an IPv4-mapped IPv6 address representing the IPv4 address `a.b.c.d`.
131 /// To convert from an IPv4 address to an IPv4-mapped IPv6 address, use [`Ipv4Addr::to_ipv6_mapped`].
132 /// Use [`Ipv6Addr::to_ipv4`] to convert an IPv4-mapped IPv6 address to the canonical IPv4 address.
133 /// Note that this will also convert the IPv6 loopback address `::1` to `0.0.0.1`. Use
134 /// [`Ipv6Addr::to_ipv4_mapped`] to avoid this.
136 /// [IETF RFC 4291 Section 2.5.5.2]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2
138 /// # Textual representation
140 /// `Ipv6Addr` provides a [`FromStr`] implementation. There are many ways to represent
141 /// an IPv6 address in text, but in general, each segments is written in hexadecimal
142 /// notation, and segments are separated by `:`. For more information, see
145 /// [`FromStr`]: crate::str::FromStr
146 /// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952
151 /// use std::net::Ipv6Addr;
153 /// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
154 /// assert_eq!("::1".parse(), Ok(localhost));
155 /// assert_eq!(localhost.is_loopback(), true);
157 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
158 #[stable(feature = "rust1", since = "1.0.0")]
159 pub struct Ipv6Addr {
163 /// Scope of an [IPv6 multicast address] as defined in [IETF RFC 7346 section 2].
165 /// # Stability Guarantees
167 /// Not all possible values for a multicast scope have been assigned.
168 /// Future RFCs may introduce new scopes, which will be added as variants to this enum;
169 /// because of this the enum is marked as `#[non_exhaustive]`.
175 /// use std::net::Ipv6Addr;
176 /// use std::net::Ipv6MulticastScope::*;
178 /// // An IPv6 multicast address with global scope (`ff0e::`).
179 /// let address = Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0);
181 /// // Will print "Global scope".
182 /// match address.multicast_scope() {
183 /// Some(InterfaceLocal) => println!("Interface-Local scope"),
184 /// Some(LinkLocal) => println!("Link-Local scope"),
185 /// Some(RealmLocal) => println!("Realm-Local scope"),
186 /// Some(AdminLocal) => println!("Admin-Local scope"),
187 /// Some(SiteLocal) => println!("Site-Local scope"),
188 /// Some(OrganizationLocal) => println!("Organization-Local scope"),
189 /// Some(Global) => println!("Global scope"),
190 /// Some(_) => println!("Unknown scope"),
191 /// None => println!("Not a multicast address!")
196 /// [IPv6 multicast address]: Ipv6Addr
197 /// [IETF RFC 7346 section 2]: https://tools.ietf.org/html/rfc7346#section-2
198 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
199 #[unstable(feature = "ip", issue = "27709")]
201 pub enum Ipv6MulticastScope {
202 /// Interface-Local scope.
204 /// Link-Local scope.
206 /// Realm-Local scope.
208 /// Admin-Local scope.
210 /// Site-Local scope.
212 /// Organization-Local scope.
219 /// Returns [`true`] for the special 'unspecified' address.
221 /// See the documentation for [`Ipv4Addr::is_unspecified()`] and
222 /// [`Ipv6Addr::is_unspecified()`] for more details.
227 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
229 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
230 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
232 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
233 #[stable(feature = "ip_shared", since = "1.12.0")]
236 pub const fn is_unspecified(&self) -> bool {
238 IpAddr::V4(ip) => ip.is_unspecified(),
239 IpAddr::V6(ip) => ip.is_unspecified(),
243 /// Returns [`true`] if this is a loopback address.
245 /// See the documentation for [`Ipv4Addr::is_loopback()`] and
246 /// [`Ipv6Addr::is_loopback()`] for more details.
251 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
253 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
254 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
256 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
257 #[stable(feature = "ip_shared", since = "1.12.0")]
260 pub const fn is_loopback(&self) -> bool {
262 IpAddr::V4(ip) => ip.is_loopback(),
263 IpAddr::V6(ip) => ip.is_loopback(),
267 /// Returns [`true`] if the address appears to be globally routable.
269 /// See the documentation for [`Ipv4Addr::is_global()`] and
270 /// [`Ipv6Addr::is_global()`] for more details.
277 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
279 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true);
280 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true);
282 #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
283 #[unstable(feature = "ip", issue = "27709")]
286 pub const fn is_global(&self) -> bool {
288 IpAddr::V4(ip) => ip.is_global(),
289 IpAddr::V6(ip) => ip.is_global(),
293 /// Returns [`true`] if this is a multicast address.
295 /// See the documentation for [`Ipv4Addr::is_multicast()`] and
296 /// [`Ipv6Addr::is_multicast()`] for more details.
301 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
303 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
304 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
306 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
307 #[stable(feature = "ip_shared", since = "1.12.0")]
310 pub const fn is_multicast(&self) -> bool {
312 IpAddr::V4(ip) => ip.is_multicast(),
313 IpAddr::V6(ip) => ip.is_multicast(),
317 /// Returns [`true`] if this address is in a range designated for documentation.
319 /// See the documentation for [`Ipv4Addr::is_documentation()`] and
320 /// [`Ipv6Addr::is_documentation()`] for more details.
327 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
329 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
331 /// IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(),
335 #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
336 #[unstable(feature = "ip", issue = "27709")]
339 pub const fn is_documentation(&self) -> bool {
341 IpAddr::V4(ip) => ip.is_documentation(),
342 IpAddr::V6(ip) => ip.is_documentation(),
346 /// Returns [`true`] if this address is in a range designated for benchmarking.
348 /// See the documentation for [`Ipv4Addr::is_benchmarking()`] and
349 /// [`Ipv6Addr::is_benchmarking()`] for more details.
356 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
358 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(198, 19, 255, 255)).is_benchmarking(), true);
359 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0)).is_benchmarking(), true);
361 #[unstable(feature = "ip", issue = "27709")]
364 pub const fn is_benchmarking(&self) -> bool {
366 IpAddr::V4(ip) => ip.is_benchmarking(),
367 IpAddr::V6(ip) => ip.is_benchmarking(),
371 /// Returns [`true`] if this address is an [`IPv4` address], and [`false`]
374 /// [`IPv4` address]: IpAddr::V4
379 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
381 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
382 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false);
384 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
385 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
388 pub const fn is_ipv4(&self) -> bool {
389 matches!(self, IpAddr::V4(_))
392 /// Returns [`true`] if this address is an [`IPv6` address], and [`false`]
395 /// [`IPv6` address]: IpAddr::V6
400 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
402 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
403 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true);
405 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
406 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
409 pub const fn is_ipv6(&self) -> bool {
410 matches!(self, IpAddr::V6(_))
413 /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped IPv6 addresses, otherwise it
414 /// return `self` as-is.
420 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
422 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).to_canonical().is_loopback(), true);
423 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).is_loopback(), false);
424 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).to_canonical().is_loopback(), true);
427 #[must_use = "this returns the result of the operation, \
428 without modifying the original"]
429 #[rustc_const_unstable(feature = "const_ip", issue = "76205")]
430 #[unstable(feature = "ip", issue = "27709")]
431 pub const fn to_canonical(&self) -> IpAddr {
433 &v4 @ IpAddr::V4(_) => v4,
434 IpAddr::V6(v6) => v6.to_canonical(),
440 /// Creates a new IPv4 address from four eight-bit octets.
442 /// The result will represent the IP address `a`.`b`.`c`.`d`.
447 /// use std::net::Ipv4Addr;
449 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
451 #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
452 #[stable(feature = "rust1", since = "1.0.0")]
455 pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
456 Ipv4Addr { octets: [a, b, c, d] }
459 /// An IPv4 address with the address pointing to localhost: `127.0.0.1`
464 /// use std::net::Ipv4Addr;
466 /// let addr = Ipv4Addr::LOCALHOST;
467 /// assert_eq!(addr, Ipv4Addr::new(127, 0, 0, 1));
469 #[stable(feature = "ip_constructors", since = "1.30.0")]
470 pub const LOCALHOST: Self = Ipv4Addr::new(127, 0, 0, 1);
472 /// An IPv4 address representing an unspecified address: `0.0.0.0`
474 /// This corresponds to the constant `INADDR_ANY` in other languages.
479 /// use std::net::Ipv4Addr;
481 /// let addr = Ipv4Addr::UNSPECIFIED;
482 /// assert_eq!(addr, Ipv4Addr::new(0, 0, 0, 0));
484 #[doc(alias = "INADDR_ANY")]
485 #[stable(feature = "ip_constructors", since = "1.30.0")]
486 pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0);
488 /// An IPv4 address representing the broadcast address: `255.255.255.255`
493 /// use std::net::Ipv4Addr;
495 /// let addr = Ipv4Addr::BROADCAST;
496 /// assert_eq!(addr, Ipv4Addr::new(255, 255, 255, 255));
498 #[stable(feature = "ip_constructors", since = "1.30.0")]
499 pub const BROADCAST: Self = Ipv4Addr::new(255, 255, 255, 255);
501 /// Returns the four eight-bit integers that make up this address.
506 /// use std::net::Ipv4Addr;
508 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
509 /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
511 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
512 #[stable(feature = "rust1", since = "1.0.0")]
515 pub const fn octets(&self) -> [u8; 4] {
519 /// Returns [`true`] for the special 'unspecified' address (`0.0.0.0`).
521 /// This property is defined in _UNIX Network Programming, Second Edition_,
522 /// W. Richard Stevens, p. 891; see also [ip7].
524 /// [ip7]: https://man7.org/linux/man-pages/man7/ip.7.html
529 /// use std::net::Ipv4Addr;
531 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
532 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
534 #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
535 #[stable(feature = "ip_shared", since = "1.12.0")]
538 pub const fn is_unspecified(&self) -> bool {
539 u32::from_be_bytes(self.octets) == 0
542 /// Returns [`true`] if this is a loopback address (`127.0.0.0/8`).
544 /// This property is defined by [IETF RFC 1122].
546 /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
551 /// use std::net::Ipv4Addr;
553 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
554 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
556 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
557 #[stable(since = "1.7.0", feature = "ip_17")]
560 pub const fn is_loopback(&self) -> bool {
561 self.octets()[0] == 127
564 /// Returns [`true`] if this is a private address.
566 /// The private address ranges are defined in [IETF RFC 1918] and include:
569 /// - `172.16.0.0/12`
570 /// - `192.168.0.0/16`
572 /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
577 /// use std::net::Ipv4Addr;
579 /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
580 /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
581 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
582 /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
583 /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
584 /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
585 /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
587 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
588 #[stable(since = "1.7.0", feature = "ip_17")]
591 pub const fn is_private(&self) -> bool {
592 match self.octets() {
594 [172, b, ..] if b >= 16 && b <= 31 => true,
595 [192, 168, ..] => true,
600 /// Returns [`true`] if the address is link-local (`169.254.0.0/16`).
602 /// This property is defined by [IETF RFC 3927].
604 /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
609 /// use std::net::Ipv4Addr;
611 /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
612 /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
613 /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
615 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
616 #[stable(since = "1.7.0", feature = "ip_17")]
619 pub const fn is_link_local(&self) -> bool {
620 matches!(self.octets(), [169, 254, ..])
623 /// Returns [`true`] if the address appears to be globally reachable
624 /// as specified by the [IANA IPv4 Special-Purpose Address Registry].
625 /// Whether or not an address is practically reachable will depend on your network configuration.
627 /// Most IPv4 addresses are globally reachable;
628 /// unless they are specifically defined as *not* globally reachable.
630 /// Non-exhaustive list of notable addresses that are not globally reachable:
632 /// - The [unspecified address] ([`is_unspecified`](Ipv4Addr::is_unspecified))
633 /// - Addresses reserved for private use ([`is_private`](Ipv4Addr::is_private))
634 /// - Addresses in the shared address space ([`is_shared`](Ipv4Addr::is_shared))
635 /// - Loopback addresses ([`is_loopback`](Ipv4Addr::is_loopback))
636 /// - Link-local addresses ([`is_link_local`](Ipv4Addr::is_link_local))
637 /// - Addresses reserved for documentation ([`is_documentation`](Ipv4Addr::is_documentation))
638 /// - Addresses reserved for benchmarking ([`is_benchmarking`](Ipv4Addr::is_benchmarking))
639 /// - Reserved addresses ([`is_reserved`](Ipv4Addr::is_reserved))
640 /// - The [broadcast address] ([`is_broadcast`](Ipv4Addr::is_broadcast))
642 /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv4 Special-Purpose Address Registry].
644 /// [IANA IPv4 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
645 /// [unspecified address]: Ipv4Addr::UNSPECIFIED
646 /// [broadcast address]: Ipv4Addr::BROADCAST
654 /// use std::net::Ipv4Addr;
656 /// // Most IPv4 addresses are globally reachable:
657 /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
659 /// // However some addresses have been assigned a special meaning
660 /// // that makes them not globally reachable. Some examples are:
662 /// // The unspecified address (`0.0.0.0`)
663 /// assert_eq!(Ipv4Addr::UNSPECIFIED.is_global(), false);
665 /// // Addresses reserved for private use (`10.0.0.0/8`, `172.16.0.0/12`, 192.168.0.0/16)
666 /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
667 /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
668 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
670 /// // Addresses in the shared address space (`100.64.0.0/10`)
671 /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
673 /// // The loopback addresses (`127.0.0.0/8`)
674 /// assert_eq!(Ipv4Addr::LOCALHOST.is_global(), false);
676 /// // Link-local addresses (`169.254.0.0/16`)
677 /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
679 /// // Addresses reserved for documentation (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`)
680 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
681 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
682 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
684 /// // Addresses reserved for benchmarking (`198.18.0.0/15`)
685 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
687 /// // Reserved addresses (`240.0.0.0/4`)
688 /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
690 /// // The broadcast address (`255.255.255.255`)
691 /// assert_eq!(Ipv4Addr::BROADCAST.is_global(), false);
693 /// // For a complete overview see the IANA IPv4 Special-Purpose Address Registry.
695 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
696 #[unstable(feature = "ip", issue = "27709")]
699 pub const fn is_global(&self) -> bool {
700 !(self.octets()[0] == 0 // "This network"
703 || self.is_loopback()
704 || self.is_link_local()
705 // addresses reserved for future protocols (`192.0.0.0/24`)
706 ||(self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0)
707 || self.is_documentation()
708 || self.is_benchmarking()
709 || self.is_reserved()
710 || self.is_broadcast())
713 /// Returns [`true`] if this address is part of the Shared Address Space defined in
714 /// [IETF RFC 6598] (`100.64.0.0/10`).
716 /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
722 /// use std::net::Ipv4Addr;
724 /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
725 /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
726 /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
728 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
729 #[unstable(feature = "ip", issue = "27709")]
732 pub const fn is_shared(&self) -> bool {
733 self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
736 /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
737 /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
738 /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
740 /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
741 /// [errata 423]: https://www.rfc-editor.org/errata/eid423
747 /// use std::net::Ipv4Addr;
749 /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
750 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
751 /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
752 /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
754 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
755 #[unstable(feature = "ip", issue = "27709")]
758 pub const fn is_benchmarking(&self) -> bool {
759 self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
762 /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
763 /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
764 /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
765 /// it is obviously not reserved for future use.
767 /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
771 /// As IANA assigns new addresses, this method will be
772 /// updated. This may result in non-reserved addresses being
773 /// treated as reserved in code that relies on an outdated version
780 /// use std::net::Ipv4Addr;
782 /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
783 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
785 /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
786 /// // The broadcast address is not considered as reserved for future use by this implementation
787 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
789 #[rustc_const_unstable(feature = "const_ipv4", issue = "76205")]
790 #[unstable(feature = "ip", issue = "27709")]
793 pub const fn is_reserved(&self) -> bool {
794 self.octets()[0] & 240 == 240 && !self.is_broadcast()
797 /// Returns [`true`] if this is a multicast address (`224.0.0.0/4`).
799 /// Multicast addresses have a most significant octet between `224` and `239`,
800 /// and is defined by [IETF RFC 5771].
802 /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
807 /// use std::net::Ipv4Addr;
809 /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
810 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
811 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
813 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
814 #[stable(since = "1.7.0", feature = "ip_17")]
817 pub const fn is_multicast(&self) -> bool {
818 self.octets()[0] >= 224 && self.octets()[0] <= 239
821 /// Returns [`true`] if this is a broadcast address (`255.255.255.255`).
823 /// A broadcast address has all octets set to `255` as defined in [IETF RFC 919].
825 /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
830 /// use std::net::Ipv4Addr;
832 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
833 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
835 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
836 #[stable(since = "1.7.0", feature = "ip_17")]
839 pub const fn is_broadcast(&self) -> bool {
840 u32::from_be_bytes(self.octets()) == u32::from_be_bytes(Self::BROADCAST.octets())
843 /// Returns [`true`] if this address is in a range designated for documentation.
845 /// This is defined in [IETF RFC 5737]:
847 /// - `192.0.2.0/24` (TEST-NET-1)
848 /// - `198.51.100.0/24` (TEST-NET-2)
849 /// - `203.0.113.0/24` (TEST-NET-3)
851 /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
856 /// use std::net::Ipv4Addr;
858 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
859 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
860 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
861 /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
863 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
864 #[stable(since = "1.7.0", feature = "ip_17")]
867 pub const fn is_documentation(&self) -> bool {
868 matches!(self.octets(), [192, 0, 2, _] | [198, 51, 100, _] | [203, 0, 113, _])
871 /// Converts this address to an [IPv4-compatible] [`IPv6` address].
873 /// `a.b.c.d` becomes `::a.b.c.d`
875 /// Note that IPv4-compatible addresses have been officially deprecated.
876 /// If you don't explicitly need an IPv4-compatible address for legacy reasons, consider using `to_ipv6_mapped` instead.
878 /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
879 /// [`IPv6` address]: Ipv6Addr
884 /// use std::net::{Ipv4Addr, Ipv6Addr};
887 /// Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
888 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x2ff)
891 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
892 #[stable(feature = "rust1", since = "1.0.0")]
893 #[must_use = "this returns the result of the operation, \
894 without modifying the original"]
896 pub const fn to_ipv6_compatible(&self) -> Ipv6Addr {
897 let [a, b, c, d] = self.octets();
898 Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] }
901 /// Converts this address to an [IPv4-mapped] [`IPv6` address].
903 /// `a.b.c.d` becomes `::ffff:a.b.c.d`
905 /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
906 /// [`IPv6` address]: Ipv6Addr
911 /// use std::net::{Ipv4Addr, Ipv6Addr};
913 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
914 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff));
916 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
917 #[stable(feature = "rust1", since = "1.0.0")]
918 #[must_use = "this returns the result of the operation, \
919 without modifying the original"]
921 pub const fn to_ipv6_mapped(&self) -> Ipv6Addr {
922 let [a, b, c, d] = self.octets();
923 Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] }
927 #[stable(feature = "ip_addr", since = "1.7.0")]
928 impl fmt::Display for IpAddr {
929 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
931 IpAddr::V4(ip) => ip.fmt(fmt),
932 IpAddr::V6(ip) => ip.fmt(fmt),
937 #[stable(feature = "ip_addr", since = "1.7.0")]
938 impl fmt::Debug for IpAddr {
939 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
940 fmt::Display::fmt(self, fmt)
944 #[stable(feature = "ip_from_ip", since = "1.16.0")]
945 impl From<Ipv4Addr> for IpAddr {
946 /// Copies this address to a new `IpAddr::V4`.
951 /// use std::net::{IpAddr, Ipv4Addr};
953 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
956 /// IpAddr::V4(addr),
957 /// IpAddr::from(addr)
961 fn from(ipv4: Ipv4Addr) -> IpAddr {
966 #[stable(feature = "ip_from_ip", since = "1.16.0")]
967 impl From<Ipv6Addr> for IpAddr {
968 /// Copies this address to a new `IpAddr::V6`.
973 /// use std::net::{IpAddr, Ipv6Addr};
975 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
978 /// IpAddr::V6(addr),
979 /// IpAddr::from(addr)
983 fn from(ipv6: Ipv6Addr) -> IpAddr {
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl fmt::Display for Ipv4Addr {
990 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
991 let octets = self.octets();
993 // If there are no alignment requirements, write the IP address directly to `f`.
994 // Otherwise, write it to a local buffer and then use `f.pad`.
995 if fmt.precision().is_none() && fmt.width().is_none() {
996 write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
998 const LONGEST_IPV4_ADDR: &str = "255.255.255.255";
1000 let mut buf = DisplayBuffer::<{ LONGEST_IPV4_ADDR.len() }>::new();
1001 // Buffer is long enough for the longest possible IPv4 address, so this should never fail.
1002 write!(buf, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
1004 fmt.pad(buf.as_str())
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 impl fmt::Debug for Ipv4Addr {
1011 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1012 fmt::Display::fmt(self, fmt)
1016 #[stable(feature = "ip_cmp", since = "1.16.0")]
1017 impl PartialEq<Ipv4Addr> for IpAddr {
1019 fn eq(&self, other: &Ipv4Addr) -> bool {
1021 IpAddr::V4(v4) => v4 == other,
1022 IpAddr::V6(_) => false,
1027 #[stable(feature = "ip_cmp", since = "1.16.0")]
1028 impl PartialEq<IpAddr> for Ipv4Addr {
1030 fn eq(&self, other: &IpAddr) -> bool {
1032 IpAddr::V4(v4) => self == v4,
1033 IpAddr::V6(_) => false,
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 impl PartialOrd for Ipv4Addr {
1041 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1042 Some(self.cmp(other))
1046 #[stable(feature = "ip_cmp", since = "1.16.0")]
1047 impl PartialOrd<Ipv4Addr> for IpAddr {
1049 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
1051 IpAddr::V4(v4) => v4.partial_cmp(other),
1052 IpAddr::V6(_) => Some(Ordering::Greater),
1057 #[stable(feature = "ip_cmp", since = "1.16.0")]
1058 impl PartialOrd<IpAddr> for Ipv4Addr {
1060 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1062 IpAddr::V4(v4) => self.partial_cmp(v4),
1063 IpAddr::V6(_) => Some(Ordering::Less),
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 impl Ord for Ipv4Addr {
1071 fn cmp(&self, other: &Ipv4Addr) -> Ordering {
1072 self.octets.cmp(&other.octets)
1076 impl IntoInner<c::in_addr> for Ipv4Addr {
1078 fn into_inner(self) -> c::in_addr {
1079 // `s_addr` is stored as BE on all machines and the array is in BE order.
1080 // So the native endian conversion method is used so that it's never swapped.
1081 c::in_addr { s_addr: u32::from_ne_bytes(self.octets) }
1084 impl FromInner<c::in_addr> for Ipv4Addr {
1085 fn from_inner(addr: c::in_addr) -> Ipv4Addr {
1086 Ipv4Addr { octets: addr.s_addr.to_ne_bytes() }
1090 #[stable(feature = "ip_u32", since = "1.1.0")]
1091 impl From<Ipv4Addr> for u32 {
1092 /// Converts an `Ipv4Addr` into a host byte order `u32`.
1097 /// use std::net::Ipv4Addr;
1099 /// let addr = Ipv4Addr::new(0x12, 0x34, 0x56, 0x78);
1100 /// assert_eq!(0x12345678, u32::from(addr));
1103 fn from(ip: Ipv4Addr) -> u32 {
1104 u32::from_be_bytes(ip.octets)
1108 #[stable(feature = "ip_u32", since = "1.1.0")]
1109 impl From<u32> for Ipv4Addr {
1110 /// Converts a host byte order `u32` into an `Ipv4Addr`.
1115 /// use std::net::Ipv4Addr;
1117 /// let addr = Ipv4Addr::from(0x12345678);
1118 /// assert_eq!(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78), addr);
1121 fn from(ip: u32) -> Ipv4Addr {
1122 Ipv4Addr { octets: ip.to_be_bytes() }
1126 #[stable(feature = "from_slice_v4", since = "1.9.0")]
1127 impl From<[u8; 4]> for Ipv4Addr {
1128 /// Creates an `Ipv4Addr` from a four element byte array.
1133 /// use std::net::Ipv4Addr;
1135 /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1136 /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1139 fn from(octets: [u8; 4]) -> Ipv4Addr {
1144 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1145 impl From<[u8; 4]> for IpAddr {
1146 /// Creates an `IpAddr::V4` from a four element byte array.
1151 /// use std::net::{IpAddr, Ipv4Addr};
1153 /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1154 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1157 fn from(octets: [u8; 4]) -> IpAddr {
1158 IpAddr::V4(Ipv4Addr::from(octets))
1163 /// Creates a new IPv6 address from eight 16-bit segments.
1165 /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1170 /// use std::net::Ipv6Addr;
1172 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1174 #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
1175 #[stable(feature = "rust1", since = "1.0.0")]
1178 pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1190 // All elements in `addr16` are big endian.
1191 // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1192 octets: unsafe { transmute::<_, [u8; 16]>(addr16) },
1196 /// An IPv6 address representing localhost: `::1`.
1201 /// use std::net::Ipv6Addr;
1203 /// let addr = Ipv6Addr::LOCALHOST;
1204 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1206 #[stable(feature = "ip_constructors", since = "1.30.0")]
1207 pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1209 /// An IPv6 address representing the unspecified address: `::`
1214 /// use std::net::Ipv6Addr;
1216 /// let addr = Ipv6Addr::UNSPECIFIED;
1217 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1219 #[stable(feature = "ip_constructors", since = "1.30.0")]
1220 pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1222 /// Returns the eight 16-bit segments that make up this address.
1227 /// use std::net::Ipv6Addr;
1229 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1230 /// [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1232 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1233 #[stable(feature = "rust1", since = "1.0.0")]
1236 pub const fn segments(&self) -> [u16; 8] {
1237 // All elements in `self.octets` must be big endian.
1238 // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1239 let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.octets) };
1240 // We want native endian u16
1253 /// Returns [`true`] for the special 'unspecified' address (`::`).
1255 /// This property is defined in [IETF RFC 4291].
1257 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1262 /// use std::net::Ipv6Addr;
1264 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1265 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1267 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1268 #[stable(since = "1.7.0", feature = "ip_17")]
1271 pub const fn is_unspecified(&self) -> bool {
1272 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1275 /// Returns [`true`] if this is the [loopback address] (`::1`),
1276 /// as defined in [IETF RFC 4291 section 2.5.3].
1278 /// Contrary to IPv4, in IPv6 there is only one loopback address.
1280 /// [loopback address]: Ipv6Addr::LOCALHOST
1281 /// [IETF RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1286 /// use std::net::Ipv6Addr;
1288 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1289 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1291 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1292 #[stable(since = "1.7.0", feature = "ip_17")]
1295 pub const fn is_loopback(&self) -> bool {
1296 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1299 /// Returns [`true`] if the address appears to be globally reachable
1300 /// as specified by the [IANA IPv6 Special-Purpose Address Registry].
1301 /// Whether or not an address is practically reachable will depend on your network configuration.
1303 /// Most IPv6 addresses are globally reachable;
1304 /// unless they are specifically defined as *not* globally reachable.
1306 /// Non-exhaustive list of notable addresses that are not globally reachable:
1307 /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified))
1308 /// - The [loopback address] ([`is_loopback`](Ipv6Addr::is_loopback))
1309 /// - IPv4-mapped addresses
1310 /// - Addresses reserved for benchmarking
1311 /// - Addresses reserved for documentation ([`is_documentation`](Ipv6Addr::is_documentation))
1312 /// - Unique local addresses ([`is_unique_local`](Ipv6Addr::is_unique_local))
1313 /// - Unicast addresses with link-local scope ([`is_unicast_link_local`](Ipv6Addr::is_unicast_link_local))
1315 /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv6 Special-Purpose Address Registry].
1317 /// Note that an address having global scope is not the same as being globally reachable,
1318 /// and there is no direct relation between the two concepts: There exist addresses with global scope
1319 /// that are not globally reachable (for example unique local addresses),
1320 /// and addresses that are globally reachable without having global scope
1321 /// (multicast addresses with non-global scope).
1323 /// [IANA IPv6 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
1324 /// [unspecified address]: Ipv6Addr::UNSPECIFIED
1325 /// [loopback address]: Ipv6Addr::LOCALHOST
1332 /// use std::net::Ipv6Addr;
1334 /// // Most IPv6 addresses are globally reachable:
1335 /// assert_eq!(Ipv6Addr::new(0x26, 0, 0x1c9, 0, 0, 0xafc8, 0x10, 0x1).is_global(), true);
1337 /// // However some addresses have been assigned a special meaning
1338 /// // that makes them not globally reachable. Some examples are:
1340 /// // The unspecified address (`::`)
1341 /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_global(), false);
1343 /// // The loopback address (`::1`)
1344 /// assert_eq!(Ipv6Addr::LOCALHOST.is_global(), false);
1346 /// // IPv4-mapped addresses (`::ffff:0:0/96`)
1347 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), false);
1349 /// // Addresses reserved for benchmarking (`2001:2::/48`)
1350 /// assert_eq!(Ipv6Addr::new(0x2001, 2, 0, 0, 0, 0, 0, 1,).is_global(), false);
1352 /// // Addresses reserved for documentation (`2001:db8::/32`)
1353 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).is_global(), false);
1355 /// // Unique local addresses (`fc00::/7`)
1356 /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1358 /// // Unicast addresses with link-local scope (`fe80::/10`)
1359 /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1361 /// // For a complete overview see the IANA IPv6 Special-Purpose Address Registry.
1363 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1364 #[unstable(feature = "ip", issue = "27709")]
1367 pub const fn is_global(&self) -> bool {
1368 !(self.is_unspecified()
1369 || self.is_loopback()
1370 // IPv4-mapped Address (`::ffff:0:0/96`)
1371 || matches!(self.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
1372 // IPv4-IPv6 Translat. (`64:ff9b:1::/48`)
1373 || matches!(self.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
1374 // Discard-Only Address Block (`100::/64`)
1375 || matches!(self.segments(), [0x100, 0, 0, 0, _, _, _, _])
1376 // IETF Protocol Assignments (`2001::/23`)
1377 || (matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
1379 // Port Control Protocol Anycast (`2001:1::1`)
1380 u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
1381 // Traversal Using Relays around NAT Anycast (`2001:1::2`)
1382 || u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
1383 // AMT (`2001:3::/32`)
1384 || matches!(self.segments(), [0x2001, 3, _, _, _, _, _, _])
1385 // AS112-v6 (`2001:4:112::/48`)
1386 || matches!(self.segments(), [0x2001, 4, 0x112, _, _, _, _, _])
1387 // ORCHIDv2 (`2001:20::/28`)
1388 || matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b >= 0x20 && b <= 0x2F)
1390 || self.is_documentation()
1391 || self.is_unique_local()
1392 || self.is_unicast_link_local())
1395 /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1397 /// This property is defined in [IETF RFC 4193].
1399 /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1406 /// use std::net::Ipv6Addr;
1408 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1409 /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1411 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1412 #[unstable(feature = "ip", issue = "27709")]
1415 pub const fn is_unique_local(&self) -> bool {
1416 (self.segments()[0] & 0xfe00) == 0xfc00
1419 /// Returns [`true`] if this is a unicast address, as defined by [IETF RFC 4291].
1420 /// Any address that is not a [multicast address] (`ff00::/8`) is unicast.
1422 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1423 /// [multicast address]: Ipv6Addr::is_multicast
1430 /// use std::net::Ipv6Addr;
1432 /// // The unspecified and loopback addresses are unicast.
1433 /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_unicast(), true);
1434 /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast(), true);
1436 /// // Any address that is not a multicast address (`ff00::/8`) is unicast.
1437 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast(), true);
1438 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_unicast(), false);
1440 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1441 #[unstable(feature = "ip", issue = "27709")]
1444 pub const fn is_unicast(&self) -> bool {
1445 !self.is_multicast()
1448 /// Returns `true` if the address is a unicast address with link-local scope,
1449 /// as defined in [RFC 4291].
1451 /// A unicast address has link-local scope if it has the prefix `fe80::/10`, as per [RFC 4291 section 2.4].
1452 /// Note that this encompasses more addresses than those defined in [RFC 4291 section 2.5.6],
1453 /// which describes "Link-Local IPv6 Unicast Addresses" as having the following stricter format:
1456 /// | 10 bits | 54 bits | 64 bits |
1457 /// +----------+-------------------------+----------------------------+
1458 /// |1111111010| 0 | interface ID |
1459 /// +----------+-------------------------+----------------------------+
1461 /// So while currently the only addresses with link-local scope an application will encounter are all in `fe80::/64`,
1462 /// this might change in the future with the publication of new standards. More addresses in `fe80::/10` could be allocated,
1463 /// and those addresses will have link-local scope.
1465 /// 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",
1466 /// this does not mean that the loopback address actually has link-local scope and this method will return `false` on it.
1468 /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
1469 /// [RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1470 /// [RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1471 /// [RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1472 /// [loopback address]: Ipv6Addr::LOCALHOST
1479 /// use std::net::Ipv6Addr;
1481 /// // The loopback address (`::1`) does not actually have link-local scope.
1482 /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast_link_local(), false);
1484 /// // Only addresses in `fe80::/10` have link-local scope.
1485 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), false);
1486 /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1488 /// // Addresses outside the stricter `fe80::/64` also have link-local scope.
1489 /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0).is_unicast_link_local(), true);
1490 /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1492 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1493 #[unstable(feature = "ip", issue = "27709")]
1496 pub const fn is_unicast_link_local(&self) -> bool {
1497 (self.segments()[0] & 0xffc0) == 0xfe80
1500 /// Returns [`true`] if this is an address reserved for documentation
1501 /// (`2001:db8::/32`).
1503 /// This property is defined in [IETF RFC 3849].
1505 /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1512 /// use std::net::Ipv6Addr;
1514 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1515 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1517 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1518 #[unstable(feature = "ip", issue = "27709")]
1521 pub const fn is_documentation(&self) -> bool {
1522 (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1525 /// Returns [`true`] if this is an address reserved for benchmarking (`2001:2::/48`).
1527 /// This property is defined in [IETF RFC 5180], where it is mistakenly specified as covering the range `2001:0200::/48`.
1528 /// This is corrected in [IETF RFC Errata 1752] to `2001:0002::/48`.
1530 /// [IETF RFC 5180]: https://tools.ietf.org/html/rfc5180
1531 /// [IETF RFC Errata 1752]: https://www.rfc-editor.org/errata_search.php?eid=1752
1536 /// use std::net::Ipv6Addr;
1538 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc613, 0x0).is_benchmarking(), false);
1539 /// assert_eq!(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0).is_benchmarking(), true);
1541 #[unstable(feature = "ip", issue = "27709")]
1544 pub const fn is_benchmarking(&self) -> bool {
1545 (self.segments()[0] == 0x2001) && (self.segments()[1] == 0x2) && (self.segments()[2] == 0)
1548 /// Returns [`true`] if the address is a globally routable unicast address.
1550 /// The following return false:
1552 /// - the loopback address
1553 /// - the link-local addresses
1554 /// - unique local addresses
1555 /// - the unspecified address
1556 /// - the address range reserved for documentation
1558 /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1561 /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1562 /// be supported in new implementations (i.e., new implementations must treat this prefix as
1563 /// Global Unicast).
1566 /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1573 /// use std::net::Ipv6Addr;
1575 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1576 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1578 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1579 #[unstable(feature = "ip", issue = "27709")]
1582 pub const fn is_unicast_global(&self) -> bool {
1584 && !self.is_loopback()
1585 && !self.is_unicast_link_local()
1586 && !self.is_unique_local()
1587 && !self.is_unspecified()
1588 && !self.is_documentation()
1589 && !self.is_benchmarking()
1592 /// Returns the address's multicast scope if the address is multicast.
1599 /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1602 /// Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1603 /// Some(Ipv6MulticastScope::Global)
1605 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1607 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1608 #[unstable(feature = "ip", issue = "27709")]
1611 pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1612 if self.is_multicast() {
1613 match self.segments()[0] & 0x000f {
1614 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1615 2 => Some(Ipv6MulticastScope::LinkLocal),
1616 3 => Some(Ipv6MulticastScope::RealmLocal),
1617 4 => Some(Ipv6MulticastScope::AdminLocal),
1618 5 => Some(Ipv6MulticastScope::SiteLocal),
1619 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1620 14 => Some(Ipv6MulticastScope::Global),
1628 /// Returns [`true`] if this is a multicast address (`ff00::/8`).
1630 /// This property is defined by [IETF RFC 4291].
1632 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1637 /// use std::net::Ipv6Addr;
1639 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1640 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1642 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1643 #[stable(since = "1.7.0", feature = "ip_17")]
1646 pub const fn is_multicast(&self) -> bool {
1647 (self.segments()[0] & 0xff00) == 0xff00
1650 /// Converts this address to an [`IPv4` address] if it's an [IPv4-mapped] address,
1651 /// as defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1653 /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1654 /// All addresses *not* starting with `::ffff` will return `None`.
1656 /// [`IPv4` address]: Ipv4Addr
1657 /// [IPv4-mapped]: Ipv6Addr
1658 /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1663 /// use std::net::{Ipv4Addr, Ipv6Addr};
1665 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1666 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1667 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1668 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1670 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1671 #[stable(feature = "ipv6_to_ipv4_mapped", since = "1.63.0")]
1672 #[must_use = "this returns the result of the operation, \
1673 without modifying the original"]
1675 pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1676 match self.octets() {
1677 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1678 Some(Ipv4Addr::new(a, b, c, d))
1684 /// Converts this address to an [`IPv4` address] if it is either
1685 /// an [IPv4-compatible] address as defined in [IETF RFC 4291 section 2.5.5.1],
1686 /// or an [IPv4-mapped] address as defined in [IETF RFC 4291 section 2.5.5.2],
1687 /// otherwise returns [`None`].
1689 /// Note that this will return an [`IPv4` address] for the IPv6 loopback address `::1`. Use
1690 /// [`Ipv6Addr::to_ipv4_mapped`] to avoid this.
1692 /// `::a.b.c.d` and `::ffff:a.b.c.d` become `a.b.c.d`. `::1` becomes `0.0.0.1`.
1693 /// All addresses *not* starting with either all zeroes or `::ffff` will return `None`.
1695 /// [`IPv4` address]: Ipv4Addr
1696 /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
1697 /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
1698 /// [IETF RFC 4291 section 2.5.5.1]: https://tools.ietf.org/html/rfc4291#section-2.5.5.1
1699 /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1704 /// use std::net::{Ipv4Addr, Ipv6Addr};
1706 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1707 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1708 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1709 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1710 /// Some(Ipv4Addr::new(0, 0, 0, 1)));
1712 #[rustc_const_stable(feature = "const_ip_50", since = "1.50.0")]
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 #[must_use = "this returns the result of the operation, \
1715 without modifying the original"]
1717 pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1718 if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1719 let [a, b] = ab.to_be_bytes();
1720 let [c, d] = cd.to_be_bytes();
1721 Some(Ipv4Addr::new(a, b, c, d))
1727 /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped addresses, otherwise it
1728 /// returns self wrapped in an `IpAddr::V6`.
1734 /// use std::net::Ipv6Addr;
1736 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).is_loopback(), false);
1737 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).to_canonical().is_loopback(), true);
1739 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1740 #[unstable(feature = "ip", issue = "27709")]
1741 #[must_use = "this returns the result of the operation, \
1742 without modifying the original"]
1744 pub const fn to_canonical(&self) -> IpAddr {
1745 if let Some(mapped) = self.to_ipv4_mapped() {
1746 return IpAddr::V4(mapped);
1751 /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1754 /// use std::net::Ipv6Addr;
1756 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1757 /// [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1759 #[rustc_const_stable(feature = "const_ip_32", since = "1.32.0")]
1760 #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1763 pub const fn octets(&self) -> [u8; 16] {
1768 /// Write an Ipv6Addr, conforming to the canonical style described by
1769 /// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 impl fmt::Display for Ipv6Addr {
1772 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1773 // If there are no alignment requirements, write the IP address directly to `f`.
1774 // Otherwise, write it to a local buffer and then use `f.pad`.
1775 if f.precision().is_none() && f.width().is_none() {
1776 let segments = self.segments();
1778 // Special case for :: and ::1; otherwise they get written with the
1780 if self.is_unspecified() {
1782 } else if self.is_loopback() {
1784 } else if let Some(ipv4) = self.to_ipv4() {
1786 // IPv4 Compatible address
1787 0 => write!(f, "::{}", ipv4),
1788 // IPv4 Mapped address
1789 0xffff => write!(f, "::ffff:{}", ipv4),
1790 _ => unreachable!(),
1793 #[derive(Copy, Clone, Default)]
1799 // Find the inner 0 span
1801 let mut longest = Span::default();
1802 let mut current = Span::default();
1804 for (i, &segment) in segments.iter().enumerate() {
1806 if current.len == 0 {
1812 if current.len > longest.len {
1816 current = Span::default();
1823 /// Write a colon-separated part of the address
1825 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1826 if let Some((first, tail)) = chunk.split_first() {
1827 write!(f, "{:x}", first)?;
1828 for segment in tail {
1830 write!(f, "{:x}", segment)?;
1837 fmt_subslice(f, &segments[..zeroes.start])?;
1839 fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1841 fmt_subslice(f, &segments)
1845 const LONGEST_IPV6_ADDR: &str = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
1847 let mut buf = DisplayBuffer::<{ LONGEST_IPV6_ADDR.len() }>::new();
1848 // Buffer is long enough for the longest possible IPv6 address, so this should never fail.
1849 write!(buf, "{}", self).unwrap();
1856 #[stable(feature = "rust1", since = "1.0.0")]
1857 impl fmt::Debug for Ipv6Addr {
1858 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1859 fmt::Display::fmt(self, fmt)
1863 #[stable(feature = "ip_cmp", since = "1.16.0")]
1864 impl PartialEq<IpAddr> for Ipv6Addr {
1866 fn eq(&self, other: &IpAddr) -> bool {
1868 IpAddr::V4(_) => false,
1869 IpAddr::V6(v6) => self == v6,
1874 #[stable(feature = "ip_cmp", since = "1.16.0")]
1875 impl PartialEq<Ipv6Addr> for IpAddr {
1877 fn eq(&self, other: &Ipv6Addr) -> bool {
1879 IpAddr::V4(_) => false,
1880 IpAddr::V6(v6) => v6 == other,
1885 #[stable(feature = "rust1", since = "1.0.0")]
1886 impl PartialOrd for Ipv6Addr {
1888 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1889 Some(self.cmp(other))
1893 #[stable(feature = "ip_cmp", since = "1.16.0")]
1894 impl PartialOrd<Ipv6Addr> for IpAddr {
1896 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1898 IpAddr::V4(_) => Some(Ordering::Less),
1899 IpAddr::V6(v6) => v6.partial_cmp(other),
1904 #[stable(feature = "ip_cmp", since = "1.16.0")]
1905 impl PartialOrd<IpAddr> for Ipv6Addr {
1907 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1909 IpAddr::V4(_) => Some(Ordering::Greater),
1910 IpAddr::V6(v6) => self.partial_cmp(v6),
1915 #[stable(feature = "rust1", since = "1.0.0")]
1916 impl Ord for Ipv6Addr {
1918 fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1919 self.segments().cmp(&other.segments())
1923 impl IntoInner<c::in6_addr> for Ipv6Addr {
1924 fn into_inner(self) -> c::in6_addr {
1925 c::in6_addr { s6_addr: self.octets }
1928 impl FromInner<c::in6_addr> for Ipv6Addr {
1930 fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1931 Ipv6Addr { octets: addr.s6_addr }
1935 #[stable(feature = "i128", since = "1.26.0")]
1936 impl From<Ipv6Addr> for u128 {
1937 /// Convert an `Ipv6Addr` into a host byte order `u128`.
1942 /// use std::net::Ipv6Addr;
1944 /// let addr = Ipv6Addr::new(
1945 /// 0x1020, 0x3040, 0x5060, 0x7080,
1946 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1948 /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1951 fn from(ip: Ipv6Addr) -> u128 {
1952 u128::from_be_bytes(ip.octets)
1955 #[stable(feature = "i128", since = "1.26.0")]
1956 impl From<u128> for Ipv6Addr {
1957 /// Convert a host byte order `u128` into an `Ipv6Addr`.
1962 /// use std::net::Ipv6Addr;
1964 /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1967 /// 0x1020, 0x3040, 0x5060, 0x7080,
1968 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1973 fn from(ip: u128) -> Ipv6Addr {
1974 Ipv6Addr::from(ip.to_be_bytes())
1978 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1979 impl From<[u8; 16]> for Ipv6Addr {
1980 /// Creates an `Ipv6Addr` from a sixteen element byte array.
1985 /// use std::net::Ipv6Addr;
1987 /// let addr = Ipv6Addr::from([
1988 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1989 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
2002 fn from(octets: [u8; 16]) -> Ipv6Addr {
2007 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
2008 impl From<[u16; 8]> for Ipv6Addr {
2009 /// Creates an `Ipv6Addr` from an eight element 16-bit array.
2014 /// use std::net::Ipv6Addr;
2016 /// let addr = Ipv6Addr::from([
2017 /// 525u16, 524u16, 523u16, 522u16,
2018 /// 521u16, 520u16, 519u16, 518u16,
2031 fn from(segments: [u16; 8]) -> Ipv6Addr {
2032 let [a, b, c, d, e, f, g, h] = segments;
2033 Ipv6Addr::new(a, b, c, d, e, f, g, h)
2037 #[stable(feature = "ip_from_slice", since = "1.17.0")]
2038 impl From<[u8; 16]> for IpAddr {
2039 /// Creates an `IpAddr::V6` from a sixteen element byte array.
2044 /// use std::net::{IpAddr, Ipv6Addr};
2046 /// let addr = IpAddr::from([
2047 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
2048 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
2051 /// IpAddr::V6(Ipv6Addr::new(
2061 fn from(octets: [u8; 16]) -> IpAddr {
2062 IpAddr::V6(Ipv6Addr::from(octets))
2066 #[stable(feature = "ip_from_slice", since = "1.17.0")]
2067 impl From<[u16; 8]> for IpAddr {
2068 /// Creates an `IpAddr::V6` from an eight element 16-bit array.
2073 /// use std::net::{IpAddr, Ipv6Addr};
2075 /// let addr = IpAddr::from([
2076 /// 525u16, 524u16, 523u16, 522u16,
2077 /// 521u16, 520u16, 519u16, 518u16,
2080 /// IpAddr::V6(Ipv6Addr::new(
2090 fn from(segments: [u16; 8]) -> IpAddr {
2091 IpAddr::V6(Ipv6Addr::from(segments))