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.
15 use net::{ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
17 use sys::net::netc as c;
18 use sys_common::{FromInner, AsInner, IntoInner};
19 use sys_common::net::LookupHost;
25 /// An internet socket address, either IPv4 or IPv6.
27 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
28 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
29 /// [`SocketAddrV6`]'s respective documentation for more details.
31 /// The size of a `SocketAddr` instance may vary depending on the target operating
34 /// [IP address]: ../../std/net/enum.IpAddr.html
35 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
36 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
41 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
43 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
45 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
46 /// assert_eq!(socket.port(), 8080);
47 /// assert_eq!(socket.is_ipv4(), true);
49 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
50 #[stable(feature = "rust1", since = "1.0.0")]
52 /// An IPv4 socket address.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
55 /// An IPv6 socket address.
56 #[stable(feature = "rust1", since = "1.0.0")]
57 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
60 /// An IPv4 socket address.
62 /// IPv4 socket addresses consist of an [IPv4 address] and a 16-bit port number, as
63 /// stated in [IETF RFC 793].
65 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
67 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
70 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
71 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
72 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
77 /// use std::net::{Ipv4Addr, SocketAddrV4};
79 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
81 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
82 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
83 /// assert_eq!(socket.port(), 8080);
86 #[stable(feature = "rust1", since = "1.0.0")]
87 pub struct SocketAddrV4 { inner: c::sockaddr_in }
89 /// An IPv6 socket address.
91 /// IPv6 socket addresses consist of an [Ipv6 address], a 16-bit port number, as well
92 /// as fields containing the traffic class, the flow label, and a scope identifier
93 /// (see [IETF RFC 2553, Section 3.3] for more details).
95 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
97 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
100 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
101 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
102 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
107 /// use std::net::{Ipv6Addr, SocketAddrV6};
109 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
111 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
112 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
113 /// assert_eq!(socket.port(), 8080);
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
120 /// Creates a new socket address from an [IP address] and a port number.
122 /// [IP address]: ../../std/net/enum.IpAddr.html
127 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
129 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
130 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
131 /// assert_eq!(socket.port(), 8080);
133 #[stable(feature = "ip_addr", since = "1.7.0")]
134 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
136 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
137 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
141 /// Returns the IP address associated with this socket address.
146 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
148 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
149 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
151 #[stable(feature = "ip_addr", since = "1.7.0")]
152 pub fn ip(&self) -> IpAddr {
154 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
155 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
159 /// Changes the IP address associated with this socket address.
164 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
166 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
167 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
168 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
170 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
171 pub fn set_ip(&mut self, new_ip: IpAddr) {
172 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
173 match (self, new_ip) {
174 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
175 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
176 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
180 /// Returns the port number associated with this socket address.
185 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
187 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
188 /// assert_eq!(socket.port(), 8080);
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn port(&self) -> u16 {
193 SocketAddr::V4(ref a) => a.port(),
194 SocketAddr::V6(ref a) => a.port(),
198 /// Changes the port number associated with this socket address.
203 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
205 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
206 /// socket.set_port(1025);
207 /// assert_eq!(socket.port(), 1025);
209 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
210 pub fn set_port(&mut self, new_port: u16) {
212 SocketAddr::V4(ref mut a) => a.set_port(new_port),
213 SocketAddr::V6(ref mut a) => a.set_port(new_port),
217 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
218 /// [IPv4 address], and [`false`] otherwise.
220 /// [`true`]: ../../std/primitive.bool.html
221 /// [`false`]: ../../std/primitive.bool.html
222 /// [IP address]: ../../std/net/enum.IpAddr.html
223 /// [IPv4 address]: ../../std/net/enum.IpAddr.html#variant.V4
228 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
231 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
232 /// assert_eq!(socket.is_ipv4(), true);
233 /// assert_eq!(socket.is_ipv6(), false);
236 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
237 pub fn is_ipv4(&self) -> bool {
239 SocketAddr::V4(_) => true,
240 SocketAddr::V6(_) => false,
244 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
245 /// [IPv6 address], and [`false`] otherwise.
247 /// [`true`]: ../../std/primitive.bool.html
248 /// [`false`]: ../../std/primitive.bool.html
249 /// [IP address]: ../../std/net/enum.IpAddr.html
250 /// [IPv6 address]: ../../std/net/enum.IpAddr.html#variant.V6
255 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
258 /// let socket = SocketAddr::new(
259 /// IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
260 /// assert_eq!(socket.is_ipv4(), false);
261 /// assert_eq!(socket.is_ipv6(), true);
264 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
265 pub fn is_ipv6(&self) -> bool {
267 SocketAddr::V4(_) => false,
268 SocketAddr::V6(_) => true,
274 /// Creates a new socket address from an [IPv4 address] and a port number.
276 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
281 /// use std::net::{SocketAddrV4, Ipv4Addr};
283 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
288 inner: c::sockaddr_in {
289 sin_family: c::AF_INET as c::sa_family_t,
290 sin_port: hton(port),
291 sin_addr: *ip.as_inner(),
292 .. unsafe { mem::zeroed() }
297 /// Returns the IP address associated with this socket address.
302 /// use std::net::{SocketAddrV4, Ipv4Addr};
304 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
305 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
307 #[stable(feature = "rust1", since = "1.0.0")]
308 pub fn ip(&self) -> &Ipv4Addr {
310 &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
314 /// Changes the IP address associated with this socket address.
319 /// use std::net::{SocketAddrV4, Ipv4Addr};
321 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
322 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
323 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
325 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
326 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
327 self.inner.sin_addr = *new_ip.as_inner()
330 /// Returns the port number associated with this socket address.
335 /// use std::net::{SocketAddrV4, Ipv4Addr};
337 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
338 /// assert_eq!(socket.port(), 8080);
340 #[stable(feature = "rust1", since = "1.0.0")]
341 pub fn port(&self) -> u16 {
342 ntoh(self.inner.sin_port)
345 /// Changes the port number associated with this socket address.
350 /// use std::net::{SocketAddrV4, Ipv4Addr};
352 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
353 /// socket.set_port(4242);
354 /// assert_eq!(socket.port(), 4242);
356 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
357 pub fn set_port(&mut self, new_port: u16) {
358 self.inner.sin_port = hton(new_port);
363 /// Creates a new socket address from an [IPv6 address], a 16-bit port number,
364 /// and the `flowinfo` and `scope_id` fields.
366 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
367 /// parameters, see [IETF RFC 2553, Section 3.3].
369 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
370 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
375 /// use std::net::{SocketAddrV6, Ipv6Addr};
377 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
383 inner: c::sockaddr_in6 {
384 sin6_family: c::AF_INET6 as c::sa_family_t,
385 sin6_port: hton(port),
386 sin6_addr: *ip.as_inner(),
387 sin6_flowinfo: flowinfo,
388 sin6_scope_id: scope_id,
389 .. unsafe { mem::zeroed() }
394 /// Returns the IP address associated with this socket address.
399 /// use std::net::{SocketAddrV6, Ipv6Addr};
401 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
402 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
404 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn ip(&self) -> &Ipv6Addr {
407 &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
411 /// Changes the IP address associated with this socket address.
416 /// use std::net::{SocketAddrV6, Ipv6Addr};
418 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
419 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
420 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
422 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
423 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
424 self.inner.sin6_addr = *new_ip.as_inner()
427 /// Returns the port number associated with this socket address.
432 /// use std::net::{SocketAddrV6, Ipv6Addr};
434 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
435 /// assert_eq!(socket.port(), 8080);
437 #[stable(feature = "rust1", since = "1.0.0")]
438 pub fn port(&self) -> u16 {
439 ntoh(self.inner.sin6_port)
442 /// Changes the port number associated with this socket address.
447 /// use std::net::{SocketAddrV6, Ipv6Addr};
449 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
450 /// socket.set_port(4242);
451 /// assert_eq!(socket.port(), 4242);
453 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
454 pub fn set_port(&mut self, new_port: u16) {
455 self.inner.sin6_port = hton(new_port);
458 /// Returns the flow information associated with this address.
460 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
461 /// as specified in [IETF RFC 2553, Section 3.3].
462 /// It combines information about the flow label and the traffic class as specified
463 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
465 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
466 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
467 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
468 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
473 /// use std::net::{SocketAddrV6, Ipv6Addr};
475 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
476 /// assert_eq!(socket.flowinfo(), 10);
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub fn flowinfo(&self) -> u32 {
480 self.inner.sin6_flowinfo
483 /// Changes the flow information associated with this socket address.
485 /// See the [`flowinfo`] method's documentation for more details.
487 /// [`flowinfo`]: #method.flowinfo
492 /// use std::net::{SocketAddrV6, Ipv6Addr};
494 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
495 /// socket.set_flowinfo(56);
496 /// assert_eq!(socket.flowinfo(), 56);
498 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
499 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
500 self.inner.sin6_flowinfo = new_flowinfo;
503 /// Returns the scope ID associated with this address.
505 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
506 /// as specified in [IETF RFC 2553, Section 3.3].
508 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
513 /// use std::net::{SocketAddrV6, Ipv6Addr};
515 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
516 /// assert_eq!(socket.scope_id(), 78);
518 #[stable(feature = "rust1", since = "1.0.0")]
519 pub fn scope_id(&self) -> u32 {
520 self.inner.sin6_scope_id
523 /// Change the scope ID associated with this socket address.
525 /// See the [`scope_id`] method's documentation for more details.
527 /// [`scope_id`]: #method.scope_id
532 /// use std::net::{SocketAddrV6, Ipv6Addr};
534 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
535 /// socket.set_scope_id(42);
536 /// assert_eq!(socket.scope_id(), 42);
538 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
539 pub fn set_scope_id(&mut self, new_scope_id: u32) {
540 self.inner.sin6_scope_id = new_scope_id;
544 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
545 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
546 SocketAddrV4 { inner: addr }
550 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
551 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
552 SocketAddrV6 { inner: addr }
556 #[stable(feature = "ip_from_ip", since = "1.16.0")]
557 impl From<SocketAddrV4> for SocketAddr {
558 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
559 fn from(sock4: SocketAddrV4) -> SocketAddr {
560 SocketAddr::V4(sock4)
564 #[stable(feature = "ip_from_ip", since = "1.16.0")]
565 impl From<SocketAddrV6> for SocketAddr {
566 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
567 fn from(sock6: SocketAddrV6) -> SocketAddr {
568 SocketAddr::V6(sock6)
572 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
573 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
574 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
576 /// This conversion creates a [`SocketAddr::V4`] for a [`IpAddr::V4`]
577 /// and creates a [`SocketAddr::V6`] for a [`IpAddr::V6`].
579 /// `u16` is treated as port of the newly created [`SocketAddr`].
580 fn from(pieces: (I, u16)) -> SocketAddr {
581 SocketAddr::new(pieces.0.into(), pieces.1)
585 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
586 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
588 SocketAddr::V4(ref a) => {
589 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
591 SocketAddr::V6(ref a) => {
592 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl fmt::Display for SocketAddr {
600 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
602 SocketAddr::V4(ref a) => a.fmt(f),
603 SocketAddr::V6(ref a) => a.fmt(f),
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl fmt::Display for SocketAddrV4 {
610 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
611 write!(f, "{}:{}", self.ip(), self.port())
615 #[stable(feature = "rust1", since = "1.0.0")]
616 impl fmt::Debug for SocketAddrV4 {
617 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
618 fmt::Display::fmt(self, fmt)
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl fmt::Display for SocketAddrV6 {
624 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
625 write!(f, "[{}]:{}", self.ip(), self.port())
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl fmt::Debug for SocketAddrV6 {
631 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
632 fmt::Display::fmt(self, fmt)
636 #[stable(feature = "rust1", since = "1.0.0")]
637 impl Clone for SocketAddrV4 {
638 fn clone(&self) -> SocketAddrV4 { *self }
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl Clone for SocketAddrV6 {
642 fn clone(&self) -> SocketAddrV6 { *self }
645 #[stable(feature = "rust1", since = "1.0.0")]
646 impl PartialEq for SocketAddrV4 {
647 fn eq(&self, other: &SocketAddrV4) -> bool {
648 self.inner.sin_port == other.inner.sin_port &&
649 self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
652 #[stable(feature = "rust1", since = "1.0.0")]
653 impl PartialEq for SocketAddrV6 {
654 fn eq(&self, other: &SocketAddrV6) -> bool {
655 self.inner.sin6_port == other.inner.sin6_port &&
656 self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
657 self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
658 self.inner.sin6_scope_id == other.inner.sin6_scope_id
661 #[stable(feature = "rust1", since = "1.0.0")]
662 impl Eq for SocketAddrV4 {}
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl Eq for SocketAddrV6 {}
666 #[stable(feature = "rust1", since = "1.0.0")]
667 impl hash::Hash for SocketAddrV4 {
668 fn hash<H: hash::Hasher>(&self, s: &mut H) {
669 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl hash::Hash for SocketAddrV6 {
674 fn hash<H: hash::Hasher>(&self, s: &mut H) {
675 (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
676 self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
680 /// A trait for objects which can be converted or resolved to one or more
681 /// [`SocketAddr`] values.
683 /// This trait is used for generic address resolution when constructing network
684 /// objects. By default it is implemented for the following types:
686 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
688 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
689 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
690 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
692 /// * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
693 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
696 /// * [`&str`]: the string should be either a string representation of a
697 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
698 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
700 /// This trait allows constructing network objects like [`TcpStream`] or
701 /// [`UdpSocket`] easily with values of various types for the bind/connection
702 /// address. It is needed because sometimes one type is more appropriate than
703 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
704 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
705 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
706 /// some other type (e.g. a string) just for it to be converted back to
707 /// [`SocketAddr`] in constructor methods is pointless.
709 /// Addresses returned by the operating system that are not IP addresses are
710 /// silently ignored.
712 /// [`FromStr`]: ../../std/str/trait.FromStr.html
713 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
714 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
715 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
716 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
717 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
718 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
719 /// [`&str`]: ../../std/primitive.str.html
720 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
721 /// [`to_socket_addrs`]: #tymethod.to_socket_addrs
722 /// [`UdpSocket`]: ../../std/net/struct.UdpSocket.html
723 /// [`u16`]: ../../std/primitive.u16.html
727 /// Creating a [`SocketAddr`] iterator that yields one item:
730 /// use std::net::{ToSocketAddrs, SocketAddr};
732 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
733 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
735 /// assert_eq!(Some(addr), addrs_iter.next());
736 /// assert!(addrs_iter.next().is_none());
739 /// Creating a [`SocketAddr`] iterator from a hostname:
742 /// use std::net::{SocketAddr, ToSocketAddrs};
744 /// // assuming 'localhost' resolves to 127.0.0.1
745 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
746 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
747 /// assert!(addrs_iter.next().is_none());
749 /// // assuming 'foo' does not resolve
750 /// assert!("foo:443".to_socket_addrs().is_err());
753 /// Creating a [`SocketAddr`] iterator that yields multiple items:
756 /// use std::net::{SocketAddr, ToSocketAddrs};
758 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
759 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
760 /// let addrs = vec![addr1, addr2];
762 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
764 /// assert_eq!(Some(addr1), addrs_iter.next());
765 /// assert_eq!(Some(addr2), addrs_iter.next());
766 /// assert!(addrs_iter.next().is_none());
769 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
770 /// socket address `&str` (missing the port):
774 /// use std::net::ToSocketAddrs;
776 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
777 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
780 /// [`TcpStream::connect`] is an example of an function that utilizes
781 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
785 /// use std::net::{TcpStream, Ipv4Addr};
787 /// let stream = TcpStream::connect(("127.0.0.1", 443));
789 /// let stream = TcpStream::connect("127.0.0.1:443");
791 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
794 /// [`TcpStream::connect`]: ../../std/net/struct.TcpStream.html#method.connect
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub trait ToSocketAddrs {
797 /// Returned iterator over socket addresses which this type may correspond
799 #[stable(feature = "rust1", since = "1.0.0")]
800 type Iter: Iterator<Item=SocketAddr>;
802 /// Converts this object to an iterator of resolved `SocketAddr`s.
804 /// The returned iterator may not actually yield any values depending on the
805 /// outcome of any resolution performed.
807 /// Note that this function may block the current thread while resolution is
809 #[stable(feature = "rust1", since = "1.0.0")]
810 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
813 #[stable(feature = "rust1", since = "1.0.0")]
814 impl ToSocketAddrs for SocketAddr {
815 type Iter = option::IntoIter<SocketAddr>;
816 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
817 Ok(Some(*self).into_iter())
821 #[stable(feature = "rust1", since = "1.0.0")]
822 impl ToSocketAddrs for SocketAddrV4 {
823 type Iter = option::IntoIter<SocketAddr>;
824 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
825 SocketAddr::V4(*self).to_socket_addrs()
829 #[stable(feature = "rust1", since = "1.0.0")]
830 impl ToSocketAddrs for SocketAddrV6 {
831 type Iter = option::IntoIter<SocketAddr>;
832 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
833 SocketAddr::V6(*self).to_socket_addrs()
837 #[stable(feature = "rust1", since = "1.0.0")]
838 impl ToSocketAddrs for (IpAddr, u16) {
839 type Iter = option::IntoIter<SocketAddr>;
840 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
841 let (ip, port) = *self;
843 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
844 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl ToSocketAddrs for (Ipv4Addr, u16) {
851 type Iter = option::IntoIter<SocketAddr>;
852 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
853 let (ip, port) = *self;
854 SocketAddrV4::new(ip, port).to_socket_addrs()
858 #[stable(feature = "rust1", since = "1.0.0")]
859 impl ToSocketAddrs for (Ipv6Addr, u16) {
860 type Iter = option::IntoIter<SocketAddr>;
861 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
862 let (ip, port) = *self;
863 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
867 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
869 let v: Vec<_> = lh.map(|mut a| { a.set_port(p); a }).collect();
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<'a> ToSocketAddrs for (&'a str, u16) {
875 type Iter = vec::IntoIter<SocketAddr>;
876 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
877 let (host, port) = *self;
879 // try to parse the host as a regular IP address first
880 if let Ok(addr) = host.parse::<Ipv4Addr>() {
881 let addr = SocketAddrV4::new(addr, port);
882 return Ok(vec![SocketAddr::V4(addr)].into_iter())
884 if let Ok(addr) = host.parse::<Ipv6Addr>() {
885 let addr = SocketAddrV6::new(addr, port, 0, 0);
886 return Ok(vec![SocketAddr::V6(addr)].into_iter())
889 resolve_socket_addr((host, port).try_into()?)
893 // accepts strings like 'localhost:12345'
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl ToSocketAddrs for str {
896 type Iter = vec::IntoIter<SocketAddr>;
897 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
898 // try to parse as a regular SocketAddr first
899 if let Some(addr) = self.parse().ok() {
900 return Ok(vec![addr].into_iter());
903 resolve_socket_addr(self.try_into()?)
907 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
908 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
909 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
911 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
912 Ok(self.iter().cloned())
916 #[stable(feature = "rust1", since = "1.0.0")]
917 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
919 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
920 (**self).to_socket_addrs()
924 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
925 impl ToSocketAddrs for String {
926 type Iter = vec::IntoIter<SocketAddr>;
927 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
928 (&**self).to_socket_addrs()
932 #[cfg(all(test, not(target_os = "emscripten")))]
935 use net::test::{tsa, sa6, sa4};
938 fn to_socket_addr_ipaddr_u16() {
939 let a = Ipv4Addr::new(77, 88, 21, 11);
941 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
942 assert_eq!(Ok(vec![e]), tsa((a, p)));
946 fn to_socket_addr_str_u16() {
947 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
948 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
950 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
951 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
953 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
954 assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
958 fn to_socket_addr_str() {
959 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
960 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
962 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
963 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
965 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
966 assert!(tsa("localhost:23924").unwrap().contains(&a));
970 fn to_socket_addr_string() {
971 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
972 assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
973 assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
974 assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
976 let s = format!("{}:{}", "77.88.21.11", "24352");
977 assert_eq!(Ok(vec![a]), tsa(s));
978 // s has been moved into the tsa call
981 // FIXME: figure out why this fails on openbsd and bitrig and fix it
983 #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
984 fn to_socket_addr_str_bad() {
985 assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
990 fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
991 fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
993 let mut v4 = SocketAddrV4::new(ip4(11), 80);
994 assert_eq!(v4.ip(), &ip4(11));
996 assert_eq!(v4.ip(), &ip4(12));
998 let mut addr = SocketAddr::V4(v4);
999 assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
1000 addr.set_ip(IpAddr::V4(ip4(13)));
1001 assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
1002 addr.set_ip(IpAddr::V6(ip6(14)));
1003 assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
1005 let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1006 assert_eq!(v6.ip(), &ip6(1));
1008 assert_eq!(v6.ip(), &ip6(2));
1010 let mut addr = SocketAddr::V6(v6);
1011 assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
1012 addr.set_ip(IpAddr::V6(ip6(3)));
1013 assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
1014 addr.set_ip(IpAddr::V4(ip4(4)));
1015 assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
1020 let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1021 assert_eq!(v4.port(), 80);
1023 assert_eq!(v4.port(), 443);
1025 let mut addr = SocketAddr::V4(v4);
1026 assert_eq!(addr.port(), 443);
1027 addr.set_port(8080);
1028 assert_eq!(addr.port(), 8080);
1030 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1031 assert_eq!(v6.port(), 80);
1033 assert_eq!(v6.port(), 443);
1035 let mut addr = SocketAddr::V6(v6);
1036 assert_eq!(addr.port(), 443);
1037 addr.set_port(8080);
1038 assert_eq!(addr.port(), 8080);
1043 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1044 assert_eq!(v6.flowinfo(), 10);
1045 v6.set_flowinfo(20);
1046 assert_eq!(v6.flowinfo(), 20);
1051 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1052 assert_eq!(v6.scope_id(), 10);
1053 v6.set_scope_id(20);
1054 assert_eq!(v6.scope_id(), 20);
1059 let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1060 assert!(v4.is_ipv4());
1061 assert!(!v4.is_ipv6());
1066 let v6 = SocketAddr::V6(SocketAddrV6::new(
1067 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
1068 assert!(!v6.is_ipv4());
1069 assert!(v6.is_ipv6());