1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![unstable(feature = "ip", reason = "extra functionality has not been \
12 scrutinized to the level that it should \
20 use net::{hton, ntoh};
21 use sys::net::netc as c;
22 use sys_common::{AsInner, FromInner};
24 /// An IP address, either an IPv4 or IPv6 address.
25 #[stable(feature = "ip_addr", since = "1.7.0")]
26 #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, PartialOrd, Ord)]
28 /// Representation of an IPv4 address.
29 #[stable(feature = "ip_addr", since = "1.7.0")]
30 V4(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv4Addr),
31 /// Representation of an IPv6 address.
32 #[stable(feature = "ip_addr", since = "1.7.0")]
33 V6(#[stable(feature = "ip_addr", since = "1.7.0")] Ipv6Addr),
36 /// Representation of an IPv4 address.
38 #[stable(feature = "rust1", since = "1.0.0")]
43 /// Representation of an IPv6 address.
45 #[stable(feature = "rust1", since = "1.0.0")]
50 #[allow(missing_docs)]
51 #[derive(Copy, PartialEq, Eq, Clone, Hash, Debug)]
52 pub enum Ipv6MulticastScope {
63 /// Returns true for the special 'unspecified' address ([IPv4], [IPv6]).
64 /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_unspecified
65 /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_unspecified
66 #[stable(feature = "ip_shared", since = "1.12.0")]
67 pub fn is_unspecified(&self) -> bool {
69 IpAddr::V4(ref a) => a.is_unspecified(),
70 IpAddr::V6(ref a) => a.is_unspecified(),
74 /// Returns true if this is a loopback address ([IPv4], [IPv6]).
75 /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_loopback
76 /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_loopback
77 #[stable(feature = "ip_shared", since = "1.12.0")]
78 pub fn is_loopback(&self) -> bool {
80 IpAddr::V4(ref a) => a.is_loopback(),
81 IpAddr::V6(ref a) => a.is_loopback(),
85 /// Returns true if the address appears to be globally routable ([IPv4], [IPv6]).
86 /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_global
87 /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_global
88 pub fn is_global(&self) -> bool {
90 IpAddr::V4(ref a) => a.is_global(),
91 IpAddr::V6(ref a) => a.is_global(),
95 /// Returns true if this is a multicast address ([IPv4], [IPv6]).
96 /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_multicast
97 /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_multicast
98 #[stable(feature = "ip_shared", since = "1.12.0")]
99 pub fn is_multicast(&self) -> bool {
101 IpAddr::V4(ref a) => a.is_multicast(),
102 IpAddr::V6(ref a) => a.is_multicast(),
106 /// Returns true if this address is in a range designated for documentation ([IPv4], [IPv6]).
107 /// [IPv4]: ../../std/net/struct.Ipv4Addr.html#method.is_documentation
108 /// [IPv6]: ../../std/net/struct.Ipv6Addr.html#method.is_documentation
109 pub fn is_documentation(&self) -> bool {
111 IpAddr::V4(ref a) => a.is_documentation(),
112 IpAddr::V6(ref a) => a.is_documentation(),
118 /// Creates a new IPv4 address from four eight-bit octets.
120 /// The result will represent the IP address `a`.`b`.`c`.`d`.
121 #[stable(feature = "rust1", since = "1.0.0")]
122 pub fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr {
125 s_addr: hton(((a as u32) << 24) |
133 /// Returns the four eight-bit integers that make up this address.
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub fn octets(&self) -> [u8; 4] {
136 let bits = ntoh(self.inner.s_addr);
137 [(bits >> 24) as u8, (bits >> 16) as u8, (bits >> 8) as u8, bits as u8]
140 /// Returns true for the special 'unspecified' address (0.0.0.0).
142 /// This property is defined in _UNIX Network Programming, Second Edition_,
143 /// W. Richard Stevens, p. 891; see also [ip7]
144 /// [ip7][http://man7.org/linux/man-pages/man7/ip.7.html]
145 #[stable(feature = "ip_shared", since = "1.12.0")]
146 pub fn is_unspecified(&self) -> bool {
147 self.inner.s_addr == 0
150 /// Returns true if this is a loopback address (127.0.0.0/8).
152 /// This property is defined by [RFC 1122].
153 /// [RFC 1122]: https://tools.ietf.org/html/rfc1122
154 #[stable(since = "1.7.0", feature = "ip_17")]
155 pub fn is_loopback(&self) -> bool {
156 self.octets()[0] == 127
159 /// Returns true if this is a private address.
161 /// The private address ranges are defined in [RFC 1918] and include:
162 /// [RFC 1918]: https://tools.ietf.org/html/rfc1918
167 #[stable(since = "1.7.0", feature = "ip_17")]
168 pub fn is_private(&self) -> bool {
169 match (self.octets()[0], self.octets()[1]) {
171 (172, b) if b >= 16 && b <= 31 => true,
177 /// Returns true if the address is link-local (169.254.0.0/16).
179 /// This property is defined by [RFC 3927].
180 /// [RFC 3927]: https://tools.ietf.org/html/rfc3927
181 #[stable(since = "1.7.0", feature = "ip_17")]
182 pub fn is_link_local(&self) -> bool {
183 self.octets()[0] == 169 && self.octets()[1] == 254
186 /// Returns true if the address appears to be globally routable.
187 /// See [iana-ipv4-special-registry][ipv4-sr].
188 /// [ipv4-sr]: http://goo.gl/RaZ7lg
190 /// The following return false:
192 /// - private address (10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16)
193 /// - the loopback address (127.0.0.0/8)
194 /// - the link-local address (169.254.0.0/16)
195 /// - the broadcast address (255.255.255.255/32)
196 /// - test addresses used for documentation (192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24)
197 /// - the unspecified address (0.0.0.0)
198 pub fn is_global(&self) -> bool {
199 !self.is_private() && !self.is_loopback() && !self.is_link_local() &&
200 !self.is_broadcast() && !self.is_documentation() && !self.is_unspecified()
203 /// Returns true if this is a multicast address (224.0.0.0/4).
205 /// Multicast addresses have a most significant octet between 224 and 239,
206 /// and is defined by [RFC 5771].
207 /// [RFC 5771]: https://tools.ietf.org/html/rfc5771
208 #[stable(since = "1.7.0", feature = "ip_17")]
209 pub fn is_multicast(&self) -> bool {
210 self.octets()[0] >= 224 && self.octets()[0] <= 239
213 /// Returns true if this is a broadcast address (255.255.255.255).
215 /// A broadcast address has all octets set to 255 as defined in [RFC 919].
216 /// [RFC 919]: https://tools.ietf.org/html/rfc919
217 #[stable(since = "1.7.0", feature = "ip_17")]
218 pub fn is_broadcast(&self) -> bool {
219 self.octets()[0] == 255 && self.octets()[1] == 255 &&
220 self.octets()[2] == 255 && self.octets()[3] == 255
223 /// Returns true if this address is in a range designated for documentation.
225 /// This is defined in [RFC 5737]:
226 /// [RFC 5737]: https://tools.ietf.org/html/rfc5737
228 /// - 192.0.2.0/24 (TEST-NET-1)
229 /// - 198.51.100.0/24 (TEST-NET-2)
230 /// - 203.0.113.0/24 (TEST-NET-3)
231 #[stable(since = "1.7.0", feature = "ip_17")]
232 pub fn is_documentation(&self) -> bool {
233 match(self.octets()[0], self.octets()[1], self.octets()[2], self.octets()[3]) {
234 (192, 0, 2, _) => true,
235 (198, 51, 100, _) => true,
236 (203, 0, 113, _) => true,
241 /// Converts this address to an IPv4-compatible IPv6 address.
243 /// a.b.c.d becomes ::a.b.c.d
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub fn to_ipv6_compatible(&self) -> Ipv6Addr {
246 Ipv6Addr::new(0, 0, 0, 0, 0, 0,
247 ((self.octets()[0] as u16) << 8) | self.octets()[1] as u16,
248 ((self.octets()[2] as u16) << 8) | self.octets()[3] as u16)
251 /// Converts this address to an IPv4-mapped IPv6 address.
253 /// a.b.c.d becomes ::ffff:a.b.c.d
254 #[stable(feature = "rust1", since = "1.0.0")]
255 pub fn to_ipv6_mapped(&self) -> Ipv6Addr {
256 Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff,
257 ((self.octets()[0] as u16) << 8) | self.octets()[1] as u16,
258 ((self.octets()[2] as u16) << 8) | self.octets()[3] as u16)
262 #[stable(feature = "rust1", since = "1.0.0")]
264 impl fmt::Display for IpAddr {
265 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
267 IpAddr::V4(ref a) => a.fmt(fmt),
268 IpAddr::V6(ref a) => a.fmt(fmt),
273 #[stable(feature = "rust1", since = "1.0.0")]
274 impl fmt::Display for Ipv4Addr {
275 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
276 let octets = self.octets();
277 write!(fmt, "{}.{}.{}.{}", octets[0], octets[1], octets[2], octets[3])
281 #[stable(feature = "rust1", since = "1.0.0")]
282 impl fmt::Debug for Ipv4Addr {
283 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
284 fmt::Display::fmt(self, fmt)
288 #[stable(feature = "rust1", since = "1.0.0")]
289 impl Clone for Ipv4Addr {
290 fn clone(&self) -> Ipv4Addr { *self }
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl PartialEq for Ipv4Addr {
295 fn eq(&self, other: &Ipv4Addr) -> bool {
296 self.inner.s_addr == other.inner.s_addr
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl Eq for Ipv4Addr {}
303 #[stable(feature = "rust1", since = "1.0.0")]
304 impl hash::Hash for Ipv4Addr {
305 fn hash<H: hash::Hasher>(&self, s: &mut H) {
306 self.inner.s_addr.hash(s)
310 #[stable(feature = "rust1", since = "1.0.0")]
311 impl PartialOrd for Ipv4Addr {
312 fn partial_cmp(&self, other: &Ipv4Addr) -> Option<Ordering> {
313 Some(self.cmp(other))
317 #[stable(feature = "rust1", since = "1.0.0")]
318 impl Ord for Ipv4Addr {
319 fn cmp(&self, other: &Ipv4Addr) -> Ordering {
320 ntoh(self.inner.s_addr).cmp(&ntoh(other.inner.s_addr))
324 impl AsInner<c::in_addr> for Ipv4Addr {
325 fn as_inner(&self) -> &c::in_addr { &self.inner }
327 impl FromInner<c::in_addr> for Ipv4Addr {
328 fn from_inner(addr: c::in_addr) -> Ipv4Addr {
329 Ipv4Addr { inner: addr }
333 #[stable(feature = "ip_u32", since = "1.1.0")]
334 impl From<Ipv4Addr> for u32 {
335 fn from(ip: Ipv4Addr) -> u32 {
336 let ip = ip.octets();
337 ((ip[0] as u32) << 24) + ((ip[1] as u32) << 16) + ((ip[2] as u32) << 8) + (ip[3] as u32)
341 #[stable(feature = "ip_u32", since = "1.1.0")]
342 impl From<u32> for Ipv4Addr {
343 fn from(ip: u32) -> Ipv4Addr {
344 Ipv4Addr::new((ip >> 24) as u8, (ip >> 16) as u8, (ip >> 8) as u8, ip as u8)
348 #[stable(feature = "from_slice_v4", since = "1.9.0")]
349 impl From<[u8; 4]> for Ipv4Addr {
350 fn from(octets: [u8; 4]) -> Ipv4Addr {
351 Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3])
356 /// Creates a new IPv6 address from eight 16-bit segments.
358 /// The result will represent the IP address a:b:c:d:e:f:g:h.
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn new(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16,
361 h: u16) -> Ipv6Addr {
362 let mut addr: c::in6_addr = unsafe { mem::zeroed() };
363 addr.s6_addr = [(a >> 8) as u8, a as u8,
364 (b >> 8) as u8, b as u8,
365 (c >> 8) as u8, c as u8,
366 (d >> 8) as u8, d as u8,
367 (e >> 8) as u8, e as u8,
368 (f >> 8) as u8, f as u8,
369 (g >> 8) as u8, g as u8,
370 (h >> 8) as u8, h as u8];
371 Ipv6Addr { inner: addr }
374 /// Returns the eight 16-bit segments that make up this address.
375 #[stable(feature = "rust1", since = "1.0.0")]
376 pub fn segments(&self) -> [u16; 8] {
377 let arr = &self.inner.s6_addr;
379 (arr[0] as u16) << 8 | (arr[1] as u16),
380 (arr[2] as u16) << 8 | (arr[3] as u16),
381 (arr[4] as u16) << 8 | (arr[5] as u16),
382 (arr[6] as u16) << 8 | (arr[7] as u16),
383 (arr[8] as u16) << 8 | (arr[9] as u16),
384 (arr[10] as u16) << 8 | (arr[11] as u16),
385 (arr[12] as u16) << 8 | (arr[13] as u16),
386 (arr[14] as u16) << 8 | (arr[15] as u16),
390 /// Returns true for the special 'unspecified' address (::).
392 /// This property is defined in [RFC 4291].
393 /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
394 #[stable(since = "1.7.0", feature = "ip_17")]
395 pub fn is_unspecified(&self) -> bool {
396 self.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
399 /// Returns true if this is a loopback address (::1).
401 /// This property is defined in [RFC 4291].
402 /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
403 #[stable(since = "1.7.0", feature = "ip_17")]
404 pub fn is_loopback(&self) -> bool {
405 self.segments() == [0, 0, 0, 0, 0, 0, 0, 1]
408 /// Returns true if the address appears to be globally routable.
410 /// The following return false:
412 /// - the loopback address
413 /// - link-local, site-local, and unique local unicast addresses
414 /// - interface-, link-, realm-, admin- and site-local multicast addresses
415 pub fn is_global(&self) -> bool {
416 match self.multicast_scope() {
417 Some(Ipv6MulticastScope::Global) => true,
418 None => self.is_unicast_global(),
423 /// Returns true if this is a unique local address (fc00::/7).
425 /// This property is defined in [RFC 4193].
426 /// [RFC 4193]: https://tools.ietf.org/html/rfc4193
427 pub fn is_unique_local(&self) -> bool {
428 (self.segments()[0] & 0xfe00) == 0xfc00
431 /// Returns true if the address is unicast and link-local (fe80::/10).
433 /// This property is defined in [RFC 4291].
434 /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
435 pub fn is_unicast_link_local(&self) -> bool {
436 (self.segments()[0] & 0xffc0) == 0xfe80
439 /// Returns true if this is a deprecated unicast site-local address
441 pub fn is_unicast_site_local(&self) -> bool {
442 (self.segments()[0] & 0xffc0) == 0xfec0
445 /// Returns true if this is an address reserved for documentation
448 /// This property is defined in [RFC 3849].
449 /// [RFC 3849]: https://tools.ietf.org/html/rfc3849
450 pub fn is_documentation(&self) -> bool {
451 (self.segments()[0] == 0x2001) && (self.segments()[1] == 0xdb8)
454 /// Returns true if the address is a globally routable unicast address.
456 /// The following return false:
458 /// - the loopback address
459 /// - the link-local addresses
460 /// - the (deprecated) site-local addresses
461 /// - unique local addresses
462 /// - the unspecified address
463 /// - the address range reserved for documentation
464 pub fn is_unicast_global(&self) -> bool {
466 && !self.is_loopback() && !self.is_unicast_link_local()
467 && !self.is_unicast_site_local() && !self.is_unique_local()
468 && !self.is_unspecified() && !self.is_documentation()
471 /// Returns the address's multicast scope if the address is multicast.
472 pub fn multicast_scope(&self) -> Option<Ipv6MulticastScope> {
473 if self.is_multicast() {
474 match self.segments()[0] & 0x000f {
475 1 => Some(Ipv6MulticastScope::InterfaceLocal),
476 2 => Some(Ipv6MulticastScope::LinkLocal),
477 3 => Some(Ipv6MulticastScope::RealmLocal),
478 4 => Some(Ipv6MulticastScope::AdminLocal),
479 5 => Some(Ipv6MulticastScope::SiteLocal),
480 8 => Some(Ipv6MulticastScope::OrganizationLocal),
481 14 => Some(Ipv6MulticastScope::Global),
489 /// Returns true if this is a multicast address (ff00::/8).
491 /// This property is defined by [RFC 4291].
492 /// [RFC 4291]: https://tools.ietf.org/html/rfc4291
493 #[stable(since = "1.7.0", feature = "ip_17")]
494 pub fn is_multicast(&self) -> bool {
495 (self.segments()[0] & 0xff00) == 0xff00
498 /// Converts this address to an IPv4 address. Returns None if this address is
499 /// neither IPv4-compatible or IPv4-mapped.
501 /// ::a.b.c.d and ::ffff:a.b.c.d become a.b.c.d
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn to_ipv4(&self) -> Option<Ipv4Addr> {
504 match self.segments() {
505 [0, 0, 0, 0, 0, f, g, h] if f == 0 || f == 0xffff => {
506 Some(Ipv4Addr::new((g >> 8) as u8, g as u8,
507 (h >> 8) as u8, h as u8))
513 /// Returns the sixteen eight-bit integers the IPv6 address consists of.
514 #[stable(feature = "ipv6_to_octets", since = "1.12.0")]
515 pub fn octets(&self) -> [u8; 16] {
520 #[stable(feature = "rust1", since = "1.0.0")]
521 impl fmt::Display for Ipv6Addr {
522 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
523 match self.segments() {
524 // We need special cases for :: and ::1, otherwise they're formatted
526 [0, 0, 0, 0, 0, 0, 0, 0] => write!(fmt, "::"),
527 [0, 0, 0, 0, 0, 0, 0, 1] => write!(fmt, "::1"),
528 // Ipv4 Compatible address
529 [0, 0, 0, 0, 0, 0, g, h] => {
530 write!(fmt, "::{}.{}.{}.{}", (g >> 8) as u8, g as u8,
531 (h >> 8) as u8, h as u8)
533 // Ipv4-Mapped address
534 [0, 0, 0, 0, 0, 0xffff, g, h] => {
535 write!(fmt, "::ffff:{}.{}.{}.{}", (g >> 8) as u8, g as u8,
536 (h >> 8) as u8, h as u8)
539 fn find_zero_slice(segments: &[u16; 8]) -> (usize, usize) {
540 let mut longest_span_len = 0;
541 let mut longest_span_at = 0;
542 let mut cur_span_len = 0;
543 let mut cur_span_at = 0;
546 if segments[i] == 0 {
547 if cur_span_len == 0 {
553 if cur_span_len > longest_span_len {
554 longest_span_len = cur_span_len;
555 longest_span_at = cur_span_at;
563 (longest_span_at, longest_span_len)
566 let (zeros_at, zeros_len) = find_zero_slice(&self.segments());
569 fn fmt_subslice(segments: &[u16], fmt: &mut fmt::Formatter) -> fmt::Result {
570 if !segments.is_empty() {
571 write!(fmt, "{:x}", segments[0])?;
572 for &seg in &segments[1..] {
573 write!(fmt, ":{:x}", seg)?;
579 fmt_subslice(&self.segments()[..zeros_at], fmt)?;
580 fmt.write_str("::")?;
581 fmt_subslice(&self.segments()[zeros_at + zeros_len..], fmt)
583 let &[a, b, c, d, e, f, g, h] = &self.segments();
584 write!(fmt, "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}",
585 a, b, c, d, e, f, g, h)
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl fmt::Debug for Ipv6Addr {
594 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
595 fmt::Display::fmt(self, fmt)
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl Clone for Ipv6Addr {
601 fn clone(&self) -> Ipv6Addr { *self }
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl PartialEq for Ipv6Addr {
606 fn eq(&self, other: &Ipv6Addr) -> bool {
607 self.inner.s6_addr == other.inner.s6_addr
611 #[stable(feature = "rust1", since = "1.0.0")]
612 impl Eq for Ipv6Addr {}
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl hash::Hash for Ipv6Addr {
616 fn hash<H: hash::Hasher>(&self, s: &mut H) {
617 self.inner.s6_addr.hash(s)
621 #[stable(feature = "rust1", since = "1.0.0")]
622 impl PartialOrd for Ipv6Addr {
623 fn partial_cmp(&self, other: &Ipv6Addr) -> Option<Ordering> {
624 Some(self.cmp(other))
628 #[stable(feature = "rust1", since = "1.0.0")]
629 impl Ord for Ipv6Addr {
630 fn cmp(&self, other: &Ipv6Addr) -> Ordering {
631 self.segments().cmp(&other.segments())
635 impl AsInner<c::in6_addr> for Ipv6Addr {
636 fn as_inner(&self) -> &c::in6_addr { &self.inner }
638 impl FromInner<c::in6_addr> for Ipv6Addr {
639 fn from_inner(addr: c::in6_addr) -> Ipv6Addr {
640 Ipv6Addr { inner: addr }
644 #[stable(feature = "ipv6_from_octets", since = "1.9.0")]
645 impl From<[u8; 16]> for Ipv6Addr {
646 fn from(octets: [u8; 16]) -> Ipv6Addr {
647 let mut inner: c::in6_addr = unsafe { mem::zeroed() };
648 inner.s6_addr = octets;
649 Ipv6Addr::from_inner(inner)
653 // Tests for this module
657 use net::Ipv6MulticastScope::*;
658 use net::test::{tsa, sa6, sa4};
661 fn test_from_str_ipv4() {
662 assert_eq!(Ok(Ipv4Addr::new(127, 0, 0, 1)), "127.0.0.1".parse());
663 assert_eq!(Ok(Ipv4Addr::new(255, 255, 255, 255)), "255.255.255.255".parse());
664 assert_eq!(Ok(Ipv4Addr::new(0, 0, 0, 0)), "0.0.0.0".parse());
667 let none: Option<Ipv4Addr> = "256.0.0.1".parse().ok();
668 assert_eq!(None, none);
670 let none: Option<Ipv4Addr> = "255.0.0".parse().ok();
671 assert_eq!(None, none);
673 let none: Option<Ipv4Addr> = "255.0.0.1.2".parse().ok();
674 assert_eq!(None, none);
675 // no number between dots
676 let none: Option<Ipv4Addr> = "255.0..1".parse().ok();
677 assert_eq!(None, none);
681 fn test_from_str_ipv6() {
682 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "0:0:0:0:0:0:0:0".parse());
683 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "0:0:0:0:0:0:0:1".parse());
685 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "::1".parse());
686 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "::".parse());
688 assert_eq!(Ok(Ipv6Addr::new(0x2a02, 0x6b8, 0, 0, 0, 0, 0x11, 0x11)),
689 "2a02:6b8::11:11".parse());
692 let none: Option<Ipv6Addr> = "::00000".parse().ok();
693 assert_eq!(None, none);
695 let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7".parse().ok();
696 assert_eq!(None, none);
698 let none: Option<Ipv6Addr> = "1:2:3:4:5:6:7:8:9".parse().ok();
699 assert_eq!(None, none);
701 let none: Option<Ipv6Addr> = "1:2:::6:7:8".parse().ok();
702 assert_eq!(None, none);
704 let none: Option<Ipv6Addr> = "1:2::6::8".parse().ok();
705 assert_eq!(None, none);
709 fn test_from_str_ipv4_in_ipv6() {
710 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 545)),
711 "::192.0.2.33".parse());
712 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0xFFFF, 49152, 545)),
713 "::FFFF:192.0.2.33".parse());
714 assert_eq!(Ok(Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 49152, 545)),
715 "64:ff9b::192.0.2.33".parse());
716 assert_eq!(Ok(Ipv6Addr::new(0x2001, 0xdb8, 0x122, 0xc000, 0x2, 0x2100, 49152, 545)),
717 "2001:db8:122:c000:2:2100:192.0.2.33".parse());
720 let none: Option<Ipv4Addr> = "::127.0.0.1:".parse().ok();
721 assert_eq!(None, none);
723 let none: Option<Ipv6Addr> = "1.2.3.4.5:127.0.0.1".parse().ok();
724 assert_eq!(None, none);
726 let none: Option<Ipv6Addr> = "1.2.3.4.5:6:7:127.0.0.1".parse().ok();
727 assert_eq!(None, none);
731 fn test_from_str_socket_addr() {
732 assert_eq!(Ok(sa4(Ipv4Addr::new(77, 88, 21, 11), 80)),
733 "77.88.21.11:80".parse());
734 assert_eq!(Ok(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80)),
735 "77.88.21.11:80".parse());
736 assert_eq!(Ok(sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53)),
737 "[2a02:6b8:0:1::1]:53".parse());
738 assert_eq!(Ok(SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1,
739 0, 0, 0, 1), 53, 0, 0)),
740 "[2a02:6b8:0:1::1]:53".parse());
741 assert_eq!(Ok(sa6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x7F00, 1), 22)),
742 "[::127.0.0.1]:22".parse());
743 assert_eq!(Ok(SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0,
744 0x7F00, 1), 22, 0, 0)),
745 "[::127.0.0.1]:22".parse());
748 let none: Option<SocketAddr> = "127.0.0.1".parse().ok();
749 assert_eq!(None, none);
751 let none: Option<SocketAddr> = "127.0.0.1:".parse().ok();
752 assert_eq!(None, none);
753 // wrong brackets around v4
754 let none: Option<SocketAddr> = "[127.0.0.1]:22".parse().ok();
755 assert_eq!(None, none);
757 let none: Option<SocketAddr> = "127.0.0.1:123456".parse().ok();
758 assert_eq!(None, none);
762 fn ipv6_addr_to_string() {
763 // ipv4-mapped address
764 let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280);
765 assert_eq!(a1.to_string(), "::ffff:192.0.2.128");
767 // ipv4-compatible address
768 let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x280);
769 assert_eq!(a1.to_string(), "::192.0.2.128");
771 // v6 address with no zero segments
772 assert_eq!(Ipv6Addr::new(8, 9, 10, 11, 12, 13, 14, 15).to_string(),
775 // reduce a single run of zeros
776 assert_eq!("ae::ffff:102:304",
777 Ipv6Addr::new(0xae, 0, 0, 0, 0, 0xffff, 0x0102, 0x0304).to_string());
779 // don't reduce just a single zero segment
780 assert_eq!("1:2:3:4:5:6:0:8",
781 Ipv6Addr::new(1, 2, 3, 4, 5, 6, 0, 8).to_string());
784 assert_eq!("::", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).to_string());
787 assert_eq!("::1", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_string());
790 assert_eq!("1::", Ipv6Addr::new(1, 0, 0, 0, 0, 0, 0, 0).to_string());
792 // two runs of zeros, second one is longer
793 assert_eq!("1:0:0:4::8", Ipv6Addr::new(1, 0, 0, 4, 0, 0, 0, 8).to_string());
795 // two runs of zeros, equal length
796 assert_eq!("1::4:5:0:0:8", Ipv6Addr::new(1, 0, 0, 4, 5, 0, 0, 8).to_string());
801 assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678),
802 Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_mapped());
803 assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678),
804 Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_compatible());
809 assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678).to_ipv4(),
810 Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
811 assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
812 Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
813 assert_eq!(Ipv6Addr::new(0, 0, 1, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
819 fn check4(octets: &[u8; 4], unspec: bool, loopback: bool,
820 global: bool, multicast: bool, documentation: bool) {
821 let ip = IpAddr::V4(Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]));
822 assert_eq!(ip.is_unspecified(), unspec);
823 assert_eq!(ip.is_loopback(), loopback);
824 assert_eq!(ip.is_global(), global);
825 assert_eq!(ip.is_multicast(), multicast);
826 assert_eq!(ip.is_documentation(), documentation);
829 fn check6(str_addr: &str, unspec: bool, loopback: bool,
830 global: bool, u_doc: bool, mcast: bool) {
831 let ip = IpAddr::V6(str_addr.parse().unwrap());
832 assert_eq!(ip.is_unspecified(), unspec);
833 assert_eq!(ip.is_loopback(), loopback);
834 assert_eq!(ip.is_global(), global);
835 assert_eq!(ip.is_documentation(), u_doc);
836 assert_eq!(ip.is_multicast(), mcast);
839 // address unspec loopbk global multicast doc
840 check4(&[0, 0, 0, 0], true, false, false, false, false);
841 check4(&[0, 0, 0, 1], false, false, true, false, false);
842 check4(&[0, 1, 0, 0], false, false, true, false, false);
843 check4(&[10, 9, 8, 7], false, false, false, false, false);
844 check4(&[127, 1, 2, 3], false, true, false, false, false);
845 check4(&[172, 31, 254, 253], false, false, false, false, false);
846 check4(&[169, 254, 253, 242], false, false, false, false, false);
847 check4(&[192, 0, 2, 183], false, false, false, false, true);
848 check4(&[192, 1, 2, 183], false, false, true, false, false);
849 check4(&[192, 168, 254, 253], false, false, false, false, false);
850 check4(&[198, 51, 100, 0], false, false, false, false, true);
851 check4(&[203, 0, 113, 0], false, false, false, false, true);
852 check4(&[203, 2, 113, 0], false, false, true, false, false);
853 check4(&[224, 0, 0, 0], false, false, true, true, false);
854 check4(&[239, 255, 255, 255], false, false, true, true, false);
855 check4(&[255, 255, 255, 255], false, false, false, false, false);
857 // address unspec loopbk global doc mcast
858 check6("::", true, false, false, false, false);
859 check6("::1", false, true, false, false, false);
860 check6("::0.0.0.2", false, false, true, false, false);
861 check6("1::", false, false, true, false, false);
862 check6("fc00::", false, false, false, false, false);
863 check6("fdff:ffff::", false, false, false, false, false);
864 check6("fe80:ffff::", false, false, false, false, false);
865 check6("febf:ffff::", false, false, false, false, false);
866 check6("fec0::", false, false, false, false, false);
867 check6("ff01::", false, false, false, false, true);
868 check6("ff02::", false, false, false, false, true);
869 check6("ff03::", false, false, false, false, true);
870 check6("ff04::", false, false, false, false, true);
871 check6("ff05::", false, false, false, false, true);
872 check6("ff08::", false, false, false, false, true);
873 check6("ff0e::", false, false, true, false, true);
874 check6("2001:db8:85a3::8a2e:370:7334", false, false, false, true, false);
875 check6("102:304:506:708:90a:b0c:d0e:f10", false, false, true, false, false);
879 fn ipv4_properties() {
880 fn check(octets: &[u8; 4], unspec: bool, loopback: bool,
881 private: bool, link_local: bool, global: bool,
882 multicast: bool, broadcast: bool, documentation: bool) {
883 let ip = Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]);
884 assert_eq!(octets, &ip.octets());
886 assert_eq!(ip.is_unspecified(), unspec);
887 assert_eq!(ip.is_loopback(), loopback);
888 assert_eq!(ip.is_private(), private);
889 assert_eq!(ip.is_link_local(), link_local);
890 assert_eq!(ip.is_global(), global);
891 assert_eq!(ip.is_multicast(), multicast);
892 assert_eq!(ip.is_broadcast(), broadcast);
893 assert_eq!(ip.is_documentation(), documentation);
896 // address unspec loopbk privt linloc global multicast brdcast doc
897 check(&[0, 0, 0, 0], true, false, false, false, false, false, false, false);
898 check(&[0, 0, 0, 1], false, false, false, false, true, false, false, false);
899 check(&[0, 1, 0, 0], false, false, false, false, true, false, false, false);
900 check(&[10, 9, 8, 7], false, false, true, false, false, false, false, false);
901 check(&[127, 1, 2, 3], false, true, false, false, false, false, false, false);
902 check(&[172, 31, 254, 253], false, false, true, false, false, false, false, false);
903 check(&[169, 254, 253, 242], false, false, false, true, false, false, false, false);
904 check(&[192, 0, 2, 183], false, false, false, false, false, false, false, true);
905 check(&[192, 1, 2, 183], false, false, false, false, true, false, false, false);
906 check(&[192, 168, 254, 253], false, false, true, false, false, false, false, false);
907 check(&[198, 51, 100, 0], false, false, false, false, false, false, false, true);
908 check(&[203, 0, 113, 0], false, false, false, false, false, false, false, true);
909 check(&[203, 2, 113, 0], false, false, false, false, true, false, false, false);
910 check(&[224, 0, 0, 0], false, false, false, false, true, true, false, false);
911 check(&[239, 255, 255, 255], false, false, false, false, true, true, false, false);
912 check(&[255, 255, 255, 255], false, false, false, false, false, false, true, false);
916 fn ipv6_properties() {
917 fn check(str_addr: &str, octets: &[u8; 16], unspec: bool, loopback: bool,
918 unique_local: bool, global: bool,
919 u_link_local: bool, u_site_local: bool, u_global: bool, u_doc: bool,
920 m_scope: Option<Ipv6MulticastScope>) {
921 let ip: Ipv6Addr = str_addr.parse().unwrap();
922 assert_eq!(str_addr, ip.to_string());
923 assert_eq!(&ip.octets(), octets);
924 assert_eq!(Ipv6Addr::from(*octets), ip);
926 assert_eq!(ip.is_unspecified(), unspec);
927 assert_eq!(ip.is_loopback(), loopback);
928 assert_eq!(ip.is_unique_local(), unique_local);
929 assert_eq!(ip.is_global(), global);
930 assert_eq!(ip.is_unicast_link_local(), u_link_local);
931 assert_eq!(ip.is_unicast_site_local(), u_site_local);
932 assert_eq!(ip.is_unicast_global(), u_global);
933 assert_eq!(ip.is_documentation(), u_doc);
934 assert_eq!(ip.multicast_scope(), m_scope);
935 assert_eq!(ip.is_multicast(), m_scope.is_some());
938 // unspec loopbk uniqlo global unill unisl uniglo doc mscope
939 check("::", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
940 true, false, false, false, false, false, false, false, None);
941 check("::1", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
942 false, true, false, false, false, false, false, false, None);
943 check("::0.0.0.2", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2],
944 false, false, false, true, false, false, true, false, None);
945 check("1::", &[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
946 false, false, false, true, false, false, true, false, None);
947 check("fc00::", &[0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
948 false, false, true, false, false, false, false, false, None);
949 check("fdff:ffff::", &[0xfd, 0xff, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
950 false, false, true, false, false, false, false, false, None);
951 check("fe80:ffff::", &[0xfe, 0x80, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
952 false, false, false, false, true, false, false, false, None);
953 check("febf:ffff::", &[0xfe, 0xbf, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
954 false, false, false, false, true, false, false, false, None);
955 check("fec0::", &[0xfe, 0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
956 false, false, false, false, false, true, false, false, None);
957 check("ff01::", &[0xff, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
958 false, false, false, false, false, false, false, false, Some(InterfaceLocal));
959 check("ff02::", &[0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
960 false, false, false, false, false, false, false, false, Some(LinkLocal));
961 check("ff03::", &[0xff, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
962 false, false, false, false, false, false, false, false, Some(RealmLocal));
963 check("ff04::", &[0xff, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
964 false, false, false, false, false, false, false, false, Some(AdminLocal));
965 check("ff05::", &[0xff, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
966 false, false, false, false, false, false, false, false, Some(SiteLocal));
967 check("ff08::", &[0xff, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
968 false, false, false, false, false, false, false, false, Some(OrganizationLocal));
969 check("ff0e::", &[0xff, 0xe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
970 false, false, false, true, false, false, false, false, Some(Global));
971 check("2001:db8:85a3::8a2e:370:7334",
972 &[0x20, 1, 0xd, 0xb8, 0x85, 0xa3, 0, 0, 0, 0, 0x8a, 0x2e, 3, 0x70, 0x73, 0x34],
973 false, false, false, false, false, false, false, true, None);
974 check("102:304:506:708:90a:b0c:d0e:f10",
975 &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
976 false, false, false, true, false, false, true, false, None);
980 fn to_socket_addr_socketaddr() {
981 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 12345);
982 assert_eq!(Ok(vec![a]), tsa(a));
986 fn test_ipv4_to_int() {
987 let a = Ipv4Addr::new(127, 0, 0, 1);
988 assert_eq!(u32::from(a), 2130706433);
992 fn test_int_to_ipv4() {
993 let a = Ipv4Addr::new(127, 0, 0, 1);
994 assert_eq!(Ipv4Addr::from(2130706433), a);
998 fn ipv4_from_u32_slice() {
999 assert_eq!(Ipv4Addr::from([127, 0, 0, 1]), Ipv4Addr::new(127, 0, 0, 1))
1004 assert!(Ipv4Addr::new(100, 64, 3, 3) < Ipv4Addr::new(192, 0, 2, 2));
1005 assert!("2001:db8:f00::1002".parse::<Ipv6Addr>().unwrap() <
1006 "2001:db8:f00::2001".parse::<Ipv6Addr>().unwrap());