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.
143 /// [`true`]: ../../std/primitive.bool.html
148 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
150 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
151 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
153 #[stable(feature = "ip_shared", since = "1.12.0")]
154 pub 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.
166 /// [`true`]: ../../std/primitive.bool.html
171 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
173 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
174 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
176 #[stable(feature = "ip_shared", since = "1.12.0")]
177 pub 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.
189 /// [`true`]: ../../std/primitive.bool.html
196 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
198 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true);
199 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true);
201 pub 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.
213 /// [`true`]: ../../std/primitive.bool.html
218 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
220 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
221 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
223 #[stable(feature = "ip_shared", since = "1.12.0")]
224 pub 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.
236 /// [`true`]: ../../std/primitive.bool.html
243 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
245 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
247 /// IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(),
251 pub 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 /// [`true`]: ../../std/primitive.bool.html
262 /// [`false`]: ../../std/primitive.bool.html
263 /// [`IPv4` address]: IpAddr::V4
268 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
270 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
271 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false);
273 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
274 pub fn is_ipv4(&self) -> bool {
275 matches!(self, IpAddr::V4(_))
278 /// Returns [`true`] if this address is an [`IPv6` address], and [`false`]
281 /// [`true`]: ../../std/primitive.bool.html
282 /// [`false`]: ../../std/primitive.bool.html
283 /// [`IPv6` address]: IpAddr::V6
288 /// use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
290 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
291 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true);
293 #[stable(feature = "ipaddr_checker", since = "1.16.0")]
294 pub 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 #[stable(feature = "rust1", since = "1.0.0")]
312 #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
313 pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
314 // `s_addr` is stored as BE on all machine and the array is in BE order.
315 // So the native endian conversion method is used so that it's never swapped.
316 Ipv4Addr { inner: c::in_addr { s_addr: u32::from_ne_bytes([a, b, c, d]) } }
319 /// An IPv4 address with the address pointing to localhost: 127.0.0.1.
324 /// use std::net::Ipv4Addr;
326 /// let addr = Ipv4Addr::LOCALHOST;
327 /// assert_eq!(addr, Ipv4Addr::new(127, 0, 0, 1));
329 #[stable(feature = "ip_constructors", since = "1.30.0")]
330 pub const LOCALHOST: Self = Ipv4Addr::new(127, 0, 0, 1);
332 /// An IPv4 address representing an unspecified address: 0.0.0.0
337 /// use std::net::Ipv4Addr;
339 /// let addr = Ipv4Addr::UNSPECIFIED;
340 /// assert_eq!(addr, Ipv4Addr::new(0, 0, 0, 0));
342 #[stable(feature = "ip_constructors", since = "1.30.0")]
343 pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0);
345 /// An IPv4 address representing the broadcast address: 255.255.255.255
350 /// use std::net::Ipv4Addr;
352 /// let addr = Ipv4Addr::BROADCAST;
353 /// assert_eq!(addr, Ipv4Addr::new(255, 255, 255, 255));
355 #[stable(feature = "ip_constructors", since = "1.30.0")]
356 pub const BROADCAST: Self = Ipv4Addr::new(255, 255, 255, 255);
358 /// Returns the four eight-bit integers that make up this address.
363 /// use std::net::Ipv4Addr;
365 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
366 /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
368 #[stable(feature = "rust1", since = "1.0.0")]
369 pub fn octets(&self) -> [u8; 4] {
370 // This returns the order we want because s_addr is stored in big-endian.
371 self.inner.s_addr.to_ne_bytes()
374 /// Returns [`true`] for the special 'unspecified' address (0.0.0.0).
376 /// This property is defined in _UNIX Network Programming, Second Edition_,
377 /// W. Richard Stevens, p. 891; see also [ip7].
379 /// [`true`]: ../../std/primitive.bool.html
380 /// [ip7]: http://man7.org/linux/man-pages/man7/ip.7.html
385 /// use std::net::Ipv4Addr;
387 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
388 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
390 #[stable(feature = "ip_shared", since = "1.12.0")]
391 #[rustc_const_stable(feature = "const_ipv4", since = "1.32.0")]
392 pub const fn is_unspecified(&self) -> bool {
393 self.inner.s_addr == 0
396 /// Returns [`true`] if this is a loopback address (127.0.0.0/8).
398 /// This property is defined by [IETF RFC 1122].
400 /// [`true`]: ../../std/primitive.bool.html
401 /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
406 /// use std::net::Ipv4Addr;
408 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
409 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
411 #[stable(since = "1.7.0", feature = "ip_17")]
412 pub fn is_loopback(&self) -> bool {
413 self.octets()[0] == 127
416 /// Returns [`true`] if this is a private address.
418 /// The private address ranges are defined in [IETF RFC 1918] and include:
424 /// [`true`]: ../../std/primitive.bool.html
425 /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
430 /// use std::net::Ipv4Addr;
432 /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
433 /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
434 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
435 /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
436 /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
437 /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
438 /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
440 #[stable(since = "1.7.0", feature = "ip_17")]
441 pub fn is_private(&self) -> bool {
442 match self.octets() {
444 [172, b, ..] if b >= 16 && b <= 31 => true,
445 [192, 168, ..] => true,
450 /// Returns [`true`] if the address is link-local (169.254.0.0/16).
452 /// This property is defined by [IETF RFC 3927].
454 /// [`true`]: ../../std/primitive.bool.html
455 /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
460 /// use std::net::Ipv4Addr;
462 /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
463 /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
464 /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
466 #[stable(since = "1.7.0", feature = "ip_17")]
467 pub fn is_link_local(&self) -> bool {
468 match self.octets() {
469 [169, 254, ..] => true,
474 /// Returns [`true`] if the address appears to be globally routable.
475 /// See [iana-ipv4-special-registry][ipv4-sr].
477 /// The following return [`false`]:
479 /// - private addresses (see [`Ipv4Addr::is_private()`])
480 /// - the loopback address (see [`Ipv4Addr::is_loopback()`])
481 /// - the link-local address (see [`Ipv4Addr::is_link_local()`])
482 /// - the broadcast address (see [`Ipv4Addr::is_broadcast()`])
483 /// - addresses used for documentation (see [`Ipv4Addr::is_documentation()`])
484 /// - the unspecified address (see [`Ipv4Addr::is_unspecified()`]), and the whole
486 /// - addresses reserved for future protocols (see
487 /// [`Ipv4Addr::is_ietf_protocol_assignment()`], except
488 /// `192.0.0.9/32` and `192.0.0.10/32` which are globally routable
489 /// - addresses reserved for future use (see [`Ipv4Addr::is_reserved()`]
490 /// - addresses reserved for networking devices benchmarking (see
491 /// [`Ipv4Addr::is_benchmarking()`])
493 /// [`true`]: ../../std/primitive.bool.html
494 /// [`false`]: ../../std/primitive.bool.html
495 /// [ipv4-sr]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
502 /// use std::net::Ipv4Addr;
504 /// // private addresses are not global
505 /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
506 /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
507 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
509 /// // the 0.0.0.0/8 block is not global
510 /// assert_eq!(Ipv4Addr::new(0, 1, 2, 3).is_global(), false);
511 /// // in particular, the unspecified address is not global
512 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_global(), false);
514 /// // the loopback address is not global
515 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_global(), false);
517 /// // link local addresses are not global
518 /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
520 /// // the broadcast address is not global
521 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_global(), false);
523 /// // the address space designated for documentation is not global
524 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
525 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
526 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
528 /// // shared addresses are not global
529 /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
531 /// // addresses reserved for protocol assignment are not global
532 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_global(), false);
533 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_global(), false);
535 /// // addresses reserved for future use are not global
536 /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
538 /// // addresses reserved for network devices benchmarking are not global
539 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
541 /// // All the other addresses are global
542 /// assert_eq!(Ipv4Addr::new(1, 1, 1, 1).is_global(), true);
543 /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
545 pub fn is_global(&self) -> bool {
546 // check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two
547 // globally routable addresses in the 192.0.0.0/24 range.
548 if u32::from(*self) == 0xc0000009 || u32::from(*self) == 0xc000000a {
552 && !self.is_loopback()
553 && !self.is_link_local()
554 && !self.is_broadcast()
555 && !self.is_documentation()
557 && !self.is_ietf_protocol_assignment()
558 && !self.is_reserved()
559 && !self.is_benchmarking()
560 // Make sure the address is not in 0.0.0.0/8
561 && self.octets()[0] != 0
564 /// Returns [`true`] if this address is part of the Shared Address Space defined in
565 /// [IETF RFC 6598] (`100.64.0.0/10`).
567 /// [`true`]: ../../std/primitive.bool.html
568 /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
574 /// use std::net::Ipv4Addr;
576 /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
577 /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
578 /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
580 pub fn is_shared(&self) -> bool {
581 self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
584 /// Returns [`true`] if this address is part of `192.0.0.0/24`, which is reserved to
585 /// IANA for IETF protocol assignments, as documented in [IETF RFC 6890].
587 /// Note that parts of this block are in use:
589 /// - `192.0.0.8/32` is the "IPv4 dummy address" (see [IETF RFC 7600])
590 /// - `192.0.0.9/32` is the "Port Control Protocol Anycast" (see [IETF RFC 7723])
591 /// - `192.0.0.10/32` is used for NAT traversal (see [IETF RFC 8155])
593 /// [`true`]: ../../std/primitive.bool.html
594 /// [IETF RFC 6890]: https://tools.ietf.org/html/rfc6890
595 /// [IETF RFC 7600]: https://tools.ietf.org/html/rfc7600
596 /// [IETF RFC 7723]: https://tools.ietf.org/html/rfc7723
597 /// [IETF RFC 8155]: https://tools.ietf.org/html/rfc8155
603 /// use std::net::Ipv4Addr;
605 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 0).is_ietf_protocol_assignment(), true);
606 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 8).is_ietf_protocol_assignment(), true);
607 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 9).is_ietf_protocol_assignment(), true);
608 /// assert_eq!(Ipv4Addr::new(192, 0, 0, 255).is_ietf_protocol_assignment(), true);
609 /// assert_eq!(Ipv4Addr::new(192, 0, 1, 0).is_ietf_protocol_assignment(), false);
610 /// assert_eq!(Ipv4Addr::new(191, 255, 255, 255).is_ietf_protocol_assignment(), false);
612 pub fn is_ietf_protocol_assignment(&self) -> bool {
613 self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0
616 /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
617 /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
618 /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
620 /// [`true`]: ../../std/primitive.bool.html
621 /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
622 /// [errata 423]: https://www.rfc-editor.org/errata/eid423
628 /// use std::net::Ipv4Addr;
630 /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
631 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
632 /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
633 /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
635 pub fn is_benchmarking(&self) -> bool {
636 self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
639 /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
640 /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
641 /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
642 /// it is obviously not reserved for future use.
644 /// [`true`]: ../../std/primitive.bool.html
645 /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
649 /// As IANA assigns new addresses, this method will be
650 /// updated. This may result in non-reserved addresses being
651 /// treated as reserved in code that relies on an outdated version
658 /// use std::net::Ipv4Addr;
660 /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
661 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
663 /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
664 /// // The broadcast address is not considered as reserved for future use by this implementation
665 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
667 pub fn is_reserved(&self) -> bool {
668 self.octets()[0] & 240 == 240 && !self.is_broadcast()
671 /// Returns [`true`] if this is a multicast address (224.0.0.0/4).
673 /// Multicast addresses have a most significant octet between 224 and 239,
674 /// and is defined by [IETF RFC 5771].
676 /// [`true`]: ../../std/primitive.bool.html
677 /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
682 /// use std::net::Ipv4Addr;
684 /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
685 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
686 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
688 #[stable(since = "1.7.0", feature = "ip_17")]
689 pub fn is_multicast(&self) -> bool {
690 self.octets()[0] >= 224 && self.octets()[0] <= 239
693 /// Returns [`true`] if this is a broadcast address (255.255.255.255).
695 /// A broadcast address has all octets set to 255 as defined in [IETF RFC 919].
697 /// [`true`]: ../../std/primitive.bool.html
698 /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
703 /// use std::net::Ipv4Addr;
705 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
706 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
708 #[stable(since = "1.7.0", feature = "ip_17")]
709 pub fn is_broadcast(&self) -> bool {
710 self == &Self::BROADCAST
713 /// Returns [`true`] if this address is in a range designated for documentation.
715 /// This is defined in [IETF RFC 5737]:
717 /// - 192.0.2.0/24 (TEST-NET-1)
718 /// - 198.51.100.0/24 (TEST-NET-2)
719 /// - 203.0.113.0/24 (TEST-NET-3)
721 /// [`true`]: ../../std/primitive.bool.html
722 /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
727 /// use std::net::Ipv4Addr;
729 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
730 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
731 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
732 /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
734 #[stable(since = "1.7.0", feature = "ip_17")]
735 pub fn is_documentation(&self) -> bool {
736 match self.octets() {
737 [192, 0, 2, _] => true,
738 [198, 51, 100, _] => true,
739 [203, 0, 113, _] => true,
744 /// Converts this address to an IPv4-compatible [`IPv6` address].
746 /// a.b.c.d becomes ::a.b.c.d
748 /// [`IPv6` address]: Ipv6Addr
753 /// use std::net::{Ipv4Addr, Ipv6Addr};
756 /// Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
757 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 767)
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn to_ipv6_compatible(&self) -> Ipv6Addr {
762 let [a, b, c, d] = self.octets();
763 Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d])
766 /// Converts this address to an IPv4-mapped [`IPv6` address].
768 /// a.b.c.d becomes ::ffff:a.b.c.d
770 /// [`IPv6` address]: Ipv6Addr
775 /// use std::net::{Ipv4Addr, Ipv6Addr};
777 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
778 /// Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 49152, 767));
780 #[stable(feature = "rust1", since = "1.0.0")]
781 pub fn to_ipv6_mapped(&self) -> Ipv6Addr {
782 let [a, b, c, d] = self.octets();
783 Ipv6Addr::from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d])
787 #[stable(feature = "ip_addr", since = "1.7.0")]
788 impl fmt::Display for IpAddr {
789 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
791 IpAddr::V4(ip) => ip.fmt(fmt),
792 IpAddr::V6(ip) => ip.fmt(fmt),
797 #[stable(feature = "ip_addr", since = "1.7.0")]
798 impl fmt::Debug for IpAddr {
799 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
800 fmt::Display::fmt(self, fmt)
804 #[stable(feature = "ip_from_ip", since = "1.16.0")]
805 impl From<Ipv4Addr> for IpAddr {
806 /// Copies this address to a new `IpAddr::V4`.
811 /// use std::net::{IpAddr, Ipv4Addr};
813 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
816 /// IpAddr::V4(addr),
817 /// IpAddr::from(addr)
820 fn from(ipv4: Ipv4Addr) -> IpAddr {
825 #[stable(feature = "ip_from_ip", since = "1.16.0")]
826 impl From<Ipv6Addr> for IpAddr {
827 /// Copies this address to a new `IpAddr::V6`.
832 /// use std::net::{IpAddr, Ipv6Addr};
834 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
837 /// IpAddr::V6(addr),
838 /// IpAddr::from(addr)
841 fn from(ipv6: Ipv6Addr) -> IpAddr {
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl fmt::Display for Ipv4Addr {
848 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
849 let octets = self.octets();
850 // Fast Path: if there's no alignment stuff, write directly to the buffer
851 if fmt.precision().is_none() && fmt.width().is_none() {
852 write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
854 const IPV4_BUF_LEN: usize = 15; // Long enough for the longest possible IPv4 address
855 let mut buf = [0u8; IPV4_BUF_LEN];
856 let mut buf_slice = &mut buf[..];
858 // Note: The call to write should never fail, hence the unwrap
859 write!(buf_slice, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
860 let len = IPV4_BUF_LEN - buf_slice.len();
862 // This unsafe is OK because we know what is being written to the buffer
863 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl fmt::Debug for Ipv4Addr {
871 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
872 fmt::Display::fmt(self, fmt)
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl Clone for Ipv4Addr {
878 fn clone(&self) -> Ipv4Addr {
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl PartialEq for Ipv4Addr {
885 fn eq(&self, other: &Ipv4Addr) -> bool {
886 self.inner.s_addr == other.inner.s_addr
890 #[stable(feature = "ip_cmp", since = "1.16.0")]
891 impl PartialEq<Ipv4Addr> for IpAddr {
892 fn eq(&self, other: &Ipv4Addr) -> bool {
894 IpAddr::V4(v4) => v4 == other,
895 IpAddr::V6(_) => false,
900 #[stable(feature = "ip_cmp", since = "1.16.0")]
901 impl PartialEq<IpAddr> for Ipv4Addr {
902 fn eq(&self, other: &IpAddr) -> bool {
904 IpAddr::V4(v4) => self == v4,
905 IpAddr::V6(_) => false,
910 #[stable(feature = "rust1", since = "1.0.0")]
911 impl Eq for Ipv4Addr {}
913 #[stable(feature = "rust1", since = "1.0.0")]
914 impl hash::Hash for Ipv4Addr {
915 fn hash<H: hash::Hasher>(&self, s: &mut H) {
917 // * hash in big endian order
918 // * in netbsd, `in_addr` has `repr(packed)`, we need to
919 // copy `s_addr` to avoid unsafe borrowing
920 { self.inner.s_addr }.hash(s)
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl PartialOrd for Ipv4Addr {
926 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
927 Some(self.cmp(other))
931 #[stable(feature = "ip_cmp", since = "1.16.0")]
932 impl PartialOrd<Ipv4Addr> for IpAddr {
933 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
935 IpAddr::V4(v4) => v4.partial_cmp(other),
936 IpAddr::V6(_) => Some(Ordering::Greater),
941 #[stable(feature = "ip_cmp", since = "1.16.0")]
942 impl PartialOrd<IpAddr> for Ipv4Addr {
943 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
945 IpAddr::V4(v4) => self.partial_cmp(v4),
946 IpAddr::V6(_) => Some(Ordering::Less),
951 #[stable(feature = "rust1", since = "1.0.0")]
952 impl Ord for Ipv4Addr {
953 fn cmp(&self, other: &Ipv4Addr) -> Ordering {
954 // Compare as native endian
955 u32::from_be(self.inner.s_addr).cmp(&u32::from_be(other.inner.s_addr))
959 impl IntoInner<c::in_addr> for Ipv4Addr {
960 fn into_inner(self) -> c::in_addr {
965 #[stable(feature = "ip_u32", since = "1.1.0")]
966 impl From<Ipv4Addr> for u32 {
967 /// Converts an `Ipv4Addr` into a host byte order `u32`.
972 /// use std::net::Ipv4Addr;
974 /// let addr = Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe);
975 /// assert_eq!(0xcafebabe, u32::from(addr));
977 fn from(ip: Ipv4Addr) -> u32 {
978 let ip = ip.octets();
979 u32::from_be_bytes(ip)
983 #[stable(feature = "ip_u32", since = "1.1.0")]
984 impl From<u32> for Ipv4Addr {
985 /// Converts a host byte order `u32` into an `Ipv4Addr`.
990 /// use std::net::Ipv4Addr;
992 /// let addr = Ipv4Addr::from(0xcafebabe);
993 /// assert_eq!(Ipv4Addr::new(0xca, 0xfe, 0xba, 0xbe), addr);
995 fn from(ip: u32) -> Ipv4Addr {
996 Ipv4Addr::from(ip.to_be_bytes())
1000 #[stable(feature = "from_slice_v4", since = "1.9.0")]
1001 impl From<[u8; 4]> for Ipv4Addr {
1002 /// Creates an `Ipv4Addr` from a four element byte array.
1007 /// use std::net::Ipv4Addr;
1009 /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1010 /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1012 fn from(octets: [u8; 4]) -> Ipv4Addr {
1013 Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])
1017 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1018 impl From<[u8; 4]> for IpAddr {
1019 /// Creates an `IpAddr::V4` from a four element byte array.
1024 /// use std::net::{IpAddr, Ipv4Addr};
1026 /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1027 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1029 fn from(octets: [u8; 4]) -> IpAddr {
1030 IpAddr::V4(Ipv4Addr::from(octets))
1035 /// Creates a new IPv6 address from eight 16-bit segments.
1037 /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1042 /// use std::net::Ipv6Addr;
1044 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1048 #[allow_internal_unstable(const_fn_transmute)]
1049 pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1061 inner: c::in6_addr {
1062 // All elements in `addr16` are big endian.
1063 // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1064 s6_addr: unsafe { transmute::<_, [u8; 16]>(addr16) },
1069 /// An IPv6 address representing localhost: `::1`.
1074 /// use std::net::Ipv6Addr;
1076 /// let addr = Ipv6Addr::LOCALHOST;
1077 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1079 #[stable(feature = "ip_constructors", since = "1.30.0")]
1080 pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1082 /// An IPv6 address representing the unspecified address: `::`
1087 /// use std::net::Ipv6Addr;
1089 /// let addr = Ipv6Addr::UNSPECIFIED;
1090 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1092 #[stable(feature = "ip_constructors", since = "1.30.0")]
1093 pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1095 /// Returns the eight 16-bit segments that make up this address.
1100 /// use std::net::Ipv6Addr;
1102 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1103 /// [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1105 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 pub const fn segments(&self) -> [u16; 8] {
1108 // All elements in `s6_addr` must be big endian.
1109 // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1110 let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.inner.s6_addr) };
1111 // We want native endian u16
1124 /// Returns [`true`] for the special 'unspecified' address (::).
1126 /// This property is defined in [IETF RFC 4291].
1128 /// [`true`]: ../../std/primitive.bool.html
1129 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1134 /// use std::net::Ipv6Addr;
1136 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1137 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1139 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1140 #[stable(since = "1.7.0", feature = "ip_17")]
1141 pub const fn is_unspecified(&self) -> bool {
1142 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1145 /// Returns [`true`] if this is a loopback address (::1).
1147 /// This property is defined in [IETF RFC 4291].
1149 /// [`true`]: ../../std/primitive.bool.html
1150 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1155 /// use std::net::Ipv6Addr;
1157 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1158 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1160 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1161 #[stable(since = "1.7.0", feature = "ip_17")]
1162 pub const fn is_loopback(&self) -> bool {
1163 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1166 /// Returns [`true`] if the address appears to be globally routable.
1168 /// The following return [`false`]:
1170 /// - the loopback address
1171 /// - link-local and unique local unicast addresses
1172 /// - interface-, link-, realm-, admin- and site-local multicast addresses
1174 /// [`true`]: ../../std/primitive.bool.html
1175 /// [`false`]: ../../std/primitive.bool.html
1182 /// use std::net::Ipv6Addr;
1184 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), true);
1185 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_global(), false);
1186 /// assert_eq!(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1).is_global(), true);
1188 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1189 pub const fn is_global(&self) -> bool {
1190 match self.multicast_scope() {
1191 Some(Ipv6MulticastScope::Global) => true,
1192 None => self.is_unicast_global(),
1197 /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1199 /// This property is defined in [IETF RFC 4193].
1201 /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1203 /// [`true`]: ../../std/primitive.bool.html
1210 /// use std::net::Ipv6Addr;
1212 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1213 /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1215 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1216 pub const fn is_unique_local(&self) -> bool {
1217 (self.segments()[0] & 0xfe00) == 0xfc00
1220 /// Returns [`true`] if the address is a unicast link-local address (`fe80::/64`).
1222 /// A common mis-conception is to think that "unicast link-local addresses start with
1223 /// `fe80::`", but the [IETF RFC 4291] actually defines a stricter format for these addresses:
1227 /// | bits | 54 bits | 64 bits |
1228 /// +----------+-------------------------+----------------------------+
1229 /// |1111111010| 0 | interface ID |
1230 /// +----------+-------------------------+----------------------------+
1233 /// This method validates the format defined in the RFC and won't recognize the following
1234 /// addresses such as `fe80:0:0:1::` or `fe81::` as unicast link-local addresses for example.
1235 /// If you need a less strict validation use [`Ipv6Addr::is_unicast_link_local()`] instead.
1237 /// [`true`]: ../../std/primitive.bool.html
1244 /// use std::net::Ipv6Addr;
1246 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0);
1247 /// assert!(ip.is_unicast_link_local_strict());
1249 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff);
1250 /// assert!(ip.is_unicast_link_local_strict());
1252 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0);
1253 /// assert!(!ip.is_unicast_link_local_strict());
1254 /// assert!(ip.is_unicast_link_local());
1256 /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0);
1257 /// assert!(!ip.is_unicast_link_local_strict());
1258 /// assert!(ip.is_unicast_link_local());
1263 /// - [IETF RFC 4291 section 2.5.6]
1264 /// - [RFC 4291 errata 4406] (which has been rejected but provides useful
1266 /// - [`Ipv6Addr::is_unicast_link_local()`]
1268 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1269 /// [IETF RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1270 /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406
1271 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1272 pub const fn is_unicast_link_local_strict(&self) -> bool {
1273 (self.segments()[0] & 0xffff) == 0xfe80
1274 && (self.segments()[1] & 0xffff) == 0
1275 && (self.segments()[2] & 0xffff) == 0
1276 && (self.segments()[3] & 0xffff) == 0
1279 /// Returns [`true`] if the address is a unicast link-local address (`fe80::/10`).
1281 /// This method returns [`true`] for addresses in the range reserved by [RFC 4291 section 2.4],
1282 /// i.e. addresses with the following format:
1286 /// | bits | 54 bits | 64 bits |
1287 /// +----------+-------------------------+----------------------------+
1288 /// |1111111010| arbitratry value | interface ID |
1289 /// +----------+-------------------------+----------------------------+
1292 /// As a result, this method consider addresses such as `fe80:0:0:1::` or `fe81::` to be
1293 /// unicast link-local addresses, whereas [`Ipv6Addr::is_unicast_link_local_strict()`] does not.
1294 /// If you need a strict validation fully compliant with the RFC, use
1295 /// [`Ipv6Addr::is_unicast_link_local_strict()`] instead.
1297 /// [`true`]: ../../std/primitive.bool.html
1304 /// use std::net::Ipv6Addr;
1306 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0);
1307 /// assert!(ip.is_unicast_link_local());
1309 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff);
1310 /// assert!(ip.is_unicast_link_local());
1312 /// let ip = Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0);
1313 /// assert!(ip.is_unicast_link_local());
1314 /// assert!(!ip.is_unicast_link_local_strict());
1316 /// let ip = Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0);
1317 /// assert!(ip.is_unicast_link_local());
1318 /// assert!(!ip.is_unicast_link_local_strict());
1323 /// - [IETF RFC 4291 section 2.4]
1324 /// - [RFC 4291 errata 4406] (which has been rejected but provides useful
1327 /// [IETF RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1328 /// [RFC 4291 errata 4406]: https://www.rfc-editor.org/errata/eid4406
1329 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1330 pub const fn is_unicast_link_local(&self) -> bool {
1331 (self.segments()[0] & 0xffc0) == 0xfe80
1334 /// Returns [`true`] if this is a deprecated unicast site-local address (fec0::/10). The
1335 /// unicast site-local address format is defined in [RFC 4291 section 2.5.7] as:
1339 /// | bits | 54 bits | 64 bits |
1340 /// +----------+-------------------------+----------------------------+
1341 /// |1111111011| subnet ID | interface ID |
1342 /// +----------+-------------------------+----------------------------+
1345 /// [`true`]: ../../std/primitive.bool.html
1346 /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1353 /// use std::net::Ipv6Addr;
1356 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_site_local(),
1359 /// assert_eq!(Ipv6Addr::new(0xfec2, 0, 0, 0, 0, 0, 0, 0).is_unicast_site_local(), true);
1364 /// As per [RFC 3879], the whole `FEC0::/10` prefix is
1365 /// deprecated. New software must not support site-local
1368 /// [RFC 3879]: https://tools.ietf.org/html/rfc3879
1369 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1370 pub const fn is_unicast_site_local(&self) -> bool {
1371 (self.segments()[0] & 0xffc0) == 0xfec0
1374 /// Returns [`true`] if this is an address reserved for documentation
1375 /// (2001:db8::/32).
1377 /// This property is defined in [IETF RFC 3849].
1379 /// [`true`]: ../../std/primitive.bool.html
1380 /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1387 /// use std::net::Ipv6Addr;
1389 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1390 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1392 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1393 pub const fn is_documentation(&self) -> bool {
1394 (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1397 /// Returns [`true`] if the address is a globally routable unicast address.
1399 /// The following return false:
1401 /// - the loopback address
1402 /// - the link-local addresses
1403 /// - unique local addresses
1404 /// - the unspecified address
1405 /// - the address range reserved for documentation
1407 /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1410 /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1411 /// be supported in new implementations (i.e., new implementations must treat this prefix as
1412 /// Global Unicast).
1415 /// [`true`]: ../../std/primitive.bool.html
1416 /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1423 /// use std::net::Ipv6Addr;
1425 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1426 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1428 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1429 pub const fn is_unicast_global(&self) -> bool {
1430 !self.is_multicast()
1431 && !self.is_loopback()
1432 && !self.is_unicast_link_local()
1433 && !self.is_unique_local()
1434 && !self.is_unspecified()
1435 && !self.is_documentation()
1438 /// Returns the address's multicast scope if the address is multicast.
1445 /// use std::net::{Ipv6Addr, Ipv6MulticastScope};
1448 /// Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1449 /// Some(Ipv6MulticastScope::Global)
1451 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1453 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1454 pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1455 if self.is_multicast() {
1456 match self.segments()[0] & 0x000f {
1457 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1458 2 => Some(Ipv6MulticastScope::LinkLocal),
1459 3 => Some(Ipv6MulticastScope::RealmLocal),
1460 4 => Some(Ipv6MulticastScope::AdminLocal),
1461 5 => Some(Ipv6MulticastScope::SiteLocal),
1462 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1463 14 => Some(Ipv6MulticastScope::Global),
1471 /// Returns [`true`] if this is a multicast address (ff00::/8).
1473 /// This property is defined by [IETF RFC 4291].
1475 /// [`true`]: ../../std/primitive.bool.html
1476 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1481 /// use std::net::Ipv6Addr;
1483 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1484 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1486 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1487 #[stable(since = "1.7.0", feature = "ip_17")]
1488 pub const fn is_multicast(&self) -> bool {
1489 (self.segments()[0] & 0xff00) == 0xff00
1492 /// Converts this address to an [`IPv4` address] if it's an "IPv4-mapped IPv6 address"
1493 /// defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1495 /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1496 /// All addresses *not* starting with `::ffff` will return `None`.
1498 /// [`IPv4` address]: Ipv4Addr
1499 /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1506 /// use std::net::{Ipv4Addr, Ipv6Addr};
1508 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1509 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1510 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1511 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1513 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1514 pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1515 match self.octets() {
1516 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1517 Some(Ipv4Addr::new(a, b, c, d))
1523 /// Converts this address to an [`IPv4` address]. Returns [`None`] if this address is
1524 /// neither IPv4-compatible or IPv4-mapped.
1526 /// ::a.b.c.d and ::ffff:a.b.c.d become a.b.c.d
1528 /// [`IPv4` address]: Ipv4Addr
1533 /// use std::net::{Ipv4Addr, Ipv6Addr};
1535 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1536 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1537 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1538 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1539 /// Some(Ipv4Addr::new(0, 0, 0, 1)));
1541 #[rustc_const_unstable(feature = "const_ipv6", issue = "76205")]
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1544 if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1545 let [a, b] = ab.to_be_bytes();
1546 let [c, d] = cd.to_be_bytes();
1547 Some(Ipv4Addr::new(a, b, c, d))
1553 /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1556 /// use std::net::Ipv6Addr;
1558 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1559 /// [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1561 #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
1562 #[rustc_const_stable(feature = "const_ipv6", since = "1.32.0")]
1563 pub const fn octets(&self) -> [u8; 16] {
1568 /// Write an Ipv6Addr, conforming to the canonical style described by
1569 /// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 impl fmt::Display for Ipv6Addr {
1572 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1573 // If there are no alignment requirements, write out the IP address to
1574 // f. Otherwise, write it to a local buffer, then use f.pad.
1575 if f.precision().is_none() && f.width().is_none() {
1576 let segments = self.segments();
1578 // Special case for :: and ::1; otherwise they get written with the
1580 if self.is_unspecified() {
1582 } else if self.is_loopback() {
1584 } else if let Some(ipv4) = self.to_ipv4() {
1586 // IPv4 Compatible address
1587 0 => write!(f, "::{}", ipv4),
1588 // IPv4 Mapped address
1589 0xffff => write!(f, "::ffff:{}", ipv4),
1590 _ => unreachable!(),
1593 #[derive(Copy, Clone, Default)]
1599 // Find the inner 0 span
1601 let mut longest = Span::default();
1602 let mut current = Span::default();
1604 for (i, &segment) in segments.iter().enumerate() {
1606 if current.len == 0 {
1612 if current.len > longest.len {
1616 current = Span::default();
1623 /// Write a colon-separated part of the address
1625 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1626 if let Some(first) = chunk.first() {
1627 fmt::LowerHex::fmt(first, f)?;
1628 for segment in &chunk[1..] {
1630 fmt::LowerHex::fmt(segment, f)?;
1637 fmt_subslice(f, &segments[..zeroes.start])?;
1639 fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1641 fmt_subslice(f, &segments)
1645 // Slow path: write the address to a local buffer, the use f.pad.
1646 // Defined recursively by using the fast path to write to the
1649 // This is the largest possible size of an IPv6 address
1650 const IPV6_BUF_LEN: usize = (4 * 8) + 7;
1651 let mut buf = [0u8; IPV6_BUF_LEN];
1652 let mut buf_slice = &mut buf[..];
1654 // Note: This call to write should never fail, so unwrap is okay.
1655 write!(buf_slice, "{}", self).unwrap();
1656 let len = IPV6_BUF_LEN - buf_slice.len();
1658 // This is safe because we know exactly what can be in this buffer
1659 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 impl fmt::Debug for Ipv6Addr {
1667 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1668 fmt::Display::fmt(self, fmt)
1672 #[stable(feature = "rust1", since = "1.0.0")]
1673 impl Clone for Ipv6Addr {
1674 fn clone(&self) -> Ipv6Addr {
1679 #[stable(feature = "rust1", since = "1.0.0")]
1680 impl PartialEq for Ipv6Addr {
1681 fn eq(&self, other: &Ipv6Addr) -> bool {
1682 self.inner.s6_addr == other.inner.s6_addr
1686 #[stable(feature = "ip_cmp", since = "1.16.0")]
1687 impl PartialEq<IpAddr> for Ipv6Addr {
1688 fn eq(&self, other: &IpAddr) -> bool {
1690 IpAddr::V4(_) => false,
1691 IpAddr::V6(v6) => self == v6,
1696 #[stable(feature = "ip_cmp", since = "1.16.0")]
1697 impl PartialEq<Ipv6Addr> for IpAddr {
1698 fn eq(&self, other: &Ipv6Addr) -> bool {
1700 IpAddr::V4(_) => false,
1701 IpAddr::V6(v6) => v6 == other,
1706 #[stable(feature = "rust1", since = "1.0.0")]
1707 impl Eq for Ipv6Addr {}
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 impl hash::Hash for Ipv6Addr {
1711 fn hash<H: hash::Hasher>(&self, s: &mut H) {
1712 self.inner.s6_addr.hash(s)
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 impl PartialOrd for Ipv6Addr {
1718 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1719 Some(self.cmp(other))
1723 #[stable(feature = "ip_cmp", since = "1.16.0")]
1724 impl PartialOrd<Ipv6Addr> for IpAddr {
1725 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1727 IpAddr::V4(_) => Some(Ordering::Less),
1728 IpAddr::V6(v6) => v6.partial_cmp(other),
1733 #[stable(feature = "ip_cmp", since = "1.16.0")]
1734 impl PartialOrd<IpAddr> for Ipv6Addr {
1735 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1737 IpAddr::V4(_) => Some(Ordering::Greater),
1738 IpAddr::V6(v6) => self.partial_cmp(v6),
1743 #[stable(feature = "rust1", since = "1.0.0")]
1744 impl Ord for Ipv6Addr {
1745 fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1746 self.segments().cmp(&other.segments())
1750 impl AsInner<c::in6_addr> for Ipv6Addr {
1751 fn as_inner(&self) -> &c::in6_addr {
1755 impl FromInner<c::in6_addr> for Ipv6Addr {
1756 fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
1757 Ipv6Addr { inner: addr }
1761 #[stable(feature = "i128", since = "1.26.0")]
1762 impl From<Ipv6Addr> for u128 {
1763 /// Convert an `Ipv6Addr` into a host byte order `u128`.
1768 /// use std::net::Ipv6Addr;
1770 /// let addr = Ipv6Addr::new(
1771 /// 0x1020, 0x3040, 0x5060, 0x7080,
1772 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1774 /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1776 fn from(ip: Ipv6Addr) -> u128 {
1777 let ip = ip.octets();
1778 u128::from_be_bytes(ip)
1781 #[stable(feature = "i128", since = "1.26.0")]
1782 impl From<u128> for Ipv6Addr {
1783 /// Convert a host byte order `u128` into an `Ipv6Addr`.
1788 /// use std::net::Ipv6Addr;
1790 /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1793 /// 0x1020, 0x3040, 0x5060, 0x7080,
1794 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1798 fn from(ip: u128) -> Ipv6Addr {
1799 Ipv6Addr::from(ip.to_be_bytes())
1803 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
1804 impl From<[u8; 16]> for Ipv6Addr {
1805 /// Creates an `Ipv6Addr` from a sixteen element byte array.
1810 /// use std::net::Ipv6Addr;
1812 /// let addr = Ipv6Addr::from([
1813 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1814 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1826 fn from(octets: [u8; 16]) -> Ipv6Addr {
1827 let inner = c::in6_addr { s6_addr: octets };
1828 Ipv6Addr::from_inner(inner)
1832 #[stable(feature = "ipv6_from_segments", since = "1.16.0")]
1833 impl From<[u16; 8]> for Ipv6Addr {
1834 /// Creates an `Ipv6Addr` from an eight element 16-bit array.
1839 /// use std::net::Ipv6Addr;
1841 /// let addr = Ipv6Addr::from([
1842 /// 525u16, 524u16, 523u16, 522u16,
1843 /// 521u16, 520u16, 519u16, 518u16,
1855 fn from(segments: [u16; 8]) -> Ipv6Addr {
1856 let [a, b, c, d, e, f, g, h] = segments;
1857 Ipv6Addr::new(a, b, c, d, e, f, g, h)
1861 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1862 impl From<[u8; 16]> for IpAddr {
1863 /// Creates an `IpAddr::V6` from a sixteen element byte array.
1868 /// use std::net::{IpAddr, Ipv6Addr};
1870 /// let addr = IpAddr::from([
1871 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1872 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1875 /// IpAddr::V6(Ipv6Addr::new(
1884 fn from(octets: [u8; 16]) -> IpAddr {
1885 IpAddr::V6(Ipv6Addr::from(octets))
1889 #[stable(feature = "ip_from_slice", since = "1.17.0")]
1890 impl From<[u16; 8]> for IpAddr {
1891 /// Creates an `IpAddr::V6` from an eight element 16-bit array.
1896 /// use std::net::{IpAddr, Ipv6Addr};
1898 /// let addr = IpAddr::from([
1899 /// 525u16, 524u16, 523u16, 522u16,
1900 /// 521u16, 520u16, 519u16, 518u16,
1903 /// IpAddr::V6(Ipv6Addr::new(
1912 fn from(segments: [u16; 8]) -> IpAddr {
1913 IpAddr::V6(Ipv6Addr::from(segments))