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