core_net/ip_addr.rs
1use core::cmp::Ordering;
2use core::fmt::{self, Write};
3use core::mem::transmute;
4
5/// An IP address, either IPv4 or IPv6.
6///
7/// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their
8/// respective documentation for more details.
9///
10/// # Examples
11///
12/// ```
13/// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
14///
15/// let localhost_v4 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
16/// let localhost_v6 = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
17///
18/// assert_eq!("127.0.0.1".parse(), Ok(localhost_v4));
19/// assert_eq!("::1".parse(), Ok(localhost_v6));
20///
21/// assert_eq!(localhost_v4.is_ipv6(), false);
22/// assert_eq!(localhost_v4.is_ipv4(), true);
23/// ```
24#[derive(Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
25pub enum IpAddr {
26 /// An IPv4 address.
27 V4(Ipv4Addr),
28 /// An IPv6 address.
29 V6(Ipv6Addr),
30}
31
32/// An IPv4 address.
33///
34/// IPv4 addresses are defined as 32-bit integers in [IETF RFC 791].
35/// They are usually represented as four octets.
36///
37/// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
38///
39/// [IETF RFC 791]: https://tools.ietf.org/html/rfc791
40///
41/// # Textual representation
42///
43/// `Ipv4Addr` provides a [`FromStr`] implementation. The four octets are in decimal
44/// notation, divided by `.` (this is called "dot-decimal notation").
45/// Notably, octal numbers (which are indicated with a leading `0`) and hexadecimal numbers (which
46/// are indicated with a leading `0x`) are not allowed per [IETF RFC 6943].
47///
48/// [IETF RFC 6943]: https://tools.ietf.org/html/rfc6943#section-3.1.1
49/// [`FromStr`]: crate::str::FromStr
50///
51/// # Examples
52///
53/// ```
54/// use core_net::Ipv4Addr;
55///
56/// let localhost = Ipv4Addr::new(127, 0, 0, 1);
57/// assert_eq!("127.0.0.1".parse(), Ok(localhost));
58/// assert_eq!(localhost.is_loopback(), true);
59/// assert!("012.004.002.000".parse::<Ipv4Addr>().is_err()); // all octets are in octal
60/// assert!("0000000.0.0.0".parse::<Ipv4Addr>().is_err()); // first octet is a zero in octal
61/// assert!("0xcb.0x0.0x71.0x00".parse::<Ipv4Addr>().is_err()); // all octets are in hex
62/// ```
63#[derive(Copy, Clone, PartialEq, Eq, Hash)]
64pub struct Ipv4Addr {
65 octets: [u8; 4],
66}
67
68/// An IPv6 address.
69///
70/// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291].
71/// They are usually represented as eight 16-bit segments.
72///
73/// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
74///
75/// # Embedding IPv4 Addresses
76///
77/// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses.
78///
79/// To assist in the transition from IPv4 to IPv6 two types of IPv6 addresses that embed an IPv4 address were defined:
80/// IPv4-compatible and IPv4-mapped addresses. Of these IPv4-compatible addresses have been officially deprecated.
81///
82/// Both types of addresses are not assigned any special meaning by this implementation,
83/// other than what the relevant standards prescribe. This means that an address like `::ffff:127.0.0.1`,
84/// while representing an IPv4 loopback address, is not itself an IPv6 loopback address; only `::1` is.
85/// To handle these so called "IPv4-in-IPv6" addresses, they have to first be converted to their canonical IPv4 address.
86///
87/// ### IPv4-Compatible IPv6 Addresses
88///
89/// IPv4-compatible IPv6 addresses are defined in [IETF RFC 4291 Section 2.5.5.1], and have been officially deprecated.
90/// The RFC describes the format of an "IPv4-Compatible IPv6 address" as follows:
91///
92/// ```text
93/// | 80 bits | 16 | 32 bits |
94/// +--------------------------------------+--------------------------+
95/// |0000..............................0000|0000| IPv4 address |
96/// +--------------------------------------+----+---------------------+
97/// ```
98/// So `::a.b.c.d` would be an IPv4-compatible IPv6 address representing the IPv4 address `a.b.c.d`.
99///
100/// To convert from an IPv4 address to an IPv4-compatible IPv6 address, use [`Ipv4Addr::to_ipv6_compatible`].
101/// Use [`Ipv6Addr::to_ipv4`] to convert an IPv4-compatible IPv6 address to the canonical IPv4 address.
102///
103/// [IETF RFC 4291 Section 2.5.5.1]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.1
104///
105/// ### IPv4-Mapped IPv6 Addresses
106///
107/// IPv4-mapped IPv6 addresses are defined in [IETF RFC 4291 Section 2.5.5.2].
108/// The RFC describes the format of an "IPv4-Mapped IPv6 address" as follows:
109///
110/// ```text
111/// | 80 bits | 16 | 32 bits |
112/// +--------------------------------------+--------------------------+
113/// |0000..............................0000|FFFF| IPv4 address |
114/// +--------------------------------------+----+---------------------+
115/// ```
116/// So `::ffff:a.b.c.d` would be an IPv4-mapped IPv6 address representing the IPv4 address `a.b.c.d`.
117///
118/// To convert from an IPv4 address to an IPv4-mapped IPv6 address, use [`Ipv4Addr::to_ipv6_mapped`].
119/// Use [`Ipv6Addr::to_ipv4`] to convert an IPv4-mapped IPv6 address to the canonical IPv4 address.
120/// Note that this will also convert the IPv6 loopback address `::1` to `0.0.0.1`. Use
121/// [`Ipv6Addr::to_ipv4_mapped`] to avoid this.
122///
123/// [IETF RFC 4291 Section 2.5.5.2]: https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2
124///
125/// # Textual representation
126///
127/// `Ipv6Addr` provides a [`FromStr`] implementation. There are many ways to represent
128/// an IPv6 address in text, but in general, each segments is written in hexadecimal
129/// notation, and segments are separated by `:`. For more information, see
130/// [IETF RFC 5952].
131///
132/// [`FromStr`]: crate::str::FromStr
133/// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952
134///
135/// # Examples
136///
137/// ```
138/// use core_net::Ipv6Addr;
139///
140/// let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
141/// assert_eq!("::1".parse(), Ok(localhost));
142/// assert_eq!(localhost.is_loopback(), true);
143/// ```
144#[derive(Copy, Clone, PartialEq, Eq, Hash)]
145pub struct Ipv6Addr {
146 octets: [u8; 16],
147}
148
149/// Scope of an [IPv6 multicast address] as defined in [IETF RFC 7346 section 2].
150///
151/// # Stability Guarantees
152///
153/// Not all possible values for a multicast scope have been assigned.
154/// Future RFCs may introduce new scopes, which will be added as variants to this enum;
155/// because of this the enum is marked as `#[non_exhaustive]`.
156///
157/// # Examples
158/// ```
159/// use core_net::Ipv6Addr;
160/// use core_net::Ipv6MulticastScope::*;
161///
162/// // An IPv6 multicast address with global scope (`ff0e::`).
163/// let address = Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0);
164///
165/// // Will print "Global scope".
166/// match address.multicast_scope() {
167/// Some(InterfaceLocal) => println!("Interface-Local scope"),
168/// Some(LinkLocal) => println!("Link-Local scope"),
169/// Some(RealmLocal) => println!("Realm-Local scope"),
170/// Some(AdminLocal) => println!("Admin-Local scope"),
171/// Some(SiteLocal) => println!("Site-Local scope"),
172/// Some(OrganizationLocal) => println!("Organization-Local scope"),
173/// Some(Global) => println!("Global scope"),
174/// Some(_) => println!("Unknown scope"),
175/// None => println!("Not a multicast address!")
176/// }
177///
178/// ```
179///
180/// [IPv6 multicast address]: Ipv6Addr
181/// [IETF RFC 7346 section 2]: https://tools.ietf.org/html/rfc7346#section-2
182#[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
183#[non_exhaustive]
184pub enum Ipv6MulticastScope {
185 /// Interface-Local scope.
186 InterfaceLocal,
187 /// Link-Local scope.
188 LinkLocal,
189 /// Realm-Local scope.
190 RealmLocal,
191 /// Admin-Local scope.
192 AdminLocal,
193 /// Site-Local scope.
194 SiteLocal,
195 /// Organization-Local scope.
196 OrganizationLocal,
197 /// Global scope.
198 Global,
199}
200
201impl IpAddr {
202 /// Returns [`true`] for the special 'unspecified' address.
203 ///
204 /// See the documentation for [`Ipv4Addr::is_unspecified()`] and
205 /// [`Ipv6Addr::is_unspecified()`] for more details.
206 ///
207 /// # Examples
208 ///
209 /// ```
210 /// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
211 ///
212 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)).is_unspecified(), true);
213 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)).is_unspecified(), true);
214 /// ```
215 #[must_use]
216 #[inline]
217 pub const fn is_unspecified(&self) -> bool {
218 match self {
219 IpAddr::V4(ip) => ip.is_unspecified(),
220 IpAddr::V6(ip) => ip.is_unspecified(),
221 }
222 }
223
224 /// Returns [`true`] if this is a loopback address.
225 ///
226 /// See the documentation for [`Ipv4Addr::is_loopback()`] and
227 /// [`Ipv6Addr::is_loopback()`] for more details.
228 ///
229 /// # Examples
230 ///
231 /// ```
232 /// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
233 ///
234 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true);
235 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true);
236 /// ```
237 #[must_use]
238 #[inline]
239 pub const fn is_loopback(&self) -> bool {
240 match self {
241 IpAddr::V4(ip) => ip.is_loopback(),
242 IpAddr::V6(ip) => ip.is_loopback(),
243 }
244 }
245
246 /// Returns [`true`] if the address appears to be globally routable.
247 ///
248 /// See the documentation for [`Ipv4Addr::is_global()`] and
249 /// [`Ipv6Addr::is_global()`] for more details.
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
255 ///
256 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true);
257 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true);
258 /// ```
259 #[must_use]
260 #[inline]
261 pub const fn is_global(&self) -> bool {
262 match self {
263 IpAddr::V4(ip) => ip.is_global(),
264 IpAddr::V6(ip) => ip.is_global(),
265 }
266 }
267
268 /// Returns [`true`] if this is a multicast address.
269 ///
270 /// See the documentation for [`Ipv4Addr::is_multicast()`] and
271 /// [`Ipv6Addr::is_multicast()`] for more details.
272 ///
273 /// # Examples
274 ///
275 /// ```
276 /// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
277 ///
278 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true);
279 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true);
280 /// ```
281 #[must_use]
282 #[inline]
283 pub const fn is_multicast(&self) -> bool {
284 match self {
285 IpAddr::V4(ip) => ip.is_multicast(),
286 IpAddr::V6(ip) => ip.is_multicast(),
287 }
288 }
289
290 /// Returns [`true`] if this address is in a range designated for documentation.
291 ///
292 /// See the documentation for [`Ipv4Addr::is_documentation()`] and
293 /// [`Ipv6Addr::is_documentation()`] for more details.
294 ///
295 /// # Examples
296 ///
297 /// ```
298 /// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
299 ///
300 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true);
301 /// assert_eq!(
302 /// IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(),
303 /// true
304 /// );
305 /// ```
306 #[must_use]
307 #[inline]
308 pub const fn is_documentation(&self) -> bool {
309 match self {
310 IpAddr::V4(ip) => ip.is_documentation(),
311 IpAddr::V6(ip) => ip.is_documentation(),
312 }
313 }
314
315 /// Returns [`true`] if this address is in a range designated for benchmarking.
316 ///
317 /// See the documentation for [`Ipv4Addr::is_benchmarking()`] and
318 /// [`Ipv6Addr::is_benchmarking()`] for more details.
319 ///
320 /// # Examples
321 ///
322 /// ```
323 /// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
324 ///
325 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(198, 19, 255, 255)).is_benchmarking(), true);
326 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0)).is_benchmarking(), true);
327 /// ```
328 #[must_use]
329 #[inline]
330 pub const fn is_benchmarking(&self) -> bool {
331 match self {
332 IpAddr::V4(ip) => ip.is_benchmarking(),
333 IpAddr::V6(ip) => ip.is_benchmarking(),
334 }
335 }
336
337 /// Returns [`true`] if this address is an [`IPv4` address], and [`false`]
338 /// otherwise.
339 ///
340 /// [`IPv4` address]: IpAddr::V4
341 ///
342 /// # Examples
343 ///
344 /// ```
345 /// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
346 ///
347 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true);
348 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false);
349 /// ```
350 #[must_use]
351 #[inline]
352 pub const fn is_ipv4(&self) -> bool {
353 matches!(self, IpAddr::V4(_))
354 }
355
356 /// Returns [`true`] if this address is an [`IPv6` address], and [`false`]
357 /// otherwise.
358 ///
359 /// [`IPv6` address]: IpAddr::V6
360 ///
361 /// # Examples
362 ///
363 /// ```
364 /// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
365 ///
366 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv6(), false);
367 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv6(), true);
368 /// ```
369 #[must_use]
370 #[inline]
371 pub const fn is_ipv6(&self) -> bool {
372 matches!(self, IpAddr::V6(_))
373 }
374
375 /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped IPv6 addresses, otherwise it
376 /// return `self` as-is.
377 ///
378 /// # Examples
379 ///
380 /// ```
381 /// use core_net::{IpAddr, Ipv4Addr, Ipv6Addr};
382 ///
383 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).to_canonical().is_loopback(), true);
384 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).is_loopback(), false);
385 /// assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1)).to_canonical().is_loopback(), true);
386 /// ```
387 #[inline]
388 #[must_use = "this returns the result of the operation, \
389 without modifying the original"]
390 pub const fn to_canonical(&self) -> IpAddr {
391 match self {
392 &v4 @ IpAddr::V4(_) => v4,
393 IpAddr::V6(v6) => v6.to_canonical(),
394 }
395 }
396}
397
398impl Ipv4Addr {
399 /// Creates a new IPv4 address from four eight-bit octets.
400 ///
401 /// The result will represent the IP address `a`.`b`.`c`.`d`.
402 ///
403 /// # Examples
404 ///
405 /// ```
406 /// use core_net::Ipv4Addr;
407 ///
408 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
409 /// ```
410 #[must_use]
411 #[inline]
412 pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
413 Ipv4Addr { octets: [a, b, c, d] }
414 }
415
416 /// An IPv4 address with the address pointing to localhost: `127.0.0.1`
417 ///
418 /// # Examples
419 ///
420 /// ```
421 /// use core_net::Ipv4Addr;
422 ///
423 /// let addr = Ipv4Addr::LOCALHOST;
424 /// assert_eq!(addr, Ipv4Addr::new(127, 0, 0, 1));
425 /// ```
426 pub const LOCALHOST: Self = Ipv4Addr::new(127, 0, 0, 1);
427
428 /// An IPv4 address representing an unspecified address: `0.0.0.0`
429 ///
430 /// This corresponds to the constant `INADDR_ANY` in other languages.
431 ///
432 /// # Examples
433 ///
434 /// ```
435 /// use core_net::Ipv4Addr;
436 ///
437 /// let addr = Ipv4Addr::UNSPECIFIED;
438 /// assert_eq!(addr, Ipv4Addr::new(0, 0, 0, 0));
439 /// ```
440 #[doc(alias = "INADDR_ANY")]
441 pub const UNSPECIFIED: Self = Ipv4Addr::new(0, 0, 0, 0);
442
443 /// An IPv4 address representing the broadcast address: `255.255.255.255`
444 ///
445 /// # Examples
446 ///
447 /// ```
448 /// use core_net::Ipv4Addr;
449 ///
450 /// let addr = Ipv4Addr::BROADCAST;
451 /// assert_eq!(addr, Ipv4Addr::new(255, 255, 255, 255));
452 /// ```
453 pub const BROADCAST: Self = Ipv4Addr::new(255, 255, 255, 255);
454
455 /// Returns the four eight-bit integers that make up this address.
456 ///
457 /// # Examples
458 ///
459 /// ```
460 /// use core_net::Ipv4Addr;
461 ///
462 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
463 /// assert_eq!(addr.octets(), [127, 0, 0, 1]);
464 /// ```
465 #[must_use]
466 #[inline]
467 pub const fn octets(&self) -> [u8; 4] {
468 self.octets
469 }
470
471 /// Returns [`true`] for the special 'unspecified' address (`0.0.0.0`).
472 ///
473 /// This property is defined in _UNIX Network Programming, Second Edition_,
474 /// W. Richard Stevens, p. 891; see also [ip7].
475 ///
476 /// [ip7]: https://man7.org/linux/man-pages/man7/ip.7.html
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use core_net::Ipv4Addr;
482 ///
483 /// assert_eq!(Ipv4Addr::new(0, 0, 0, 0).is_unspecified(), true);
484 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_unspecified(), false);
485 /// ```
486 #[must_use]
487 #[inline]
488 pub const fn is_unspecified(&self) -> bool {
489 u32::from_be_bytes(self.octets) == 0
490 }
491
492 /// Returns [`true`] if this is a loopback address (`127.0.0.0/8`).
493 ///
494 /// This property is defined by [IETF RFC 1122].
495 ///
496 /// [IETF RFC 1122]: https://tools.ietf.org/html/rfc1122
497 ///
498 /// # Examples
499 ///
500 /// ```
501 /// use core_net::Ipv4Addr;
502 ///
503 /// assert_eq!(Ipv4Addr::new(127, 0, 0, 1).is_loopback(), true);
504 /// assert_eq!(Ipv4Addr::new(45, 22, 13, 197).is_loopback(), false);
505 /// ```
506 #[must_use]
507 #[inline]
508 pub const fn is_loopback(&self) -> bool {
509 self.octets()[0] == 127
510 }
511
512 /// Returns [`true`] if this is a private address.
513 ///
514 /// The private address ranges are defined in [IETF RFC 1918] and include:
515 ///
516 /// - `10.0.0.0/8`
517 /// - `172.16.0.0/12`
518 /// - `192.168.0.0/16`
519 ///
520 /// [IETF RFC 1918]: https://tools.ietf.org/html/rfc1918
521 ///
522 /// # Examples
523 ///
524 /// ```
525 /// use core_net::Ipv4Addr;
526 ///
527 /// assert_eq!(Ipv4Addr::new(10, 0, 0, 1).is_private(), true);
528 /// assert_eq!(Ipv4Addr::new(10, 10, 10, 10).is_private(), true);
529 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 10).is_private(), true);
530 /// assert_eq!(Ipv4Addr::new(172, 29, 45, 14).is_private(), true);
531 /// assert_eq!(Ipv4Addr::new(172, 32, 0, 2).is_private(), false);
532 /// assert_eq!(Ipv4Addr::new(192, 168, 0, 2).is_private(), true);
533 /// assert_eq!(Ipv4Addr::new(192, 169, 0, 2).is_private(), false);
534 /// ```
535 #[must_use]
536 #[inline]
537 pub const fn is_private(&self) -> bool {
538 match self.octets() {
539 [10, ..] => true,
540 [172, b, ..] if b >= 16 && b <= 31 => true,
541 [192, 168, ..] => true,
542 _ => false,
543 }
544 }
545
546 /// Returns [`true`] if the address is link-local (`169.254.0.0/16`).
547 ///
548 /// This property is defined by [IETF RFC 3927].
549 ///
550 /// [IETF RFC 3927]: https://tools.ietf.org/html/rfc3927
551 ///
552 /// # Examples
553 ///
554 /// ```
555 /// use core_net::Ipv4Addr;
556 ///
557 /// assert_eq!(Ipv4Addr::new(169, 254, 0, 0).is_link_local(), true);
558 /// assert_eq!(Ipv4Addr::new(169, 254, 10, 65).is_link_local(), true);
559 /// assert_eq!(Ipv4Addr::new(16, 89, 10, 65).is_link_local(), false);
560 /// ```
561 #[must_use]
562 #[inline]
563 pub const fn is_link_local(&self) -> bool {
564 matches!(self.octets(), [169, 254, ..])
565 }
566
567 /// Returns [`true`] if the address appears to be globally reachable
568 /// as specified by the [IANA IPv4 Special-Purpose Address Registry].
569 /// Whether or not an address is practically reachable will depend on your network configuration.
570 ///
571 /// Most IPv4 addresses are globally reachable;
572 /// unless they are specifically defined as *not* globally reachable.
573 ///
574 /// Non-exhaustive list of notable addresses that are not globally reachable:
575 ///
576 /// - The [unspecified address] ([`is_unspecified`](Ipv4Addr::is_unspecified))
577 /// - Addresses reserved for private use ([`is_private`](Ipv4Addr::is_private))
578 /// - Addresses in the shared address space ([`is_shared`](Ipv4Addr::is_shared))
579 /// - Loopback addresses ([`is_loopback`](Ipv4Addr::is_loopback))
580 /// - Link-local addresses ([`is_link_local`](Ipv4Addr::is_link_local))
581 /// - Addresses reserved for documentation ([`is_documentation`](Ipv4Addr::is_documentation))
582 /// - Addresses reserved for benchmarking ([`is_benchmarking`](Ipv4Addr::is_benchmarking))
583 /// - Reserved addresses ([`is_reserved`](Ipv4Addr::is_reserved))
584 /// - The [broadcast address] ([`is_broadcast`](Ipv4Addr::is_broadcast))
585 ///
586 /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv4 Special-Purpose Address Registry].
587 ///
588 /// [IANA IPv4 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
589 /// [unspecified address]: Ipv4Addr::UNSPECIFIED
590 /// [broadcast address]: Ipv4Addr::BROADCAST
591
592 ///
593 /// # Examples
594 ///
595 /// ```
596 /// use core_net::Ipv4Addr;
597 ///
598 /// // Most IPv4 addresses are globally reachable:
599 /// assert_eq!(Ipv4Addr::new(80, 9, 12, 3).is_global(), true);
600 ///
601 /// // However some addresses have been assigned a special meaning
602 /// // that makes them not globally reachable. Some examples are:
603 ///
604 /// // The unspecified address (`0.0.0.0`)
605 /// assert_eq!(Ipv4Addr::UNSPECIFIED.is_global(), false);
606 ///
607 /// // Addresses reserved for private use (`10.0.0.0/8`, `172.16.0.0/12`, 192.168.0.0/16)
608 /// assert_eq!(Ipv4Addr::new(10, 254, 0, 0).is_global(), false);
609 /// assert_eq!(Ipv4Addr::new(192, 168, 10, 65).is_global(), false);
610 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_global(), false);
611 ///
612 /// // Addresses in the shared address space (`100.64.0.0/10`)
613 /// assert_eq!(Ipv4Addr::new(100, 100, 0, 0).is_global(), false);
614 ///
615 /// // The loopback addresses (`127.0.0.0/8`)
616 /// assert_eq!(Ipv4Addr::LOCALHOST.is_global(), false);
617 ///
618 /// // Link-local addresses (`169.254.0.0/16`)
619 /// assert_eq!(Ipv4Addr::new(169, 254, 45, 1).is_global(), false);
620 ///
621 /// // Addresses reserved for documentation (`192.0.2.0/24`, `198.51.100.0/24`, `203.0.113.0/24`)
622 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_global(), false);
623 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_global(), false);
624 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_global(), false);
625 ///
626 /// // Addresses reserved for benchmarking (`198.18.0.0/15`)
627 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_global(), false);
628 ///
629 /// // Reserved addresses (`240.0.0.0/4`)
630 /// assert_eq!(Ipv4Addr::new(250, 10, 20, 30).is_global(), false);
631 ///
632 /// // The broadcast address (`255.255.255.255`)
633 /// assert_eq!(Ipv4Addr::BROADCAST.is_global(), false);
634 ///
635 /// // For a complete overview see the IANA IPv4 Special-Purpose Address Registry.
636 /// ```
637 #[must_use]
638 #[inline]
639 pub const fn is_global(&self) -> bool {
640 !(self.octets()[0] == 0 // "This network"
641 || self.is_private()
642 || self.is_shared()
643 || self.is_loopback()
644 || self.is_link_local()
645 // addresses reserved for future protocols (`192.0.0.0/24`)
646 ||(self.octets()[0] == 192 && self.octets()[1] == 0 && self.octets()[2] == 0)
647 || self.is_documentation()
648 || self.is_benchmarking()
649 || self.is_reserved()
650 || self.is_broadcast())
651 }
652
653 /// Returns [`true`] if this address is part of the Shared Address Space defined in
654 /// [IETF RFC 6598] (`100.64.0.0/10`).
655 ///
656 /// [IETF RFC 6598]: https://tools.ietf.org/html/rfc6598
657 ///
658 /// # Examples
659 ///
660 /// ```
661 /// use core_net::Ipv4Addr;
662 ///
663 /// assert_eq!(Ipv4Addr::new(100, 64, 0, 0).is_shared(), true);
664 /// assert_eq!(Ipv4Addr::new(100, 127, 255, 255).is_shared(), true);
665 /// assert_eq!(Ipv4Addr::new(100, 128, 0, 0).is_shared(), false);
666 /// ```
667 #[must_use]
668 #[inline]
669 pub const fn is_shared(&self) -> bool {
670 self.octets()[0] == 100 && (self.octets()[1] & 0b1100_0000 == 0b0100_0000)
671 }
672
673 /// Returns [`true`] if this address part of the `198.18.0.0/15` range, which is reserved for
674 /// network devices benchmarking. This range is defined in [IETF RFC 2544] as `192.18.0.0`
675 /// through `198.19.255.255` but [errata 423] corrects it to `198.18.0.0/15`.
676 ///
677 /// [IETF RFC 2544]: https://tools.ietf.org/html/rfc2544
678 /// [errata 423]: https://www.rfc-editor.org/errata/eid423
679 ///
680 /// # Examples
681 ///
682 /// ```
683 /// use core_net::Ipv4Addr;
684 ///
685 /// assert_eq!(Ipv4Addr::new(198, 17, 255, 255).is_benchmarking(), false);
686 /// assert_eq!(Ipv4Addr::new(198, 18, 0, 0).is_benchmarking(), true);
687 /// assert_eq!(Ipv4Addr::new(198, 19, 255, 255).is_benchmarking(), true);
688 /// assert_eq!(Ipv4Addr::new(198, 20, 0, 0).is_benchmarking(), false);
689 /// ```
690 #[must_use]
691 #[inline]
692 pub const fn is_benchmarking(&self) -> bool {
693 self.octets()[0] == 198 && (self.octets()[1] & 0xfe) == 18
694 }
695
696 /// Returns [`true`] if this address is reserved by IANA for future use. [IETF RFC 1112]
697 /// defines the block of reserved addresses as `240.0.0.0/4`. This range normally includes the
698 /// broadcast address `255.255.255.255`, but this implementation explicitly excludes it, since
699 /// it is obviously not reserved for future use.
700 ///
701 /// [IETF RFC 1112]: https://tools.ietf.org/html/rfc1112
702 ///
703 /// # Warning
704 ///
705 /// As IANA assigns new addresses, this method will be
706 /// updated. This may result in non-reserved addresses being
707 /// treated as reserved in code that relies on an outdated version
708 /// of this method.
709 ///
710 /// # Examples
711 ///
712 /// ```
713 /// use core_net::Ipv4Addr;
714 ///
715 /// assert_eq!(Ipv4Addr::new(240, 0, 0, 0).is_reserved(), true);
716 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 254).is_reserved(), true);
717 ///
718 /// assert_eq!(Ipv4Addr::new(239, 255, 255, 255).is_reserved(), false);
719 /// // The broadcast address is not considered as reserved for future use by this implementation
720 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_reserved(), false);
721 /// ```
722 #[must_use]
723 #[inline]
724 pub const fn is_reserved(&self) -> bool {
725 self.octets()[0] & 240 == 240 && !self.is_broadcast()
726 }
727
728 /// Returns [`true`] if this is a multicast address (`224.0.0.0/4`).
729 ///
730 /// Multicast addresses have a most significant octet between `224` and `239`,
731 /// and is defined by [IETF RFC 5771].
732 ///
733 /// [IETF RFC 5771]: https://tools.ietf.org/html/rfc5771
734 ///
735 /// # Examples
736 ///
737 /// ```
738 /// use core_net::Ipv4Addr;
739 ///
740 /// assert_eq!(Ipv4Addr::new(224, 254, 0, 0).is_multicast(), true);
741 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_multicast(), true);
742 /// assert_eq!(Ipv4Addr::new(172, 16, 10, 65).is_multicast(), false);
743 /// ```
744 #[must_use]
745 #[inline]
746 pub const fn is_multicast(&self) -> bool {
747 self.octets()[0] >= 224 && self.octets()[0] <= 239
748 }
749
750 /// Returns [`true`] if this is a broadcast address (`255.255.255.255`).
751 ///
752 /// A broadcast address has all octets set to `255` as defined in [IETF RFC 919].
753 ///
754 /// [IETF RFC 919]: https://tools.ietf.org/html/rfc919
755 ///
756 /// # Examples
757 ///
758 /// ```
759 /// use core_net::Ipv4Addr;
760 ///
761 /// assert_eq!(Ipv4Addr::new(255, 255, 255, 255).is_broadcast(), true);
762 /// assert_eq!(Ipv4Addr::new(236, 168, 10, 65).is_broadcast(), false);
763 /// ```
764 #[must_use]
765 #[inline]
766 pub const fn is_broadcast(&self) -> bool {
767 u32::from_be_bytes(self.octets()) == u32::from_be_bytes(Self::BROADCAST.octets())
768 }
769
770 /// Returns [`true`] if this address is in a range designated for documentation.
771 ///
772 /// This is defined in [IETF RFC 5737]:
773 ///
774 /// - `192.0.2.0/24` (TEST-NET-1)
775 /// - `198.51.100.0/24` (TEST-NET-2)
776 /// - `203.0.113.0/24` (TEST-NET-3)
777 ///
778 /// [IETF RFC 5737]: https://tools.ietf.org/html/rfc5737
779 ///
780 /// # Examples
781 ///
782 /// ```
783 /// use core_net::Ipv4Addr;
784 ///
785 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).is_documentation(), true);
786 /// assert_eq!(Ipv4Addr::new(198, 51, 100, 65).is_documentation(), true);
787 /// assert_eq!(Ipv4Addr::new(203, 0, 113, 6).is_documentation(), true);
788 /// assert_eq!(Ipv4Addr::new(193, 34, 17, 19).is_documentation(), false);
789 /// ```
790 #[must_use]
791 #[inline]
792 pub const fn is_documentation(&self) -> bool {
793 matches!(self.octets(), [192, 0, 2, _] | [198, 51, 100, _] | [203, 0, 113, _])
794 }
795
796 /// Converts this address to an [IPv4-compatible] [`IPv6` address].
797 ///
798 /// `a.b.c.d` becomes `::a.b.c.d`
799 ///
800 /// Note that IPv4-compatible addresses have been officially deprecated.
801 /// If you don't explicitly need an IPv4-compatible address for legacy reasons, consider using `to_ipv6_mapped` instead.
802 ///
803 /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
804 /// [`IPv6` address]: Ipv6Addr
805 ///
806 /// # Examples
807 ///
808 /// ```
809 /// use core_net::{Ipv4Addr, Ipv6Addr};
810 ///
811 /// assert_eq!(
812 /// Ipv4Addr::new(192, 0, 2, 255).to_ipv6_compatible(),
813 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x2ff)
814 /// );
815 /// ```
816 #[must_use = "this returns the result of the operation, \
817 without modifying the original"]
818 #[inline]
819 pub const fn to_ipv6_compatible(&self) -> Ipv6Addr {
820 let [a, b, c, d] = self.octets();
821 Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] }
822 }
823
824 /// Converts this address to an [IPv4-mapped] [`IPv6` address].
825 ///
826 /// `a.b.c.d` becomes `::ffff:a.b.c.d`
827 ///
828 /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
829 /// [`IPv6` address]: Ipv6Addr
830 ///
831 /// # Examples
832 ///
833 /// ```
834 /// use core_net::{Ipv4Addr, Ipv6Addr};
835 ///
836 /// assert_eq!(Ipv4Addr::new(192, 0, 2, 255).to_ipv6_mapped(),
837 /// Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x2ff));
838 /// ```
839 #[must_use = "this returns the result of the operation, \
840 without modifying the original"]
841 #[inline]
842 pub const fn to_ipv6_mapped(&self) -> Ipv6Addr {
843 let [a, b, c, d] = self.octets();
844 Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] }
845 }
846}
847
848impl fmt::Display for IpAddr {
849 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
850 match self {
851 IpAddr::V4(ip) => ip.fmt(fmt),
852 IpAddr::V6(ip) => ip.fmt(fmt),
853 }
854 }
855}
856
857impl fmt::Debug for IpAddr {
858 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
859 fmt::Display::fmt(self, fmt)
860 }
861}
862
863impl From<Ipv4Addr> for IpAddr {
864 /// Copies this address to a new `IpAddr::V4`.
865 ///
866 /// # Examples
867 ///
868 /// ```
869 /// use core_net::{IpAddr, Ipv4Addr};
870 ///
871 /// let addr = Ipv4Addr::new(127, 0, 0, 1);
872 ///
873 /// assert_eq!(
874 /// IpAddr::V4(addr),
875 /// IpAddr::from(addr)
876 /// )
877 /// ```
878 #[inline]
879 fn from(ipv4: Ipv4Addr) -> IpAddr {
880 IpAddr::V4(ipv4)
881 }
882}
883
884impl From<Ipv6Addr> for IpAddr {
885 /// Copies this address to a new `IpAddr::V6`.
886 ///
887 /// # Examples
888 ///
889 /// ```
890 /// use core_net::{IpAddr, Ipv6Addr};
891 ///
892 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
893 ///
894 /// assert_eq!(
895 /// IpAddr::V6(addr),
896 /// IpAddr::from(addr)
897 /// );
898 /// ```
899 #[inline]
900 fn from(ipv6: Ipv6Addr) -> IpAddr {
901 IpAddr::V6(ipv6)
902 }
903}
904
905impl fmt::Display for Ipv4Addr {
906 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
907 let octets = self.octets();
908
909 // If there are no alignment requirements, write the IP address directly to `f`.
910 // Otherwise, write it to a local buffer and then use `f.pad`.
911 if fmt.precision().is_none() && fmt.width().is_none() {
912 write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
913 } else {
914 const LONGEST_IPV4_ADDR: &str = "255.255.255.255";
915
916 let mut buf = String::with_capacity(LONGEST_IPV4_ADDR.len());
917 // Buffer is long enough for the longest possible IPv4 address, so this should never fail.
918 write!(buf, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3]).unwrap();
919
920 fmt.pad(buf.as_str())
921 }
922 }
923}
924
925impl fmt::Debug for Ipv4Addr {
926 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
927 fmt::Display::fmt(self, fmt)
928 }
929}
930
931impl PartialEq<Ipv4Addr> for IpAddr {
932 #[inline]
933 fn eq(&self, other: &Ipv4Addr) -> bool {
934 match self {
935 IpAddr::V4(v4) => v4 == other,
936 IpAddr::V6(_) => false,
937 }
938 }
939}
940
941impl PartialEq<IpAddr> for Ipv4Addr {
942 #[inline]
943 fn eq(&self, other: &IpAddr) -> bool {
944 match other {
945 IpAddr::V4(v4) => self == v4,
946 IpAddr::V6(_) => false,
947 }
948 }
949}
950
951impl PartialOrd for Ipv4Addr {
952 #[inline]
953 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
954 Some(self.cmp(other))
955 }
956}
957
958impl PartialOrd<Ipv4Addr> for IpAddr {
959 #[inline]
960 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
961 match self {
962 IpAddr::V4(v4) => v4.partial_cmp(other),
963 IpAddr::V6(_) => Some(Ordering::Greater),
964 }
965 }
966}
967
968impl PartialOrd<IpAddr> for Ipv4Addr {
969 #[inline]
970 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
971 match other {
972 IpAddr::V4(v4) => self.partial_cmp(v4),
973 IpAddr::V6(_) => Some(Ordering::Less),
974 }
975 }
976}
977
978impl Ord for Ipv4Addr {
979 #[inline]
980 fn cmp(&self, other: &Ipv4Addr) -> Ordering {
981 self.octets.cmp(&other.octets)
982 }
983}
984
985impl From<Ipv4Addr> for u32 {
986 /// Converts an `Ipv4Addr` into a host byte order `u32`.
987 ///
988 /// # Examples
989 ///
990 /// ```
991 /// use core_net::Ipv4Addr;
992 ///
993 /// let addr = Ipv4Addr::new(0x12, 0x34, 0x56, 0x78);
994 /// assert_eq!(0x12345678, u32::from(addr));
995 /// ```
996 #[inline]
997 fn from(ip: Ipv4Addr) -> u32 {
998 u32::from_be_bytes(ip.octets)
999 }
1000}
1001
1002impl From<u32> for Ipv4Addr {
1003 /// Converts a host byte order `u32` into an `Ipv4Addr`.
1004 ///
1005 /// # Examples
1006 ///
1007 /// ```
1008 /// use core_net::Ipv4Addr;
1009 ///
1010 /// let addr = Ipv4Addr::from(0x12345678);
1011 /// assert_eq!(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78), addr);
1012 /// ```
1013 #[inline]
1014 fn from(ip: u32) -> Ipv4Addr {
1015 Ipv4Addr { octets: ip.to_be_bytes() }
1016 }
1017}
1018
1019impl From<[u8; 4]> for Ipv4Addr {
1020 /// Creates an `Ipv4Addr` from a four element byte array.
1021 ///
1022 /// # Examples
1023 ///
1024 /// ```
1025 /// use core_net::Ipv4Addr;
1026 ///
1027 /// let addr = Ipv4Addr::from([13u8, 12u8, 11u8, 10u8]);
1028 /// assert_eq!(Ipv4Addr::new(13, 12, 11, 10), addr);
1029 /// ```
1030 #[inline]
1031 fn from(octets: [u8; 4]) -> Ipv4Addr {
1032 Ipv4Addr { octets }
1033 }
1034}
1035
1036impl From<[u8; 4]> for IpAddr {
1037 /// Creates an `IpAddr::V4` from a four element byte array.
1038 ///
1039 /// # Examples
1040 ///
1041 /// ```
1042 /// use core_net::{IpAddr, Ipv4Addr};
1043 ///
1044 /// let addr = IpAddr::from([13u8, 12u8, 11u8, 10u8]);
1045 /// assert_eq!(IpAddr::V4(Ipv4Addr::new(13, 12, 11, 10)), addr);
1046 /// ```
1047 #[inline]
1048 fn from(octets: [u8; 4]) -> IpAddr {
1049 IpAddr::V4(Ipv4Addr::from(octets))
1050 }
1051}
1052
1053impl Ipv6Addr {
1054 /// Creates a new IPv6 address from eight 16-bit segments.
1055 ///
1056 /// The result will represent the IP address `a:b:c:d:e:f:g:h`.
1057 ///
1058 /// # Examples
1059 ///
1060 /// ```
1061 /// use core_net::Ipv6Addr;
1062 ///
1063 /// let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff);
1064 /// ```
1065 #[must_use]
1066 #[inline]
1067 pub const fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> Ipv6Addr {
1068 let addr16 = [
1069 a.to_be(),
1070 b.to_be(),
1071 c.to_be(),
1072 d.to_be(),
1073 e.to_be(),
1074 f.to_be(),
1075 g.to_be(),
1076 h.to_be(),
1077 ];
1078 Ipv6Addr {
1079 // All elements in `addr16` are big endian.
1080 // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
1081 octets: unsafe { transmute::<_, [u8; 16]>(addr16) },
1082 }
1083 }
1084
1085 /// An IPv6 address representing localhost: `::1`.
1086 ///
1087 /// This corresponds to constant `IN6ADDR_LOOPBACK_INIT` or `in6addr_loopback` in other
1088 /// languages.
1089 ///
1090 /// # Examples
1091 ///
1092 /// ```
1093 /// use core_net::Ipv6Addr;
1094 ///
1095 /// let addr = Ipv6Addr::LOCALHOST;
1096 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
1097 /// ```
1098 #[doc(alias = "IN6ADDR_LOOPBACK_INIT")]
1099 #[doc(alias = "in6addr_loopback")]
1100 pub const LOCALHOST: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
1101
1102 /// An IPv6 address representing the unspecified address: `::`
1103 ///
1104 /// This corresponds to constant `IN6ADDR_ANY_INIT` or `in6addr_any` in other languages.
1105 ///
1106 /// # Examples
1107 ///
1108 /// ```
1109 /// use core_net::Ipv6Addr;
1110 ///
1111 /// let addr = Ipv6Addr::UNSPECIFIED;
1112 /// assert_eq!(addr, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));
1113 /// ```
1114 #[doc(alias = "IN6ADDR_ANY_INIT")]
1115 #[doc(alias = "in6addr_any")]
1116 pub const UNSPECIFIED: Self = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0);
1117
1118 /// Returns the eight 16-bit segments that make up this address.
1119 ///
1120 /// # Examples
1121 ///
1122 /// ```
1123 /// use core_net::Ipv6Addr;
1124 ///
1125 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(),
1126 /// [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]);
1127 /// ```
1128 #[must_use]
1129 #[inline]
1130 pub const fn segments(&self) -> [u16; 8] {
1131 // All elements in `self.octets` must be big endian.
1132 // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`.
1133 let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.octets) };
1134 // We want native endian u16
1135 [
1136 u16::from_be(a),
1137 u16::from_be(b),
1138 u16::from_be(c),
1139 u16::from_be(d),
1140 u16::from_be(e),
1141 u16::from_be(f),
1142 u16::from_be(g),
1143 u16::from_be(h),
1144 ]
1145 }
1146
1147 /// Returns [`true`] for the special 'unspecified' address (`::`).
1148 ///
1149 /// This property is defined in [IETF RFC 4291].
1150 ///
1151 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1152 ///
1153 /// # Examples
1154 ///
1155 /// ```
1156 /// use core_net::Ipv6Addr;
1157 ///
1158 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unspecified(), false);
1159 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).is_unspecified(), true);
1160 /// ```
1161 #[must_use]
1162 #[inline]
1163 pub const fn is_unspecified(&self) -> bool {
1164 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::UNSPECIFIED.octets())
1165 }
1166
1167 /// Returns [`true`] if this is the [loopback address] (`::1`),
1168 /// as defined in [IETF RFC 4291 section 2.5.3].
1169 ///
1170 /// Contrary to IPv4, in IPv6 there is only one loopback address.
1171 ///
1172 /// [loopback address]: Ipv6Addr::LOCALHOST
1173 /// [IETF RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1174 ///
1175 /// # Examples
1176 ///
1177 /// ```
1178 /// use core_net::Ipv6Addr;
1179 ///
1180 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_loopback(), false);
1181 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1).is_loopback(), true);
1182 /// ```
1183 #[must_use]
1184 #[inline]
1185 pub const fn is_loopback(&self) -> bool {
1186 u128::from_be_bytes(self.octets()) == u128::from_be_bytes(Ipv6Addr::LOCALHOST.octets())
1187 }
1188
1189 /// Returns [`true`] if the address appears to be globally reachable
1190 /// as specified by the [IANA IPv6 Special-Purpose Address Registry].
1191 /// Whether or not an address is practically reachable will depend on your network configuration.
1192 ///
1193 /// Most IPv6 addresses are globally reachable;
1194 /// unless they are specifically defined as *not* globally reachable.
1195 ///
1196 /// Non-exhaustive list of notable addresses that are not globally reachable:
1197 /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified))
1198 /// - The [loopback address] ([`is_loopback`](Ipv6Addr::is_loopback))
1199 /// - IPv4-mapped addresses
1200 /// - Addresses reserved for benchmarking
1201 /// - Addresses reserved for documentation ([`is_documentation`](Ipv6Addr::is_documentation))
1202 /// - Unique local addresses ([`is_unique_local`](Ipv6Addr::is_unique_local))
1203 /// - Unicast addresses with link-local scope ([`is_unicast_link_local`](Ipv6Addr::is_unicast_link_local))
1204 ///
1205 /// For the complete overview of which addresses are globally reachable, see the table at the [IANA IPv6 Special-Purpose Address Registry].
1206 ///
1207 /// Note that an address having global scope is not the same as being globally reachable,
1208 /// and there is no direct relation between the two concepts: There exist addresses with global scope
1209 /// that are not globally reachable (for example unique local addresses),
1210 /// and addresses that are globally reachable without having global scope
1211 /// (multicast addresses with non-global scope).
1212 ///
1213 /// [IANA IPv6 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
1214 /// [unspecified address]: Ipv6Addr::UNSPECIFIED
1215 /// [loopback address]: Ipv6Addr::LOCALHOST
1216 ///
1217 /// # Examples
1218 ///
1219 /// ```
1220 /// use core_net::Ipv6Addr;
1221 ///
1222 /// // Most IPv6 addresses are globally reachable:
1223 /// assert_eq!(Ipv6Addr::new(0x26, 0, 0x1c9, 0, 0, 0xafc8, 0x10, 0x1).is_global(), true);
1224 ///
1225 /// // However some addresses have been assigned a special meaning
1226 /// // that makes them not globally reachable. Some examples are:
1227 ///
1228 /// // The unspecified address (`::`)
1229 /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_global(), false);
1230 ///
1231 /// // The loopback address (`::1`)
1232 /// assert_eq!(Ipv6Addr::LOCALHOST.is_global(), false);
1233 ///
1234 /// // IPv4-mapped addresses (`::ffff:0:0/96`)
1235 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_global(), false);
1236 ///
1237 /// // Addresses reserved for benchmarking (`2001:2::/48`)
1238 /// assert_eq!(Ipv6Addr::new(0x2001, 2, 0, 0, 0, 0, 0, 1,).is_global(), false);
1239 ///
1240 /// // Addresses reserved for documentation (`2001:db8::/32`)
1241 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).is_global(), false);
1242 ///
1243 /// // Unique local addresses (`fc00::/7`)
1244 /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1245 ///
1246 /// // Unicast addresses with link-local scope (`fe80::/10`)
1247 /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 1).is_global(), false);
1248 ///
1249 /// // For a complete overview see the IANA IPv6 Special-Purpose Address Registry.
1250 /// ```
1251 #[must_use]
1252 #[inline]
1253 pub const fn is_global(&self) -> bool {
1254 !(self.is_unspecified()
1255 || self.is_loopback()
1256 // IPv4-mapped Address (`::ffff:0:0/96`)
1257 || matches!(self.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
1258 // IPv4-IPv6 Translat. (`64:ff9b:1::/48`)
1259 || matches!(self.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
1260 // Discard-Only Address Block (`100::/64`)
1261 || matches!(self.segments(), [0x100, 0, 0, 0, _, _, _, _])
1262 // IETF Protocol Assignments (`2001::/23`)
1263 || (matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
1264 && !(
1265 // Port Control Protocol Anycast (`2001:1::1`)
1266 u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
1267 // Traversal Using Relays around NAT Anycast (`2001:1::2`)
1268 || u128::from_be_bytes(self.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
1269 // AMT (`2001:3::/32`)
1270 || matches!(self.segments(), [0x2001, 3, _, _, _, _, _, _])
1271 // AS112-v6 (`2001:4:112::/48`)
1272 || matches!(self.segments(), [0x2001, 4, 0x112, _, _, _, _, _])
1273 // ORCHIDv2 (`2001:20::/28`)
1274 || matches!(self.segments(), [0x2001, b, _, _, _, _, _, _] if b >= 0x20 && b <= 0x2F)
1275 ))
1276 || self.is_documentation()
1277 || self.is_unique_local()
1278 || self.is_unicast_link_local())
1279 }
1280
1281 /// Returns [`true`] if this is a unique local address (`fc00::/7`).
1282 ///
1283 /// This property is defined in [IETF RFC 4193].
1284 ///
1285 /// [IETF RFC 4193]: https://tools.ietf.org/html/rfc4193
1286 ///
1287 /// # Examples
1288 ///
1289 /// ```
1290 /// use core_net::Ipv6Addr;
1291 ///
1292 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unique_local(), false);
1293 /// assert_eq!(Ipv6Addr::new(0xfc02, 0, 0, 0, 0, 0, 0, 0).is_unique_local(), true);
1294 /// ```
1295 #[must_use]
1296 #[inline]
1297 pub const fn is_unique_local(&self) -> bool {
1298 (self.segments()[0] & 0xfe00) == 0xfc00
1299 }
1300
1301 /// Returns [`true`] if this is a unicast address, as defined by [IETF RFC 4291].
1302 /// Any address that is not a [multicast address] (`ff00::/8`) is unicast.
1303 ///
1304 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1305 /// [multicast address]: Ipv6Addr::is_multicast
1306 ///
1307 /// # Examples
1308 ///
1309 /// ```
1310 /// use core_net::Ipv6Addr;
1311 ///
1312 /// // The unspecified and loopback addresses are unicast.
1313 /// assert_eq!(Ipv6Addr::UNSPECIFIED.is_unicast(), true);
1314 /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast(), true);
1315 ///
1316 /// // Any address that is not a multicast address (`ff00::/8`) is unicast.
1317 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast(), true);
1318 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_unicast(), false);
1319 /// ```
1320 #[must_use]
1321 #[inline]
1322 pub const fn is_unicast(&self) -> bool {
1323 !self.is_multicast()
1324 }
1325
1326 /// Returns `true` if the address is a unicast address with link-local scope,
1327 /// as defined in [RFC 4291].
1328 ///
1329 /// A unicast address has link-local scope if it has the prefix `fe80::/10`, as per [RFC 4291 section 2.4].
1330 /// Note that this encompasses more addresses than those defined in [RFC 4291 section 2.5.6],
1331 /// which describes "Link-Local IPv6 Unicast Addresses" as having the following stricter format:
1332 ///
1333 /// ```text
1334 /// | 10 bits | 54 bits | 64 bits |
1335 /// +----------+-------------------------+----------------------------+
1336 /// |1111111010| 0 | interface ID |
1337 /// +----------+-------------------------+----------------------------+
1338 /// ```
1339 /// So while currently the only addresses with link-local scope an application will encounter are all in `fe80::/64`,
1340 /// this might change in the future with the publication of new standards. More addresses in `fe80::/10` could be allocated,
1341 /// and those addresses will have link-local scope.
1342 ///
1343 /// 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",
1344 /// this does not mean that the loopback address actually has link-local scope and this method will return `false` on it.
1345 ///
1346 /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
1347 /// [RFC 4291 section 2.4]: https://tools.ietf.org/html/rfc4291#section-2.4
1348 /// [RFC 4291 section 2.5.3]: https://tools.ietf.org/html/rfc4291#section-2.5.3
1349 /// [RFC 4291 section 2.5.6]: https://tools.ietf.org/html/rfc4291#section-2.5.6
1350 /// [loopback address]: Ipv6Addr::LOCALHOST
1351 ///
1352 /// # Examples
1353 ///
1354 /// ```
1355 /// use core_net::Ipv6Addr;
1356 ///
1357 /// // The loopback address (`::1`) does not actually have link-local scope.
1358 /// assert_eq!(Ipv6Addr::LOCALHOST.is_unicast_link_local(), false);
1359 ///
1360 /// // Only addresses in `fe80::/10` have link-local scope.
1361 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), false);
1362 /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1363 ///
1364 /// // Addresses outside the stricter `fe80::/64` also have link-local scope.
1365 /// assert_eq!(Ipv6Addr::new(0xfe80, 0, 0, 1, 0, 0, 0, 0).is_unicast_link_local(), true);
1366 /// assert_eq!(Ipv6Addr::new(0xfe81, 0, 0, 0, 0, 0, 0, 0).is_unicast_link_local(), true);
1367 /// ```
1368 #[must_use]
1369 #[inline]
1370 pub const fn is_unicast_link_local(&self) -> bool {
1371 (self.segments()[0] & 0xffc0) == 0xfe80
1372 }
1373
1374 /// Returns [`true`] if this is an address reserved for documentation
1375 /// (`2001:db8::/32`).
1376 ///
1377 /// This property is defined in [IETF RFC 3849].
1378 ///
1379 /// [IETF RFC 3849]: https://tools.ietf.org/html/rfc3849
1380 ///
1381 /// # Examples
1382 ///
1383 /// ```
1384 /// use core_net::Ipv6Addr;
1385 ///
1386 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_documentation(), false);
1387 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_documentation(), true);
1388 /// ```
1389 #[must_use]
1390 #[inline]
1391 pub const fn is_documentation(&self) -> bool {
1392 (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
1393 }
1394
1395 /// Returns [`true`] if this is an address reserved for benchmarking (`2001:2::/48`).
1396 ///
1397 /// This property is defined in [IETF RFC 5180], where it is mistakenly specified as covering the range `2001:0200::/48`.
1398 /// This is corrected in [IETF RFC Errata 1752] to `2001:0002::/48`.
1399 ///
1400 /// [IETF RFC 5180]: https://tools.ietf.org/html/rfc5180
1401 /// [IETF RFC Errata 1752]: https://www.rfc-editor.org/errata_search.php?eid=1752
1402 ///
1403 /// ```
1404 /// use core_net::Ipv6Addr;
1405 ///
1406 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc613, 0x0).is_benchmarking(), false);
1407 /// assert_eq!(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0).is_benchmarking(), true);
1408 /// ```
1409 #[must_use]
1410 #[inline]
1411 pub const fn is_benchmarking(&self) -> bool {
1412 (self.segments()[0] == 0x2001) && (self.segments()[1] == 0x2) && (self.segments()[2] == 0)
1413 }
1414
1415 /// Returns [`true`] if the address is a globally routable unicast address.
1416 ///
1417 /// The following return false:
1418 ///
1419 /// - the loopback address
1420 /// - the link-local addresses
1421 /// - unique local addresses
1422 /// - the unspecified address
1423 /// - the address range reserved for documentation
1424 ///
1425 /// This method returns [`true`] for site-local addresses as per [RFC 4291 section 2.5.7]
1426 ///
1427 /// ```no_rust
1428 /// The special behavior of [the site-local unicast] prefix defined in [RFC3513] must no longer
1429 /// be supported in new implementations (i.e., new implementations must treat this prefix as
1430 /// Global Unicast).
1431 /// ```
1432 ///
1433 /// [RFC 4291 section 2.5.7]: https://tools.ietf.org/html/rfc4291#section-2.5.7
1434 ///
1435 /// # Examples
1436 ///
1437 /// ```
1438 /// use core_net::Ipv6Addr;
1439 ///
1440 /// assert_eq!(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0).is_unicast_global(), false);
1441 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_unicast_global(), true);
1442 /// ```
1443 #[must_use]
1444 #[inline]
1445 pub const fn is_unicast_global(&self) -> bool {
1446 self.is_unicast()
1447 && !self.is_loopback()
1448 && !self.is_unicast_link_local()
1449 && !self.is_unique_local()
1450 && !self.is_unspecified()
1451 && !self.is_documentation()
1452 && !self.is_benchmarking()
1453 }
1454
1455 /// Returns the address's multicast scope if the address is multicast.
1456 ///
1457 /// # Examples
1458 ///
1459 /// ```
1460 /// use core_net::{Ipv6Addr, Ipv6MulticastScope};
1461 ///
1462 /// assert_eq!(
1463 /// Ipv6Addr::new(0xff0e, 0, 0, 0, 0, 0, 0, 0).multicast_scope(),
1464 /// Some(Ipv6MulticastScope::Global)
1465 /// );
1466 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).multicast_scope(), None);
1467 /// ```
1468 #[must_use]
1469 #[inline]
1470 pub const fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
1471 if self.is_multicast() {
1472 match self.segments()[0] & 0x000f {
1473 1 => Some(Ipv6MulticastScope::InterfaceLocal),
1474 2 => Some(Ipv6MulticastScope::LinkLocal),
1475 3 => Some(Ipv6MulticastScope::RealmLocal),
1476 4 => Some(Ipv6MulticastScope::AdminLocal),
1477 5 => Some(Ipv6MulticastScope::SiteLocal),
1478 8 => Some(Ipv6MulticastScope::OrganizationLocal),
1479 14 => Some(Ipv6MulticastScope::Global),
1480 _ => None,
1481 }
1482 } else {
1483 None
1484 }
1485 }
1486
1487 /// Returns [`true`] if this is a multicast address (`ff00::/8`).
1488 ///
1489 /// This property is defined by [IETF RFC 4291].
1490 ///
1491 /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291
1492 ///
1493 /// # Examples
1494 ///
1495 /// ```
1496 /// use core_net::Ipv6Addr;
1497 ///
1498 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).is_multicast(), true);
1499 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).is_multicast(), false);
1500 /// ```
1501 #[must_use]
1502 #[inline]
1503 pub const fn is_multicast(&self) -> bool {
1504 (self.segments()[0] & 0xff00) == 0xff00
1505 }
1506
1507 /// Converts this address to an [`IPv4` address] if it's an [IPv4-mapped] address,
1508 /// as defined in [IETF RFC 4291 section 2.5.5.2], otherwise returns [`None`].
1509 ///
1510 /// `::ffff:a.b.c.d` becomes `a.b.c.d`.
1511 /// All addresses *not* starting with `::ffff` will return `None`.
1512 ///
1513 /// [`IPv4` address]: Ipv4Addr
1514 /// [IPv4-mapped]: Ipv6Addr
1515 /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1516 ///
1517 /// # Examples
1518 ///
1519 /// ```
1520 /// use core_net::{Ipv4Addr, Ipv6Addr};
1521 ///
1522 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4_mapped(), None);
1523 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4_mapped(),
1524 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1525 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4_mapped(), None);
1526 /// ```
1527 #[must_use = "this returns the result of the operation, \
1528 without modifying the original"]
1529 #[inline]
1530 pub const fn to_ipv4_mapped(&self) -> Option<Ipv4Addr> {
1531 match self.octets() {
1532 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, a, b, c, d] => {
1533 Some(Ipv4Addr::new(a, b, c, d))
1534 }
1535 _ => None,
1536 }
1537 }
1538
1539 /// Converts this address to an [`IPv4` address] if it is either
1540 /// an [IPv4-compatible] address as defined in [IETF RFC 4291 section 2.5.5.1],
1541 /// or an [IPv4-mapped] address as defined in [IETF RFC 4291 section 2.5.5.2],
1542 /// otherwise returns [`None`].
1543 ///
1544 /// Note that this will return an [`IPv4` address] for the IPv6 loopback address `::1`. Use
1545 /// [`Ipv6Addr::to_ipv4_mapped`] to avoid this.
1546 ///
1547 /// `::a.b.c.d` and `::ffff:a.b.c.d` become `a.b.c.d`. `::1` becomes `0.0.0.1`.
1548 /// All addresses *not* starting with either all zeroes or `::ffff` will return `None`.
1549 ///
1550 /// [`IPv4` address]: Ipv4Addr
1551 /// [IPv4-compatible]: Ipv6Addr#ipv4-compatible-ipv6-addresses
1552 /// [IPv4-mapped]: Ipv6Addr#ipv4-mapped-ipv6-addresses
1553 /// [IETF RFC 4291 section 2.5.5.1]: https://tools.ietf.org/html/rfc4291#section-2.5.5.1
1554 /// [IETF RFC 4291 section 2.5.5.2]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
1555 ///
1556 /// # Examples
1557 ///
1558 /// ```
1559 /// use core_net::{Ipv4Addr, Ipv6Addr};
1560 ///
1561 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).to_ipv4(), None);
1562 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).to_ipv4(),
1563 /// Some(Ipv4Addr::new(192, 10, 2, 255)));
1564 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_ipv4(),
1565 /// Some(Ipv4Addr::new(0, 0, 0, 1)));
1566 /// ```
1567 #[must_use = "this returns the result of the operation, \
1568 without modifying the original"]
1569 #[inline]
1570 pub const fn to_ipv4(&self) -> Option<Ipv4Addr> {
1571 if let [0, 0, 0, 0, 0, 0 | 0xffff, ab, cd] = self.segments() {
1572 let [a, b] = ab.to_be_bytes();
1573 let [c, d] = cd.to_be_bytes();
1574 Some(Ipv4Addr::new(a, b, c, d))
1575 } else {
1576 None
1577 }
1578 }
1579
1580 /// Converts this address to an `IpAddr::V4` if it is an IPv4-mapped addresses, otherwise it
1581 /// returns self wrapped in an `IpAddr::V6`.
1582 ///
1583 /// # Examples
1584 ///
1585 /// ```
1586 /// use core_net::Ipv6Addr;
1587 ///
1588 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).is_loopback(), false);
1589 /// assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x7f00, 0x1).to_canonical().is_loopback(), true);
1590 /// ```
1591 #[must_use = "this returns the result of the operation, \
1592 without modifying the original"]
1593 #[inline]
1594 pub const fn to_canonical(&self) -> IpAddr {
1595 if let Some(mapped) = self.to_ipv4_mapped() {
1596 return IpAddr::V4(mapped);
1597 }
1598 IpAddr::V6(*self)
1599 }
1600
1601 /// Returns the sixteen eight-bit integers the IPv6 address consists of.
1602 ///
1603 /// ```
1604 /// use core_net::Ipv6Addr;
1605 ///
1606 /// assert_eq!(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0).octets(),
1607 /// [255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1608 /// ```
1609 #[must_use]
1610 #[inline]
1611 pub const fn octets(&self) -> [u8; 16] {
1612 self.octets
1613 }
1614}
1615
1616/// Write an Ipv6Addr, conforming to the canonical style described by
1617/// [RFC 5952](https://tools.ietf.org/html/rfc5952).
1618impl fmt::Display for Ipv6Addr {
1619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1620 // If there are no alignment requirements, write the IP address directly to `f`.
1621 // Otherwise, write it to a local buffer and then use `f.pad`.
1622 if f.precision().is_none() && f.width().is_none() {
1623 let segments = self.segments();
1624
1625 // Special case for :: and ::1; otherwise they get written with the
1626 // IPv4 formatter
1627 if self.is_unspecified() {
1628 f.write_str("::")
1629 } else if self.is_loopback() {
1630 f.write_str("::1")
1631 } else if let Some(ipv4) = self.to_ipv4() {
1632 match segments[5] {
1633 // IPv4 Compatible address
1634 0 => write!(f, "::{}", ipv4),
1635 // IPv4 Mapped address
1636 0xffff => write!(f, "::ffff:{}", ipv4),
1637 _ => unreachable!(),
1638 }
1639 } else {
1640 #[derive(Copy, Clone, Default)]
1641 struct Span {
1642 start: usize,
1643 len: usize,
1644 }
1645
1646 // Find the inner 0 span
1647 let zeroes = {
1648 let mut longest = Span::default();
1649 let mut current = Span::default();
1650
1651 for (i, &segment) in segments.iter().enumerate() {
1652 if segment == 0 {
1653 if current.len == 0 {
1654 current.start = i;
1655 }
1656
1657 current.len += 1;
1658
1659 if current.len > longest.len {
1660 longest = current;
1661 }
1662 } else {
1663 current = Span::default();
1664 }
1665 }
1666
1667 longest
1668 };
1669
1670 /// Write a colon-separated part of the address
1671 #[inline]
1672 fn fmt_subslice(f: &mut fmt::Formatter<'_>, chunk: &[u16]) -> fmt::Result {
1673 if let Some((first, tail)) = chunk.split_first() {
1674 write!(f, "{:x}", first)?;
1675 for segment in tail {
1676 f.write_char(':')?;
1677 write!(f, "{:x}", segment)?;
1678 }
1679 }
1680 Ok(())
1681 }
1682
1683 if zeroes.len > 1 {
1684 fmt_subslice(f, &segments[..zeroes.start])?;
1685 f.write_str("::")?;
1686 fmt_subslice(f, &segments[zeroes.start + zeroes.len..])
1687 } else {
1688 fmt_subslice(f, &segments)
1689 }
1690 }
1691 } else {
1692 const LONGEST_IPV6_ADDR: &str = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
1693
1694 let mut buf = String::with_capacity(LONGEST_IPV6_ADDR.len());
1695 // Buffer is long enough for the longest possible IPv6 address, so this should never fail.
1696 write!(buf, "{}", self).unwrap();
1697
1698 f.pad(buf.as_str())
1699 }
1700 }
1701}
1702
1703impl fmt::Debug for Ipv6Addr {
1704 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1705 fmt::Display::fmt(self, fmt)
1706 }
1707}
1708
1709impl PartialEq<IpAddr> for Ipv6Addr {
1710 #[inline]
1711 fn eq(&self, other: &IpAddr) -> bool {
1712 match other {
1713 IpAddr::V4(_) => false,
1714 IpAddr::V6(v6) => self == v6,
1715 }
1716 }
1717}
1718
1719impl PartialEq<Ipv6Addr> for IpAddr {
1720 #[inline]
1721 fn eq(&self, other: &Ipv6Addr) -> bool {
1722 match self {
1723 IpAddr::V4(_) => false,
1724 IpAddr::V6(v6) => v6 == other,
1725 }
1726 }
1727}
1728
1729impl PartialOrd for Ipv6Addr {
1730 #[inline]
1731 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1732 Some(self.cmp(other))
1733 }
1734}
1735
1736impl PartialOrd<Ipv6Addr> for IpAddr {
1737 #[inline]
1738 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
1739 match self {
1740 IpAddr::V4(_) => Some(Ordering::Less),
1741 IpAddr::V6(v6) => v6.partial_cmp(other),
1742 }
1743 }
1744}
1745
1746impl PartialOrd<IpAddr> for Ipv6Addr {
1747 #[inline]
1748 fn partial_cmp(&self, other: &IpAddr) -> Option<Ordering> {
1749 match other {
1750 IpAddr::V4(_) => Some(Ordering::Greater),
1751 IpAddr::V6(v6) => self.partial_cmp(v6),
1752 }
1753 }
1754}
1755
1756impl Ord for Ipv6Addr {
1757 #[inline]
1758 fn cmp(&self, other: &Ipv6Addr) -> Ordering {
1759 self.segments().cmp(&other.segments())
1760 }
1761}
1762
1763impl From<Ipv6Addr> for u128 {
1764 /// Convert an `Ipv6Addr` into a host byte order `u128`.
1765 ///
1766 /// # Examples
1767 ///
1768 /// ```
1769 /// use core_net::Ipv6Addr;
1770 ///
1771 /// let addr = Ipv6Addr::new(
1772 /// 0x1020, 0x3040, 0x5060, 0x7080,
1773 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1774 /// );
1775 /// assert_eq!(0x102030405060708090A0B0C0D0E0F00D_u128, u128::from(addr));
1776 /// ```
1777 #[inline]
1778 fn from(ip: Ipv6Addr) -> u128 {
1779 u128::from_be_bytes(ip.octets)
1780 }
1781}
1782
1783impl From<u128> for Ipv6Addr {
1784 /// Convert a host byte order `u128` into an `Ipv6Addr`.
1785 ///
1786 /// # Examples
1787 ///
1788 /// ```
1789 /// use core_net::Ipv6Addr;
1790 ///
1791 /// let addr = Ipv6Addr::from(0x102030405060708090A0B0C0D0E0F00D_u128);
1792 /// assert_eq!(
1793 /// Ipv6Addr::new(
1794 /// 0x1020, 0x3040, 0x5060, 0x7080,
1795 /// 0x90A0, 0xB0C0, 0xD0E0, 0xF00D,
1796 /// ),
1797 /// addr);
1798 /// ```
1799 #[inline]
1800 fn from(ip: u128) -> Ipv6Addr {
1801 Ipv6Addr::from(ip.to_be_bytes())
1802 }
1803}
1804
1805impl From<[u8; 16]> for Ipv6Addr {
1806 /// Creates an `Ipv6Addr` from a sixteen element byte array.
1807 ///
1808 /// # Examples
1809 ///
1810 /// ```
1811 /// use core_net::Ipv6Addr;
1812 ///
1813 /// let addr = Ipv6Addr::from([
1814 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1815 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1816 /// ]);
1817 /// assert_eq!(
1818 /// Ipv6Addr::new(
1819 /// 0x1918, 0x1716,
1820 /// 0x1514, 0x1312,
1821 /// 0x1110, 0x0f0e,
1822 /// 0x0d0c, 0x0b0a
1823 /// ),
1824 /// addr
1825 /// );
1826 /// ```
1827 #[inline]
1828 fn from(octets: [u8; 16]) -> Ipv6Addr {
1829 Ipv6Addr { octets }
1830 }
1831}
1832
1833impl From<[u16; 8]> for Ipv6Addr {
1834 /// Creates an `Ipv6Addr` from an eight element 16-bit array.
1835 ///
1836 /// # Examples
1837 ///
1838 /// ```
1839 /// use core_net::Ipv6Addr;
1840 ///
1841 /// let addr = Ipv6Addr::from([
1842 /// 525u16, 524u16, 523u16, 522u16,
1843 /// 521u16, 520u16, 519u16, 518u16,
1844 /// ]);
1845 /// assert_eq!(
1846 /// Ipv6Addr::new(
1847 /// 0x20d, 0x20c,
1848 /// 0x20b, 0x20a,
1849 /// 0x209, 0x208,
1850 /// 0x207, 0x206
1851 /// ),
1852 /// addr
1853 /// );
1854 /// ```
1855 #[inline]
1856 fn from(segments: [u16; 8]) -> Ipv6Addr {
1857 let [a, b, c, d, e, f, g, h] = segments;
1858 Ipv6Addr::new(a, b, c, d, e, f, g, h)
1859 }
1860}
1861
1862impl From<[u8; 16]> for IpAddr {
1863 /// Creates an `IpAddr::V6` from a sixteen element byte array.
1864 ///
1865 /// # Examples
1866 ///
1867 /// ```
1868 /// use core_net::{IpAddr, Ipv6Addr};
1869 ///
1870 /// let addr = IpAddr::from([
1871 /// 25u8, 24u8, 23u8, 22u8, 21u8, 20u8, 19u8, 18u8,
1872 /// 17u8, 16u8, 15u8, 14u8, 13u8, 12u8, 11u8, 10u8,
1873 /// ]);
1874 /// assert_eq!(
1875 /// IpAddr::V6(Ipv6Addr::new(
1876 /// 0x1918, 0x1716,
1877 /// 0x1514, 0x1312,
1878 /// 0x1110, 0x0f0e,
1879 /// 0x0d0c, 0x0b0a
1880 /// )),
1881 /// addr
1882 /// );
1883 /// ```
1884 #[inline]
1885 fn from(octets: [u8; 16]) -> IpAddr {
1886 IpAddr::V6(Ipv6Addr::from(octets))
1887 }
1888}
1889
1890impl From<[u16; 8]> for IpAddr {
1891 /// Creates an `IpAddr::V6` from an eight element 16-bit array.
1892 ///
1893 /// # Examples
1894 ///
1895 /// ```
1896 /// use core_net::{IpAddr, Ipv6Addr};
1897 ///
1898 /// let addr = IpAddr::from([
1899 /// 525u16, 524u16, 523u16, 522u16,
1900 /// 521u16, 520u16, 519u16, 518u16,
1901 /// ]);
1902 /// assert_eq!(
1903 /// IpAddr::V6(Ipv6Addr::new(
1904 /// 0x20d, 0x20c,
1905 /// 0x20b, 0x20a,
1906 /// 0x209, 0x208,
1907 /// 0x207, 0x206
1908 /// )),
1909 /// addr
1910 /// );
1911 /// ```
1912 #[inline]
1913 fn from(segments: [u16; 8]) -> IpAddr {
1914 IpAddr::V6(Ipv6Addr::from(segments))
1915 }
1916}