1 use crate::convert::TryInto;
7 use crate::net::{htons, ntohs, 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 {
230 matches!(*self, SocketAddr::V4(_))
233 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
234 /// [IPv6 address], and [`false`] otherwise.
236 /// [`true`]: ../../std/primitive.bool.html
237 /// [`false`]: ../../std/primitive.bool.html
238 /// [IP address]: ../../std/net/enum.IpAddr.html
239 /// [IPv6 address]: ../../std/net/enum.IpAddr.html#variant.V6
244 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
246 /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
247 /// assert_eq!(socket.is_ipv4(), false);
248 /// assert_eq!(socket.is_ipv6(), true);
250 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
251 pub fn is_ipv6(&self) -> bool {
252 matches!(*self, SocketAddr::V6(_))
257 /// Creates a new socket address from an [IPv4 address] and a port number.
259 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
264 /// use std::net::{SocketAddrV4, Ipv4Addr};
266 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
271 inner: c::sockaddr_in {
272 sin_family: c::AF_INET as c::sa_family_t,
273 sin_port: htons(port),
274 sin_addr: *ip.as_inner(),
275 ..unsafe { mem::zeroed() }
280 /// Returns the IP address associated with this socket address.
285 /// use std::net::{SocketAddrV4, Ipv4Addr};
287 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
288 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn ip(&self) -> &Ipv4Addr {
292 unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
295 /// Changes the IP address associated with this socket address.
300 /// use std::net::{SocketAddrV4, Ipv4Addr};
302 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
303 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
304 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
306 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
307 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
308 self.inner.sin_addr = *new_ip.as_inner()
311 /// Returns the port number associated with this socket address.
316 /// use std::net::{SocketAddrV4, Ipv4Addr};
318 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
319 /// assert_eq!(socket.port(), 8080);
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub fn port(&self) -> u16 {
323 ntohs(self.inner.sin_port)
326 /// Changes the port number associated with this socket address.
331 /// use std::net::{SocketAddrV4, Ipv4Addr};
333 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
334 /// socket.set_port(4242);
335 /// assert_eq!(socket.port(), 4242);
337 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
338 pub fn set_port(&mut self, new_port: u16) {
339 self.inner.sin_port = htons(new_port);
344 /// Creates a new socket address from an [IPv6 address], a 16-bit port number,
345 /// and the `flowinfo` and `scope_id` fields.
347 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
348 /// parameters, see [IETF RFC 2553, Section 3.3].
350 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
351 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
356 /// use std::net::{SocketAddrV6, Ipv6Addr};
358 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
363 inner: c::sockaddr_in6 {
364 sin6_family: c::AF_INET6 as c::sa_family_t,
365 sin6_port: htons(port),
366 sin6_addr: *ip.as_inner(),
367 sin6_flowinfo: flowinfo,
368 sin6_scope_id: scope_id,
369 ..unsafe { mem::zeroed() }
374 /// Returns the IP address associated with this socket address.
379 /// use std::net::{SocketAddrV6, Ipv6Addr};
381 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
382 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
384 #[stable(feature = "rust1", since = "1.0.0")]
385 pub fn ip(&self) -> &Ipv6Addr {
386 unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }
389 /// Changes the IP address associated with this socket address.
394 /// use std::net::{SocketAddrV6, Ipv6Addr};
396 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
397 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
398 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
400 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
401 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
402 self.inner.sin6_addr = *new_ip.as_inner()
405 /// Returns the port number associated with this socket address.
410 /// use std::net::{SocketAddrV6, Ipv6Addr};
412 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
413 /// assert_eq!(socket.port(), 8080);
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn port(&self) -> u16 {
417 ntohs(self.inner.sin6_port)
420 /// Changes the port number associated with this socket address.
425 /// use std::net::{SocketAddrV6, Ipv6Addr};
427 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
428 /// socket.set_port(4242);
429 /// assert_eq!(socket.port(), 4242);
431 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
432 pub fn set_port(&mut self, new_port: u16) {
433 self.inner.sin6_port = htons(new_port);
436 /// Returns the flow information associated with this address.
438 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
439 /// as specified in [IETF RFC 2553, Section 3.3].
440 /// It combines information about the flow label and the traffic class as specified
441 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
443 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
444 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
445 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
446 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
451 /// use std::net::{SocketAddrV6, Ipv6Addr};
453 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
454 /// assert_eq!(socket.flowinfo(), 10);
456 #[stable(feature = "rust1", since = "1.0.0")]
457 pub fn flowinfo(&self) -> u32 {
458 self.inner.sin6_flowinfo
461 /// Changes the flow information associated with this socket address.
463 /// See the [`flowinfo`] method's documentation for more details.
465 /// [`flowinfo`]: #method.flowinfo
470 /// use std::net::{SocketAddrV6, Ipv6Addr};
472 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
473 /// socket.set_flowinfo(56);
474 /// assert_eq!(socket.flowinfo(), 56);
476 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
477 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
478 self.inner.sin6_flowinfo = new_flowinfo;
481 /// Returns the scope ID associated with this address.
483 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
484 /// as specified in [IETF RFC 2553, Section 3.3].
486 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
491 /// use std::net::{SocketAddrV6, Ipv6Addr};
493 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
494 /// assert_eq!(socket.scope_id(), 78);
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub fn scope_id(&self) -> u32 {
498 self.inner.sin6_scope_id
501 /// Changes the scope ID associated with this socket address.
503 /// See the [`scope_id`] method's documentation for more details.
505 /// [`scope_id`]: #method.scope_id
510 /// use std::net::{SocketAddrV6, Ipv6Addr};
512 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
513 /// socket.set_scope_id(42);
514 /// assert_eq!(socket.scope_id(), 42);
516 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
517 pub fn set_scope_id(&mut self, new_scope_id: u32) {
518 self.inner.sin6_scope_id = new_scope_id;
522 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
523 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
524 SocketAddrV4 { inner: addr }
528 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
529 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
530 SocketAddrV6 { inner: addr }
534 #[stable(feature = "ip_from_ip", since = "1.16.0")]
535 impl From<SocketAddrV4> for SocketAddr {
536 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
538 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
539 /// [`SocketAddr::V4`]: ../../std/net/enum.SocketAddr.html#variant.V4
540 fn from(sock4: SocketAddrV4) -> SocketAddr {
541 SocketAddr::V4(sock4)
545 #[stable(feature = "ip_from_ip", since = "1.16.0")]
546 impl From<SocketAddrV6> for SocketAddr {
547 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
549 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
550 /// [`SocketAddr::V6`]: ../../std/net/enum.SocketAddr.html#variant.V6
551 fn from(sock6: SocketAddrV6) -> SocketAddr {
552 SocketAddr::V6(sock6)
556 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
557 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
558 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
560 /// This conversion creates a [`SocketAddr::V4`] for a [`IpAddr::V4`]
561 /// and creates a [`SocketAddr::V6`] for a [`IpAddr::V6`].
563 /// `u16` is treated as port of the newly created [`SocketAddr`].
565 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
566 /// [`IpAddr::V4`]: ../../std/net/enum.IpAddr.html#variant.V4
567 /// [`IpAddr::V6`]: ../../std/net/enum.IpAddr.html#variant.V6
568 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
569 /// [`SocketAddr::V4`]: ../../std/net/enum.SocketAddr.html#variant.V4
570 /// [`SocketAddr::V6`]: ../../std/net/enum.SocketAddr.html#variant.V6
571 fn from(pieces: (I, u16)) -> SocketAddr {
572 SocketAddr::new(pieces.0.into(), pieces.1)
576 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
577 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
579 SocketAddr::V4(ref a) => {
580 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
582 SocketAddr::V6(ref a) => {
583 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl fmt::Display for SocketAddr {
591 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593 SocketAddr::V4(ref a) => a.fmt(f),
594 SocketAddr::V6(ref a) => a.fmt(f),
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl fmt::Display for SocketAddrV4 {
601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602 write!(f, "{}:{}", self.ip(), self.port())
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl fmt::Debug for SocketAddrV4 {
608 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
609 fmt::Display::fmt(self, fmt)
613 #[stable(feature = "rust1", since = "1.0.0")]
614 impl fmt::Display for SocketAddrV6 {
615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616 write!(f, "[{}]:{}", self.ip(), self.port())
620 #[stable(feature = "rust1", since = "1.0.0")]
621 impl fmt::Debug for SocketAddrV6 {
622 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
623 fmt::Display::fmt(self, fmt)
627 #[stable(feature = "rust1", since = "1.0.0")]
628 impl Clone for SocketAddrV4 {
629 fn clone(&self) -> SocketAddrV4 {
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl Clone for SocketAddrV6 {
635 fn clone(&self) -> SocketAddrV6 {
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl PartialEq for SocketAddrV4 {
642 fn eq(&self, other: &SocketAddrV4) -> bool {
643 self.inner.sin_port == other.inner.sin_port
644 && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl PartialEq for SocketAddrV6 {
649 fn eq(&self, other: &SocketAddrV6) -> bool {
650 self.inner.sin6_port == other.inner.sin6_port
651 && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
652 && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
653 && self.inner.sin6_scope_id == other.inner.sin6_scope_id
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl Eq for SocketAddrV4 {}
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl Eq for SocketAddrV6 {}
661 #[stable(feature = "rust1", since = "1.0.0")]
662 impl hash::Hash for SocketAddrV4 {
663 fn hash<H: hash::Hasher>(&self, s: &mut H) {
664 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl hash::Hash for SocketAddrV6 {
669 fn hash<H: hash::Hasher>(&self, s: &mut H) {
671 self.inner.sin6_port,
672 &self.inner.sin6_addr.s6_addr,
673 self.inner.sin6_flowinfo,
674 self.inner.sin6_scope_id,
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>> {
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl ToSocketAddrs for (&str, u16) {
880 type Iter = vec::IntoIter<SocketAddr>;
881 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
882 let (host, port) = *self;
884 // try to parse the host as a regular IP address first
885 if let Ok(addr) = host.parse::<Ipv4Addr>() {
886 let addr = SocketAddrV4::new(addr, port);
887 return Ok(vec![SocketAddr::V4(addr)].into_iter());
889 if let Ok(addr) = host.parse::<Ipv6Addr>() {
890 let addr = SocketAddrV6::new(addr, port, 0, 0);
891 return Ok(vec![SocketAddr::V6(addr)].into_iter());
894 resolve_socket_addr((host, port).try_into()?)
898 // accepts strings like 'localhost:12345'
899 #[stable(feature = "rust1", since = "1.0.0")]
900 impl ToSocketAddrs for str {
901 type Iter = vec::IntoIter<SocketAddr>;
902 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
903 // try to parse as a regular SocketAddr first
904 if let Ok(addr) = self.parse() {
905 return Ok(vec![addr].into_iter());
908 resolve_socket_addr(self.try_into()?)
912 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
913 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
914 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
916 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
917 Ok(self.iter().cloned())
921 #[stable(feature = "rust1", since = "1.0.0")]
922 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
924 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
925 (**self).to_socket_addrs()
929 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
930 impl ToSocketAddrs for String {
931 type Iter = vec::IntoIter<SocketAddr>;
932 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
933 (&**self).to_socket_addrs()
937 #[cfg(all(test, not(target_os = "emscripten")))]
939 use crate::net::test::{sa4, sa6, tsa};
943 fn to_socket_addr_ipaddr_u16() {
944 let a = Ipv4Addr::new(77, 88, 21, 11);
946 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
947 assert_eq!(Ok(vec![e]), tsa((a, p)));
951 fn to_socket_addr_str_u16() {
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_str() {
967 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
968 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
970 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
971 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
973 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
974 #[cfg(not(target_env = "sgx"))]
975 assert!(tsa("localhost:23924").unwrap().contains(&a));
976 #[cfg(target_env = "sgx")]
981 fn to_socket_addr_string() {
982 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
983 assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
984 assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
985 assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
987 let s = format!("{}:{}", "77.88.21.11", "24352");
988 assert_eq!(Ok(vec![a]), tsa(s));
989 // s has been moved into the tsa call
992 // FIXME: figure out why this fails on openbsd and fix it
994 #[cfg(not(any(windows, target_os = "openbsd")))]
995 fn to_socket_addr_str_bad() {
996 assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
1001 fn ip4(low: u8) -> Ipv4Addr {
1002 Ipv4Addr::new(77, 88, 21, low)
1004 fn ip6(low: u16) -> Ipv6Addr {
1005 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low)
1008 let mut v4 = SocketAddrV4::new(ip4(11), 80);
1009 assert_eq!(v4.ip(), &ip4(11));
1011 assert_eq!(v4.ip(), &ip4(12));
1013 let mut addr = SocketAddr::V4(v4);
1014 assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
1015 addr.set_ip(IpAddr::V4(ip4(13)));
1016 assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
1017 addr.set_ip(IpAddr::V6(ip6(14)));
1018 assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
1020 let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1021 assert_eq!(v6.ip(), &ip6(1));
1023 assert_eq!(v6.ip(), &ip6(2));
1025 let mut addr = SocketAddr::V6(v6);
1026 assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
1027 addr.set_ip(IpAddr::V6(ip6(3)));
1028 assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
1029 addr.set_ip(IpAddr::V4(ip4(4)));
1030 assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
1035 let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1036 assert_eq!(v4.port(), 80);
1038 assert_eq!(v4.port(), 443);
1040 let mut addr = SocketAddr::V4(v4);
1041 assert_eq!(addr.port(), 443);
1042 addr.set_port(8080);
1043 assert_eq!(addr.port(), 8080);
1045 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1046 assert_eq!(v6.port(), 80);
1048 assert_eq!(v6.port(), 443);
1050 let mut addr = SocketAddr::V6(v6);
1051 assert_eq!(addr.port(), 443);
1052 addr.set_port(8080);
1053 assert_eq!(addr.port(), 8080);
1058 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1059 assert_eq!(v6.flowinfo(), 10);
1060 v6.set_flowinfo(20);
1061 assert_eq!(v6.flowinfo(), 20);
1066 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1067 assert_eq!(v6.scope_id(), 10);
1068 v6.set_scope_id(20);
1069 assert_eq!(v6.scope_id(), 20);
1074 let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1075 assert!(v4.is_ipv4());
1076 assert!(!v4.is_ipv6());
1081 let v6 = SocketAddr::V6(SocketAddrV6::new(
1082 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1),
1087 assert!(!v6.is_ipv4());
1088 assert!(v6.is_ipv6());