5 use crate::net::{ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
7 use crate::sys::net::netc as c;
8 use crate::sys_common::{FromInner, AsInner, IntoInner};
9 use crate::sys_common::net::LookupHost;
13 use crate::convert::TryInto;
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 { inner: c::sockaddr_in }
79 /// An IPv6 socket address.
81 /// IPv6 socket addresses consist of an [Ipv6 address], a 16-bit port number, as well
82 /// as fields containing the traffic class, the flow label, and a scope identifier
83 /// (see [IETF RFC 2553, Section 3.3] for more details).
85 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
87 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
90 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
91 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
92 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
97 /// use std::net::{Ipv6Addr, SocketAddrV6};
99 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
101 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
102 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
103 /// assert_eq!(socket.port(), 8080);
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
110 /// Creates a new socket address from an [IP address] and a port number.
112 /// [IP address]: ../../std/net/enum.IpAddr.html
117 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
119 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
120 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
121 /// assert_eq!(socket.port(), 8080);
123 #[stable(feature = "ip_addr", since = "1.7.0")]
124 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
126 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
127 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
131 /// Returns the IP address associated with this socket address.
136 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
138 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
139 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
141 #[stable(feature = "ip_addr", since = "1.7.0")]
142 pub fn ip(&self) -> IpAddr {
144 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
145 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
149 /// Changes the IP address associated with this socket address.
154 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
156 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
157 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
158 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
160 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
161 pub fn set_ip(&mut self, new_ip: IpAddr) {
162 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
163 match (self, new_ip) {
164 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
165 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
166 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
170 /// Returns the port number associated with this socket address.
175 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
177 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
178 /// assert_eq!(socket.port(), 8080);
180 #[stable(feature = "rust1", since = "1.0.0")]
181 pub fn port(&self) -> u16 {
183 SocketAddr::V4(ref a) => a.port(),
184 SocketAddr::V6(ref a) => a.port(),
188 /// Changes the port number associated with this socket address.
193 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
195 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
196 /// socket.set_port(1025);
197 /// assert_eq!(socket.port(), 1025);
199 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
200 pub fn set_port(&mut self, new_port: u16) {
202 SocketAddr::V4(ref mut a) => a.set_port(new_port),
203 SocketAddr::V6(ref mut a) => a.set_port(new_port),
207 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
208 /// [IPv4 address], and [`false`] otherwise.
210 /// [`true`]: ../../std/primitive.bool.html
211 /// [`false`]: ../../std/primitive.bool.html
212 /// [IP address]: ../../std/net/enum.IpAddr.html
213 /// [IPv4 address]: ../../std/net/enum.IpAddr.html#variant.V4
218 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
221 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
222 /// assert_eq!(socket.is_ipv4(), true);
223 /// assert_eq!(socket.is_ipv6(), false);
226 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
227 pub fn is_ipv4(&self) -> bool {
229 SocketAddr::V4(_) => true,
230 SocketAddr::V6(_) => false,
234 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
235 /// [IPv6 address], and [`false`] otherwise.
237 /// [`true`]: ../../std/primitive.bool.html
238 /// [`false`]: ../../std/primitive.bool.html
239 /// [IP address]: ../../std/net/enum.IpAddr.html
240 /// [IPv6 address]: ../../std/net/enum.IpAddr.html#variant.V6
245 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
248 /// let socket = SocketAddr::new(
249 /// 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);
254 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
255 pub fn is_ipv6(&self) -> bool {
257 SocketAddr::V4(_) => false,
258 SocketAddr::V6(_) => true,
264 /// Creates a new socket address from an [IPv4 address] and a port number.
266 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
271 /// use std::net::{SocketAddrV4, Ipv4Addr};
273 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
278 inner: c::sockaddr_in {
279 sin_family: c::AF_INET as c::sa_family_t,
280 sin_port: hton(port),
281 sin_addr: *ip.as_inner(),
282 .. unsafe { mem::zeroed() }
287 /// Returns the IP address associated with this socket address.
292 /// use std::net::{SocketAddrV4, Ipv4Addr};
294 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
295 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn ip(&self) -> &Ipv4Addr {
300 &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
304 /// Changes the IP address associated with this socket address.
309 /// use std::net::{SocketAddrV4, Ipv4Addr};
311 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
312 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
313 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
315 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
316 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
317 self.inner.sin_addr = *new_ip.as_inner()
320 /// Returns the port number associated with this socket address.
325 /// use std::net::{SocketAddrV4, Ipv4Addr};
327 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
328 /// assert_eq!(socket.port(), 8080);
330 #[stable(feature = "rust1", since = "1.0.0")]
331 pub fn port(&self) -> u16 {
332 ntoh(self.inner.sin_port)
335 /// Changes the port number associated with this socket address.
340 /// use std::net::{SocketAddrV4, Ipv4Addr};
342 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
343 /// socket.set_port(4242);
344 /// assert_eq!(socket.port(), 4242);
346 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
347 pub fn set_port(&mut self, new_port: u16) {
348 self.inner.sin_port = hton(new_port);
353 /// Creates a new socket address from an [IPv6 address], a 16-bit port number,
354 /// and the `flowinfo` and `scope_id` fields.
356 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
357 /// parameters, see [IETF RFC 2553, Section 3.3].
359 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
360 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
365 /// use std::net::{SocketAddrV6, Ipv6Addr};
367 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
373 inner: c::sockaddr_in6 {
374 sin6_family: c::AF_INET6 as c::sa_family_t,
375 sin6_port: hton(port),
376 sin6_addr: *ip.as_inner(),
377 sin6_flowinfo: flowinfo,
378 sin6_scope_id: scope_id,
379 .. unsafe { mem::zeroed() }
384 /// Returns the IP address associated with this socket address.
389 /// use std::net::{SocketAddrV6, Ipv6Addr};
391 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
392 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn ip(&self) -> &Ipv6Addr {
397 &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
401 /// Changes the IP address associated with this socket address.
406 /// use std::net::{SocketAddrV6, Ipv6Addr};
408 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
409 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
410 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
412 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
413 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
414 self.inner.sin6_addr = *new_ip.as_inner()
417 /// Returns the port number associated with this socket address.
422 /// use std::net::{SocketAddrV6, Ipv6Addr};
424 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
425 /// assert_eq!(socket.port(), 8080);
427 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn port(&self) -> u16 {
429 ntoh(self.inner.sin6_port)
432 /// Changes the port number associated with this socket address.
437 /// use std::net::{SocketAddrV6, Ipv6Addr};
439 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
440 /// socket.set_port(4242);
441 /// assert_eq!(socket.port(), 4242);
443 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
444 pub fn set_port(&mut self, new_port: u16) {
445 self.inner.sin6_port = hton(new_port);
448 /// Returns the flow information associated with this address.
450 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
451 /// as specified in [IETF RFC 2553, Section 3.3].
452 /// It combines information about the flow label and the traffic class as specified
453 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
455 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
456 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
457 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
458 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
463 /// use std::net::{SocketAddrV6, Ipv6Addr};
465 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
466 /// assert_eq!(socket.flowinfo(), 10);
468 #[stable(feature = "rust1", since = "1.0.0")]
469 pub fn flowinfo(&self) -> u32 {
470 self.inner.sin6_flowinfo
473 /// Changes the flow information associated with this socket address.
475 /// See the [`flowinfo`] method's documentation for more details.
477 /// [`flowinfo`]: #method.flowinfo
482 /// use std::net::{SocketAddrV6, Ipv6Addr};
484 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
485 /// socket.set_flowinfo(56);
486 /// assert_eq!(socket.flowinfo(), 56);
488 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
489 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
490 self.inner.sin6_flowinfo = new_flowinfo;
493 /// Returns the scope ID associated with this address.
495 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
496 /// as specified in [IETF RFC 2553, Section 3.3].
498 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
503 /// use std::net::{SocketAddrV6, Ipv6Addr};
505 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
506 /// assert_eq!(socket.scope_id(), 78);
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn scope_id(&self) -> u32 {
510 self.inner.sin6_scope_id
513 /// Changes the scope ID associated with this socket address.
515 /// See the [`scope_id`] method's documentation for more details.
517 /// [`scope_id`]: #method.scope_id
522 /// use std::net::{SocketAddrV6, Ipv6Addr};
524 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
525 /// socket.set_scope_id(42);
526 /// assert_eq!(socket.scope_id(), 42);
528 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
529 pub fn set_scope_id(&mut self, new_scope_id: u32) {
530 self.inner.sin6_scope_id = new_scope_id;
534 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
535 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
536 SocketAddrV4 { inner: addr }
540 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
541 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
542 SocketAddrV6 { inner: addr }
546 #[stable(feature = "ip_from_ip", since = "1.16.0")]
547 impl From<SocketAddrV4> for SocketAddr {
548 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
549 fn from(sock4: SocketAddrV4) -> SocketAddr {
550 SocketAddr::V4(sock4)
554 #[stable(feature = "ip_from_ip", since = "1.16.0")]
555 impl From<SocketAddrV6> for SocketAddr {
556 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::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`].
570 fn from(pieces: (I, u16)) -> SocketAddr {
571 SocketAddr::new(pieces.0.into(), pieces.1)
575 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
576 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
578 SocketAddr::V4(ref a) => {
579 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
581 SocketAddr::V6(ref a) => {
582 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
588 #[stable(feature = "rust1", since = "1.0.0")]
589 impl fmt::Display for SocketAddr {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
592 SocketAddr::V4(ref a) => a.fmt(f),
593 SocketAddr::V6(ref a) => a.fmt(f),
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl fmt::Display for SocketAddrV4 {
600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
601 write!(f, "{}:{}", self.ip(), self.port())
605 #[stable(feature = "rust1", since = "1.0.0")]
606 impl fmt::Debug for SocketAddrV4 {
607 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
608 fmt::Display::fmt(self, fmt)
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl fmt::Display for SocketAddrV6 {
614 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
615 write!(f, "[{}]:{}", self.ip(), self.port())
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl fmt::Debug for SocketAddrV6 {
621 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
622 fmt::Display::fmt(self, fmt)
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl Clone for SocketAddrV4 {
628 fn clone(&self) -> SocketAddrV4 { *self }
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl Clone for SocketAddrV6 {
632 fn clone(&self) -> SocketAddrV6 { *self }
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl PartialEq for SocketAddrV4 {
637 fn eq(&self, other: &SocketAddrV4) -> bool {
638 self.inner.sin_port == other.inner.sin_port &&
639 self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl PartialEq for SocketAddrV6 {
644 fn eq(&self, other: &SocketAddrV6) -> bool {
645 self.inner.sin6_port == other.inner.sin6_port &&
646 self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
647 self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
648 self.inner.sin6_scope_id == other.inner.sin6_scope_id
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl Eq for SocketAddrV4 {}
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl Eq for SocketAddrV6 {}
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl hash::Hash for SocketAddrV4 {
658 fn hash<H: hash::Hasher>(&self, s: &mut H) {
659 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl hash::Hash for SocketAddrV6 {
664 fn hash<H: hash::Hasher>(&self, s: &mut H) {
665 (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
666 self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
670 /// A trait for objects which can be converted or resolved to one or more
671 /// [`SocketAddr`] values.
673 /// This trait is used for generic address resolution when constructing network
674 /// objects. By default it is implemented for the following types:
676 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
678 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
679 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
680 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
682 /// * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
683 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
686 /// * [`&str`]: the string should be either a string representation of a
687 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
688 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
690 /// This trait allows constructing network objects like [`TcpStream`] or
691 /// [`UdpSocket`] easily with values of various types for the bind/connection
692 /// address. It is needed because sometimes one type is more appropriate than
693 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
694 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
695 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
696 /// some other type (e.g., a string) just for it to be converted back to
697 /// [`SocketAddr`] in constructor methods is pointless.
699 /// Addresses returned by the operating system that are not IP addresses are
700 /// silently ignored.
702 /// [`FromStr`]: ../../std/str/trait.FromStr.html
703 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
704 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
705 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
706 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
707 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
708 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
709 /// [`&str`]: ../../std/primitive.str.html
710 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
711 /// [`to_socket_addrs`]: #tymethod.to_socket_addrs
712 /// [`UdpSocket`]: ../../std/net/struct.UdpSocket.html
713 /// [`u16`]: ../../std/primitive.u16.html
717 /// Creating a [`SocketAddr`] iterator that yields one item:
720 /// use std::net::{ToSocketAddrs, SocketAddr};
722 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
723 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
725 /// assert_eq!(Some(addr), addrs_iter.next());
726 /// assert!(addrs_iter.next().is_none());
729 /// Creating a [`SocketAddr`] iterator from a hostname:
732 /// use std::net::{SocketAddr, ToSocketAddrs};
734 /// // assuming 'localhost' resolves to 127.0.0.1
735 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
736 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
737 /// assert!(addrs_iter.next().is_none());
739 /// // assuming 'foo' does not resolve
740 /// assert!("foo:443".to_socket_addrs().is_err());
743 /// Creating a [`SocketAddr`] iterator that yields multiple items:
746 /// use std::net::{SocketAddr, ToSocketAddrs};
748 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
749 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
750 /// let addrs = vec![addr1, addr2];
752 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
754 /// assert_eq!(Some(addr1), addrs_iter.next());
755 /// assert_eq!(Some(addr2), addrs_iter.next());
756 /// assert!(addrs_iter.next().is_none());
759 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
760 /// socket address `&str` (missing the port):
764 /// use std::net::ToSocketAddrs;
766 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
767 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
770 /// [`TcpStream::connect`] is an example of an function that utilizes
771 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
775 /// use std::net::{TcpStream, Ipv4Addr};
777 /// let stream = TcpStream::connect(("127.0.0.1", 443));
779 /// let stream = TcpStream::connect("127.0.0.1:443");
781 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
784 /// [`TcpStream::connect`]: ../../std/net/struct.TcpStream.html#method.connect
785 #[stable(feature = "rust1", since = "1.0.0")]
786 pub trait ToSocketAddrs {
787 /// Returned iterator over socket addresses which this type may correspond
789 #[stable(feature = "rust1", since = "1.0.0")]
790 type Iter: Iterator<Item=SocketAddr>;
792 /// Converts this object to an iterator of resolved `SocketAddr`s.
794 /// The returned iterator may not actually yield any values depending on the
795 /// outcome of any resolution performed.
797 /// Note that this function may block the current thread while resolution is
799 #[stable(feature = "rust1", since = "1.0.0")]
800 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
803 #[stable(feature = "rust1", since = "1.0.0")]
804 impl ToSocketAddrs for SocketAddr {
805 type Iter = option::IntoIter<SocketAddr>;
806 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
807 Ok(Some(*self).into_iter())
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl ToSocketAddrs for SocketAddrV4 {
813 type Iter = option::IntoIter<SocketAddr>;
814 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
815 SocketAddr::V4(*self).to_socket_addrs()
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl ToSocketAddrs for SocketAddrV6 {
821 type Iter = option::IntoIter<SocketAddr>;
822 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
823 SocketAddr::V6(*self).to_socket_addrs()
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl ToSocketAddrs for (IpAddr, u16) {
829 type Iter = option::IntoIter<SocketAddr>;
830 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
831 let (ip, port) = *self;
833 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
834 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl ToSocketAddrs for (Ipv4Addr, u16) {
841 type Iter = option::IntoIter<SocketAddr>;
842 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
843 let (ip, port) = *self;
844 SocketAddrV4::new(ip, port).to_socket_addrs()
848 #[stable(feature = "rust1", since = "1.0.0")]
849 impl ToSocketAddrs for (Ipv6Addr, u16) {
850 type Iter = option::IntoIter<SocketAddr>;
851 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
852 let (ip, port) = *self;
853 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
857 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
859 let v: Vec<_> = lh.map(|mut a| { a.set_port(p); a }).collect();
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl ToSocketAddrs for (&str, u16) {
865 type Iter = vec::IntoIter<SocketAddr>;
866 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
867 let (host, port) = *self;
869 // try to parse the host as a regular IP address first
870 if let Ok(addr) = host.parse::<Ipv4Addr>() {
871 let addr = SocketAddrV4::new(addr, port);
872 return Ok(vec![SocketAddr::V4(addr)].into_iter())
874 if let Ok(addr) = host.parse::<Ipv6Addr>() {
875 let addr = SocketAddrV6::new(addr, port, 0, 0);
876 return Ok(vec![SocketAddr::V6(addr)].into_iter())
879 resolve_socket_addr((host, port).try_into()?)
883 // accepts strings like 'localhost:12345'
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl ToSocketAddrs for str {
886 type Iter = vec::IntoIter<SocketAddr>;
887 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
888 // try to parse as a regular SocketAddr first
889 if let Some(addr) = self.parse().ok() {
890 return Ok(vec![addr].into_iter());
893 resolve_socket_addr(self.try_into()?)
897 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
898 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
899 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
901 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
902 Ok(self.iter().cloned())
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
909 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
910 (**self).to_socket_addrs()
914 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
915 impl ToSocketAddrs for String {
916 type Iter = vec::IntoIter<SocketAddr>;
917 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
918 (&**self).to_socket_addrs()
922 #[cfg(all(test, not(target_os = "emscripten")))]
925 use crate::net::test::{tsa, sa6, sa4};
928 fn to_socket_addr_ipaddr_u16() {
929 let a = Ipv4Addr::new(77, 88, 21, 11);
931 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
932 assert_eq!(Ok(vec![e]), tsa((a, p)));
936 fn to_socket_addr_str_u16() {
937 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
938 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
940 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
941 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
943 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
944 #[cfg(not(target_env = "sgx"))]
945 assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
946 #[cfg(target_env = "sgx")]
951 fn to_socket_addr_str() {
952 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
953 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
955 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
956 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
958 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
959 #[cfg(not(target_env = "sgx"))]
960 assert!(tsa("localhost:23924").unwrap().contains(&a));
961 #[cfg(target_env = "sgx")]
966 fn to_socket_addr_string() {
967 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
968 assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
969 assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
970 assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
972 let s = format!("{}:{}", "77.88.21.11", "24352");
973 assert_eq!(Ok(vec![a]), tsa(s));
974 // s has been moved into the tsa call
977 // FIXME: figure out why this fails on openbsd and fix it
979 #[cfg(not(any(windows, target_os = "openbsd")))]
980 fn to_socket_addr_str_bad() {
981 assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
986 fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
987 fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
989 let mut v4 = SocketAddrV4::new(ip4(11), 80);
990 assert_eq!(v4.ip(), &ip4(11));
992 assert_eq!(v4.ip(), &ip4(12));
994 let mut addr = SocketAddr::V4(v4);
995 assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
996 addr.set_ip(IpAddr::V4(ip4(13)));
997 assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
998 addr.set_ip(IpAddr::V6(ip6(14)));
999 assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
1001 let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1002 assert_eq!(v6.ip(), &ip6(1));
1004 assert_eq!(v6.ip(), &ip6(2));
1006 let mut addr = SocketAddr::V6(v6);
1007 assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
1008 addr.set_ip(IpAddr::V6(ip6(3)));
1009 assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
1010 addr.set_ip(IpAddr::V4(ip4(4)));
1011 assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
1016 let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1017 assert_eq!(v4.port(), 80);
1019 assert_eq!(v4.port(), 443);
1021 let mut addr = SocketAddr::V4(v4);
1022 assert_eq!(addr.port(), 443);
1023 addr.set_port(8080);
1024 assert_eq!(addr.port(), 8080);
1026 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1027 assert_eq!(v6.port(), 80);
1029 assert_eq!(v6.port(), 443);
1031 let mut addr = SocketAddr::V6(v6);
1032 assert_eq!(addr.port(), 443);
1033 addr.set_port(8080);
1034 assert_eq!(addr.port(), 8080);
1039 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1040 assert_eq!(v6.flowinfo(), 10);
1041 v6.set_flowinfo(20);
1042 assert_eq!(v6.flowinfo(), 20);
1047 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1048 assert_eq!(v6.scope_id(), 10);
1049 v6.set_scope_id(20);
1050 assert_eq!(v6.scope_id(), 20);
1055 let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1056 assert!(v4.is_ipv4());
1057 assert!(!v4.is_ipv6());
1062 let v6 = SocketAddr::V6(SocketAddrV6::new(
1063 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
1064 assert!(!v6.is_ipv4());
1065 assert!(v6.is_ipv6());