1 use crate::convert::TryInto;
7 use crate::net::{hton, ntoh, IpAddr, Ipv4Addr, Ipv6Addr};
10 use crate::sys::net::netc as c;
11 use crate::sys_common::net::LookupHost;
12 use crate::sys_common::{AsInner, FromInner, IntoInner};
15 /// An internet socket address, either IPv4 or IPv6.
17 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
18 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
19 /// [`SocketAddrV6`]'s respective documentation for more details.
21 /// The size of a `SocketAddr` instance may vary depending on the target operating
24 /// [IP address]: ../../std/net/enum.IpAddr.html
25 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
26 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
31 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
33 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
35 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
36 /// assert_eq!(socket.port(), 8080);
37 /// assert_eq!(socket.is_ipv4(), true);
39 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
40 #[stable(feature = "rust1", since = "1.0.0")]
42 /// An IPv4 socket address.
43 #[stable(feature = "rust1", since = "1.0.0")]
44 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
45 /// An IPv6 socket address.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
50 /// An IPv4 socket address.
52 /// IPv4 socket addresses consist of an [IPv4 address] and a 16-bit port number, as
53 /// stated in [IETF RFC 793].
55 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
57 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
60 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
61 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
62 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
67 /// use std::net::{Ipv4Addr, SocketAddrV4};
69 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
71 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
72 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
73 /// assert_eq!(socket.port(), 8080);
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub struct SocketAddrV4 {
78 inner: c::sockaddr_in,
81 /// An IPv6 socket address.
83 /// IPv6 socket addresses consist of an [Ipv6 address], a 16-bit port number, as well
84 /// as fields containing the traffic class, the flow label, and a scope identifier
85 /// (see [IETF RFC 2553, Section 3.3] for more details).
87 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
89 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
92 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
93 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
94 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
99 /// use std::net::{Ipv6Addr, SocketAddrV6};
101 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
103 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
104 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
105 /// assert_eq!(socket.port(), 8080);
108 #[stable(feature = "rust1", since = "1.0.0")]
109 pub struct SocketAddrV6 {
110 inner: c::sockaddr_in6,
114 /// Creates a new socket address from an [IP address] and a port number.
116 /// [IP address]: ../../std/net/enum.IpAddr.html
121 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
123 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
124 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
125 /// assert_eq!(socket.port(), 8080);
127 #[stable(feature = "ip_addr", since = "1.7.0")]
128 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
130 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
131 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
135 /// Returns the IP address associated with this socket address.
140 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
142 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
143 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
145 #[stable(feature = "ip_addr", since = "1.7.0")]
146 pub fn ip(&self) -> IpAddr {
148 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
149 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
153 /// Changes the IP address associated with this socket address.
158 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
160 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
161 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
162 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
164 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
165 pub fn set_ip(&mut self, new_ip: IpAddr) {
166 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
167 match (self, new_ip) {
168 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
169 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
170 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
174 /// Returns the port number associated with this socket address.
179 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
181 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
182 /// assert_eq!(socket.port(), 8080);
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub fn port(&self) -> u16 {
187 SocketAddr::V4(ref a) => a.port(),
188 SocketAddr::V6(ref a) => a.port(),
192 /// Changes the port number associated with this socket address.
197 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
199 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
200 /// socket.set_port(1025);
201 /// assert_eq!(socket.port(), 1025);
203 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
204 pub fn set_port(&mut self, new_port: u16) {
206 SocketAddr::V4(ref mut a) => a.set_port(new_port),
207 SocketAddr::V6(ref mut a) => a.set_port(new_port),
211 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
212 /// [IPv4 address], and [`false`] otherwise.
214 /// [`true`]: ../../std/primitive.bool.html
215 /// [`false`]: ../../std/primitive.bool.html
216 /// [IP address]: ../../std/net/enum.IpAddr.html
217 /// [IPv4 address]: ../../std/net/enum.IpAddr.html#variant.V4
222 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
224 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
225 /// assert_eq!(socket.is_ipv4(), true);
226 /// assert_eq!(socket.is_ipv6(), false);
228 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
229 pub fn is_ipv4(&self) -> bool {
231 SocketAddr::V4(_) => true,
232 SocketAddr::V6(_) => false,
236 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
237 /// [IPv6 address], and [`false`] otherwise.
239 /// [`true`]: ../../std/primitive.bool.html
240 /// [`false`]: ../../std/primitive.bool.html
241 /// [IP address]: ../../std/net/enum.IpAddr.html
242 /// [IPv6 address]: ../../std/net/enum.IpAddr.html#variant.V6
247 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
249 /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
250 /// assert_eq!(socket.is_ipv4(), false);
251 /// assert_eq!(socket.is_ipv6(), true);
253 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
254 pub fn is_ipv6(&self) -> bool {
256 SocketAddr::V4(_) => false,
257 SocketAddr::V6(_) => true,
263 /// Creates a new socket address from an [IPv4 address] and a port number.
265 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
270 /// use std::net::{SocketAddrV4, Ipv4Addr};
272 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
277 inner: c::sockaddr_in {
278 sin_family: c::AF_INET as c::sa_family_t,
279 sin_port: hton(port),
280 sin_addr: *ip.as_inner(),
281 ..unsafe { mem::zeroed() }
286 /// Returns the IP address associated with this socket address.
291 /// use std::net::{SocketAddrV4, Ipv4Addr};
293 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
294 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
296 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn ip(&self) -> &Ipv4Addr {
298 unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
301 /// Changes the IP address associated with this socket address.
306 /// use std::net::{SocketAddrV4, Ipv4Addr};
308 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
309 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
310 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
312 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
313 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
314 self.inner.sin_addr = *new_ip.as_inner()
317 /// Returns the port number associated with this socket address.
322 /// use std::net::{SocketAddrV4, Ipv4Addr};
324 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
325 /// assert_eq!(socket.port(), 8080);
327 #[stable(feature = "rust1", since = "1.0.0")]
328 pub fn port(&self) -> u16 {
329 ntoh(self.inner.sin_port)
332 /// Changes the port number associated with this socket address.
337 /// use std::net::{SocketAddrV4, Ipv4Addr};
339 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
340 /// socket.set_port(4242);
341 /// assert_eq!(socket.port(), 4242);
343 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
344 pub fn set_port(&mut self, new_port: u16) {
345 self.inner.sin_port = hton(new_port);
350 /// Creates a new socket address from an [IPv6 address], a 16-bit port number,
351 /// and the `flowinfo` and `scope_id` fields.
353 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
354 /// parameters, see [IETF RFC 2553, Section 3.3].
356 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
357 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
362 /// use std::net::{SocketAddrV6, Ipv6Addr};
364 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
369 inner: c::sockaddr_in6 {
370 sin6_family: c::AF_INET6 as c::sa_family_t,
371 sin6_port: hton(port),
372 sin6_addr: *ip.as_inner(),
373 sin6_flowinfo: flowinfo,
374 sin6_scope_id: scope_id,
375 ..unsafe { mem::zeroed() }
380 /// Returns the IP address associated with this socket address.
385 /// use std::net::{SocketAddrV6, Ipv6Addr};
387 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
388 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn ip(&self) -> &Ipv6Addr {
392 unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }
395 /// Changes the IP address associated with this socket address.
400 /// use std::net::{SocketAddrV6, Ipv6Addr};
402 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
403 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
404 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
406 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
407 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
408 self.inner.sin6_addr = *new_ip.as_inner()
411 /// Returns the port number associated with this socket address.
416 /// use std::net::{SocketAddrV6, Ipv6Addr};
418 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
419 /// assert_eq!(socket.port(), 8080);
421 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn port(&self) -> u16 {
423 ntoh(self.inner.sin6_port)
426 /// Changes the port number associated with this socket address.
431 /// use std::net::{SocketAddrV6, Ipv6Addr};
433 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
434 /// socket.set_port(4242);
435 /// assert_eq!(socket.port(), 4242);
437 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
438 pub fn set_port(&mut self, new_port: u16) {
439 self.inner.sin6_port = hton(new_port);
442 /// Returns the flow information associated with this address.
444 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
445 /// as specified in [IETF RFC 2553, Section 3.3].
446 /// It combines information about the flow label and the traffic class as specified
447 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
449 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
450 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
451 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
452 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
457 /// use std::net::{SocketAddrV6, Ipv6Addr};
459 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
460 /// assert_eq!(socket.flowinfo(), 10);
462 #[stable(feature = "rust1", since = "1.0.0")]
463 pub fn flowinfo(&self) -> u32 {
464 self.inner.sin6_flowinfo
467 /// Changes the flow information associated with this socket address.
469 /// See the [`flowinfo`] method's documentation for more details.
471 /// [`flowinfo`]: #method.flowinfo
476 /// use std::net::{SocketAddrV6, Ipv6Addr};
478 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
479 /// socket.set_flowinfo(56);
480 /// assert_eq!(socket.flowinfo(), 56);
482 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
483 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
484 self.inner.sin6_flowinfo = new_flowinfo;
487 /// Returns the scope ID associated with this address.
489 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
490 /// as specified in [IETF RFC 2553, Section 3.3].
492 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
497 /// use std::net::{SocketAddrV6, Ipv6Addr};
499 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
500 /// assert_eq!(socket.scope_id(), 78);
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn scope_id(&self) -> u32 {
504 self.inner.sin6_scope_id
507 /// Changes the scope ID associated with this socket address.
509 /// See the [`scope_id`] method's documentation for more details.
511 /// [`scope_id`]: #method.scope_id
516 /// use std::net::{SocketAddrV6, Ipv6Addr};
518 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
519 /// socket.set_scope_id(42);
520 /// assert_eq!(socket.scope_id(), 42);
522 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
523 pub fn set_scope_id(&mut self, new_scope_id: u32) {
524 self.inner.sin6_scope_id = new_scope_id;
528 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
529 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
530 SocketAddrV4 { inner: addr }
534 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
535 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
536 SocketAddrV6 { inner: addr }
540 #[stable(feature = "ip_from_ip", since = "1.16.0")]
541 impl From<SocketAddrV4> for SocketAddr {
542 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
544 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
545 /// [`SocketAddr::V4`]: ../../std/net/enum.SocketAddr.html#variant.V4
546 fn from(sock4: SocketAddrV4) -> SocketAddr {
547 SocketAddr::V4(sock4)
551 #[stable(feature = "ip_from_ip", since = "1.16.0")]
552 impl From<SocketAddrV6> for SocketAddr {
553 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
555 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
556 /// [`SocketAddr::V6`]: ../../std/net/enum.SocketAddr.html#variant.V6
557 fn from(sock6: SocketAddrV6) -> SocketAddr {
558 SocketAddr::V6(sock6)
562 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
563 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
564 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
566 /// This conversion creates a [`SocketAddr::V4`] for a [`IpAddr::V4`]
567 /// and creates a [`SocketAddr::V6`] for a [`IpAddr::V6`].
569 /// `u16` is treated as port of the newly created [`SocketAddr`].
571 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
572 /// [`IpAddr::V4`]: ../../std/net/enum.IpAddr.html#variant.V4
573 /// [`IpAddr::V6`]: ../../std/net/enum.IpAddr.html#variant.V6
574 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
575 /// [`SocketAddr::V4`]: ../../std/net/enum.SocketAddr.html#variant.V4
576 /// [`SocketAddr::V6`]: ../../std/net/enum.SocketAddr.html#variant.V6
577 fn from(pieces: (I, u16)) -> SocketAddr {
578 SocketAddr::new(pieces.0.into(), pieces.1)
582 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
583 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
585 SocketAddr::V4(ref a) => {
586 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
588 SocketAddr::V6(ref a) => {
589 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
595 #[stable(feature = "rust1", since = "1.0.0")]
596 impl fmt::Display for SocketAddr {
597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
599 SocketAddr::V4(ref a) => a.fmt(f),
600 SocketAddr::V6(ref a) => a.fmt(f),
605 #[stable(feature = "rust1", since = "1.0.0")]
606 impl fmt::Display for SocketAddrV4 {
607 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608 write!(f, "{}:{}", self.ip(), self.port())
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl fmt::Debug for SocketAddrV4 {
614 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
615 fmt::Display::fmt(self, fmt)
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl fmt::Display for SocketAddrV6 {
621 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
622 write!(f, "[{}]:{}", self.ip(), self.port())
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl fmt::Debug for SocketAddrV6 {
628 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
629 fmt::Display::fmt(self, fmt)
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl Clone for SocketAddrV4 {
635 fn clone(&self) -> SocketAddrV4 {
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl Clone for SocketAddrV6 {
641 fn clone(&self) -> SocketAddrV6 {
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl PartialEq for SocketAddrV4 {
648 fn eq(&self, other: &SocketAddrV4) -> bool {
649 self.inner.sin_port == other.inner.sin_port
650 && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl PartialEq for SocketAddrV6 {
655 fn eq(&self, other: &SocketAddrV6) -> bool {
656 self.inner.sin6_port == other.inner.sin6_port
657 && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
658 && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
659 && self.inner.sin6_scope_id == other.inner.sin6_scope_id
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl Eq for SocketAddrV4 {}
664 #[stable(feature = "rust1", since = "1.0.0")]
665 impl Eq for SocketAddrV6 {}
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl hash::Hash for SocketAddrV4 {
669 fn hash<H: hash::Hasher>(&self, s: &mut H) {
670 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
673 #[stable(feature = "rust1", since = "1.0.0")]
674 impl hash::Hash for SocketAddrV6 {
675 fn hash<H: hash::Hasher>(&self, s: &mut H) {
677 self.inner.sin6_port,
678 &self.inner.sin6_addr.s6_addr,
679 self.inner.sin6_flowinfo,
680 self.inner.sin6_scope_id,
686 /// A trait for objects which can be converted or resolved to one or more
687 /// [`SocketAddr`] values.
689 /// This trait is used for generic address resolution when constructing network
690 /// objects. By default it is implemented for the following types:
692 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
694 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
695 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
696 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
698 /// * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
699 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
702 /// * [`&str`]: the string should be either a string representation of a
703 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
704 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
706 /// This trait allows constructing network objects like [`TcpStream`] or
707 /// [`UdpSocket`] easily with values of various types for the bind/connection
708 /// address. It is needed because sometimes one type is more appropriate than
709 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
710 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
711 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
712 /// some other type (e.g., a string) just for it to be converted back to
713 /// [`SocketAddr`] in constructor methods is pointless.
715 /// Addresses returned by the operating system that are not IP addresses are
716 /// silently ignored.
718 /// [`FromStr`]: ../../std/str/trait.FromStr.html
719 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
720 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
721 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
722 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
723 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
724 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
725 /// [`&str`]: ../../std/primitive.str.html
726 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
727 /// [`to_socket_addrs`]: #tymethod.to_socket_addrs
728 /// [`UdpSocket`]: ../../std/net/struct.UdpSocket.html
729 /// [`u16`]: ../../std/primitive.u16.html
733 /// Creating a [`SocketAddr`] iterator that yields one item:
736 /// use std::net::{ToSocketAddrs, SocketAddr};
738 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
739 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
741 /// assert_eq!(Some(addr), addrs_iter.next());
742 /// assert!(addrs_iter.next().is_none());
745 /// Creating a [`SocketAddr`] iterator from a hostname:
748 /// use std::net::{SocketAddr, ToSocketAddrs};
750 /// // assuming 'localhost' resolves to 127.0.0.1
751 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
752 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
753 /// assert!(addrs_iter.next().is_none());
755 /// // assuming 'foo' does not resolve
756 /// assert!("foo:443".to_socket_addrs().is_err());
759 /// Creating a [`SocketAddr`] iterator that yields multiple items:
762 /// use std::net::{SocketAddr, ToSocketAddrs};
764 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
765 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
766 /// let addrs = vec![addr1, addr2];
768 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
770 /// assert_eq!(Some(addr1), addrs_iter.next());
771 /// assert_eq!(Some(addr2), addrs_iter.next());
772 /// assert!(addrs_iter.next().is_none());
775 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
776 /// socket address `&str` (missing the port):
780 /// use std::net::ToSocketAddrs;
782 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
783 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
786 /// [`TcpStream::connect`] is an example of an function that utilizes
787 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
791 /// use std::net::{TcpStream, Ipv4Addr};
793 /// let stream = TcpStream::connect(("127.0.0.1", 443));
795 /// let stream = TcpStream::connect("127.0.0.1:443");
797 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
800 /// [`TcpStream::connect`]: ../../std/net/struct.TcpStream.html#method.connect
801 #[stable(feature = "rust1", since = "1.0.0")]
802 pub trait ToSocketAddrs {
803 /// Returned iterator over socket addresses which this type may correspond
805 #[stable(feature = "rust1", since = "1.0.0")]
806 type Iter: Iterator<Item = SocketAddr>;
808 /// Converts this object to an iterator of resolved `SocketAddr`s.
810 /// The returned iterator may not actually yield any values depending on the
811 /// outcome of any resolution performed.
813 /// Note that this function may block the current thread while resolution is
815 #[stable(feature = "rust1", since = "1.0.0")]
816 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl ToSocketAddrs for SocketAddr {
821 type Iter = option::IntoIter<SocketAddr>;
822 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
823 Ok(Some(*self).into_iter())
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl ToSocketAddrs for SocketAddrV4 {
829 type Iter = option::IntoIter<SocketAddr>;
830 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
831 SocketAddr::V4(*self).to_socket_addrs()
835 #[stable(feature = "rust1", since = "1.0.0")]
836 impl ToSocketAddrs for SocketAddrV6 {
837 type Iter = option::IntoIter<SocketAddr>;
838 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
839 SocketAddr::V6(*self).to_socket_addrs()
843 #[stable(feature = "rust1", since = "1.0.0")]
844 impl ToSocketAddrs for (IpAddr, u16) {
845 type Iter = option::IntoIter<SocketAddr>;
846 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
847 let (ip, port) = *self;
849 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
850 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl ToSocketAddrs for (Ipv4Addr, u16) {
857 type Iter = option::IntoIter<SocketAddr>;
858 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
859 let (ip, port) = *self;
860 SocketAddrV4::new(ip, port).to_socket_addrs()
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl ToSocketAddrs for (Ipv6Addr, u16) {
866 type Iter = option::IntoIter<SocketAddr>;
867 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
868 let (ip, port) = *self;
869 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
873 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl ToSocketAddrs for (&str, u16) {
886 type Iter = vec::IntoIter<SocketAddr>;
887 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
888 let (host, port) = *self;
890 // try to parse the host as a regular IP address first
891 if let Ok(addr) = host.parse::<Ipv4Addr>() {
892 let addr = SocketAddrV4::new(addr, port);
893 return Ok(vec![SocketAddr::V4(addr)].into_iter());
895 if let Ok(addr) = host.parse::<Ipv6Addr>() {
896 let addr = SocketAddrV6::new(addr, port, 0, 0);
897 return Ok(vec![SocketAddr::V6(addr)].into_iter());
900 resolve_socket_addr((host, port).try_into()?)
904 // accepts strings like 'localhost:12345'
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl ToSocketAddrs for str {
907 type Iter = vec::IntoIter<SocketAddr>;
908 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
909 // try to parse as a regular SocketAddr first
910 if let Some(addr) = self.parse().ok() {
911 return Ok(vec![addr].into_iter());
914 resolve_socket_addr(self.try_into()?)
918 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
919 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
920 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
922 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
923 Ok(self.iter().cloned())
927 #[stable(feature = "rust1", since = "1.0.0")]
928 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
930 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
931 (**self).to_socket_addrs()
935 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
936 impl ToSocketAddrs for String {
937 type Iter = vec::IntoIter<SocketAddr>;
938 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
939 (&**self).to_socket_addrs()
943 #[cfg(all(test, not(target_os = "emscripten")))]
945 use crate::net::test::{sa4, sa6, tsa};
949 fn to_socket_addr_ipaddr_u16() {
950 let a = Ipv4Addr::new(77, 88, 21, 11);
952 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
953 assert_eq!(Ok(vec![e]), tsa((a, p)));
957 fn to_socket_addr_str_u16() {
958 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
959 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
961 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
962 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
964 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
965 #[cfg(not(target_env = "sgx"))]
966 assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
967 #[cfg(target_env = "sgx")]
972 fn to_socket_addr_str() {
973 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
974 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
976 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
977 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
979 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
980 #[cfg(not(target_env = "sgx"))]
981 assert!(tsa("localhost:23924").unwrap().contains(&a));
982 #[cfg(target_env = "sgx")]
987 fn to_socket_addr_string() {
988 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
989 assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
990 assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
991 assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
993 let s = format!("{}:{}", "77.88.21.11", "24352");
994 assert_eq!(Ok(vec![a]), tsa(s));
995 // s has been moved into the tsa call
998 // FIXME: figure out why this fails on openbsd and fix it
1000 #[cfg(not(any(windows, target_os = "openbsd")))]
1001 fn to_socket_addr_str_bad() {
1002 assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
1007 fn ip4(low: u8) -> Ipv4Addr {
1008 Ipv4Addr::new(77, 88, 21, low)
1010 fn ip6(low: u16) -> Ipv6Addr {
1011 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low)
1014 let mut v4 = SocketAddrV4::new(ip4(11), 80);
1015 assert_eq!(v4.ip(), &ip4(11));
1017 assert_eq!(v4.ip(), &ip4(12));
1019 let mut addr = SocketAddr::V4(v4);
1020 assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
1021 addr.set_ip(IpAddr::V4(ip4(13)));
1022 assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
1023 addr.set_ip(IpAddr::V6(ip6(14)));
1024 assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
1026 let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1027 assert_eq!(v6.ip(), &ip6(1));
1029 assert_eq!(v6.ip(), &ip6(2));
1031 let mut addr = SocketAddr::V6(v6);
1032 assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
1033 addr.set_ip(IpAddr::V6(ip6(3)));
1034 assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
1035 addr.set_ip(IpAddr::V4(ip4(4)));
1036 assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
1041 let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1042 assert_eq!(v4.port(), 80);
1044 assert_eq!(v4.port(), 443);
1046 let mut addr = SocketAddr::V4(v4);
1047 assert_eq!(addr.port(), 443);
1048 addr.set_port(8080);
1049 assert_eq!(addr.port(), 8080);
1051 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1052 assert_eq!(v6.port(), 80);
1054 assert_eq!(v6.port(), 443);
1056 let mut addr = SocketAddr::V6(v6);
1057 assert_eq!(addr.port(), 443);
1058 addr.set_port(8080);
1059 assert_eq!(addr.port(), 8080);
1064 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1065 assert_eq!(v6.flowinfo(), 10);
1066 v6.set_flowinfo(20);
1067 assert_eq!(v6.flowinfo(), 20);
1072 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1073 assert_eq!(v6.scope_id(), 10);
1074 v6.set_scope_id(20);
1075 assert_eq!(v6.scope_id(), 20);
1080 let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1081 assert!(v4.is_ipv4());
1082 assert!(!v4.is_ipv6());
1087 let v6 = SocketAddr::V6(SocketAddrV6::new(
1088 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1),
1093 assert!(!v6.is_ipv4());
1094 assert!(v6.is_ipv6());