1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::cmp::Ordering;
5 use crate::convert::TryInto;
8 use crate::io::{self, Write};
11 use crate::net::{htons, ntohs, IpAddr, Ipv4Addr, Ipv6Addr};
14 use crate::sys::net::netc as c;
15 use crate::sys_common::net::LookupHost;
16 use crate::sys_common::{AsInner, FromInner, IntoInner};
19 /// An internet socket address, either IPv4 or IPv6.
21 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
22 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
23 /// [`SocketAddrV6`]'s respective documentation for more details.
25 /// The size of a `SocketAddr` instance may vary depending on the target operating
28 /// [IP address]: IpAddr
33 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
35 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
37 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
38 /// assert_eq!(socket.port(), 8080);
39 /// assert_eq!(socket.is_ipv4(), true);
41 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
42 #[stable(feature = "rust1", since = "1.0.0")]
44 /// An IPv4 socket address.
45 #[stable(feature = "rust1", since = "1.0.0")]
46 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
47 /// An IPv6 socket address.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
52 /// An IPv4 socket address.
54 /// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
55 /// stated in [IETF RFC 793].
57 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
59 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
60 /// system. Do not assume that this type has the same memory layout as the underlying
61 /// system representation.
63 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
64 /// [`IPv4` address]: Ipv4Addr
69 /// use std::net::{Ipv4Addr, SocketAddrV4};
71 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
73 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
74 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
75 /// assert_eq!(socket.port(), 8080);
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub struct SocketAddrV4 {
80 // Do not assume that this struct is implemented as the underlying system representation.
81 // The memory layout is not part of the stable interface that std exposes.
82 inner: c::sockaddr_in,
85 /// An IPv6 socket address.
87 /// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
88 /// as fields containing the traffic class, the flow label, and a scope identifier
89 /// (see [IETF RFC 2553, Section 3.3] for more details).
91 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
93 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
94 /// system. Do not assume that this type has the same memory layout as the underlying
95 /// system representation.
97 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
98 /// [`IPv6` address]: Ipv6Addr
103 /// use std::net::{Ipv6Addr, SocketAddrV6};
105 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
107 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
108 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
109 /// assert_eq!(socket.port(), 8080);
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub struct SocketAddrV6 {
114 // Do not assume that this struct is implemented as the underlying system representation.
115 // The memory layout is not part of the stable interface that std exposes.
116 inner: c::sockaddr_in6,
120 /// Creates a new socket address from an [IP address] and a port number.
122 /// [IP address]: IpAddr
127 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
129 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
130 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
131 /// assert_eq!(socket.port(), 8080);
133 #[stable(feature = "ip_addr", since = "1.7.0")]
135 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
137 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
138 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
142 /// Returns the IP address associated with this socket address.
147 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
149 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
150 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
153 #[stable(feature = "ip_addr", since = "1.7.0")]
154 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
155 pub const fn ip(&self) -> IpAddr {
157 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
158 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
162 /// Changes the IP address associated with this socket address.
167 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
169 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
170 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
171 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
173 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
174 pub fn set_ip(&mut self, new_ip: IpAddr) {
175 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
176 match (self, new_ip) {
177 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
178 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
179 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
183 /// Returns the port number associated with this socket address.
188 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
190 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
191 /// assert_eq!(socket.port(), 8080);
194 #[stable(feature = "rust1", since = "1.0.0")]
195 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
196 pub const fn port(&self) -> u16 {
198 SocketAddr::V4(ref a) => a.port(),
199 SocketAddr::V6(ref a) => a.port(),
203 /// Changes the port number associated with this socket address.
208 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
210 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
211 /// socket.set_port(1025);
212 /// assert_eq!(socket.port(), 1025);
214 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
215 pub fn set_port(&mut self, new_port: u16) {
217 SocketAddr::V4(ref mut a) => a.set_port(new_port),
218 SocketAddr::V6(ref mut a) => a.set_port(new_port),
222 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
223 /// [`IPv4` address], and [`false`] otherwise.
225 /// [IP address]: IpAddr
226 /// [`IPv4` address]: IpAddr::V4
231 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
233 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
234 /// assert_eq!(socket.is_ipv4(), true);
235 /// assert_eq!(socket.is_ipv6(), false);
238 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
239 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
240 pub const fn is_ipv4(&self) -> bool {
241 matches!(*self, SocketAddr::V4(_))
244 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
245 /// [`IPv6` address], and [`false`] otherwise.
247 /// [IP address]: IpAddr
248 /// [`IPv6` address]: IpAddr::V6
253 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
255 /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
256 /// assert_eq!(socket.is_ipv4(), false);
257 /// assert_eq!(socket.is_ipv6(), true);
260 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
261 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
262 pub const fn is_ipv6(&self) -> bool {
263 matches!(*self, SocketAddr::V6(_))
268 /// Creates a new socket address from an [`IPv4` address] and a port number.
270 /// [`IPv4` address]: Ipv4Addr
275 /// use std::net::{SocketAddrV4, Ipv4Addr};
277 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
279 #[stable(feature = "rust1", since = "1.0.0")]
281 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
283 inner: c::sockaddr_in {
284 sin_family: c::AF_INET as c::sa_family_t,
285 sin_port: htons(port),
286 sin_addr: ip.into_inner(),
287 ..unsafe { mem::zeroed() }
292 /// Returns the IP address associated with this socket address.
297 /// use std::net::{SocketAddrV4, Ipv4Addr};
299 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
300 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
303 #[stable(feature = "rust1", since = "1.0.0")]
304 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
305 pub const fn ip(&self) -> &Ipv4Addr {
306 // SAFETY: `Ipv4Addr` is `#[repr(C)] struct { _: in_addr; }`.
307 // It is safe to cast from `&in_addr` to `&Ipv4Addr`.
308 unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
311 /// Changes the IP address associated with this socket address.
316 /// use std::net::{SocketAddrV4, Ipv4Addr};
318 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
319 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
320 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
322 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
323 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
324 self.inner.sin_addr = new_ip.into_inner()
327 /// Returns the port number associated with this socket address.
332 /// use std::net::{SocketAddrV4, Ipv4Addr};
334 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
335 /// assert_eq!(socket.port(), 8080);
338 #[stable(feature = "rust1", since = "1.0.0")]
339 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
340 pub const fn port(&self) -> u16 {
341 ntohs(self.inner.sin_port)
344 /// Changes the port number associated with this socket address.
349 /// use std::net::{SocketAddrV4, Ipv4Addr};
351 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
352 /// socket.set_port(4242);
353 /// assert_eq!(socket.port(), 4242);
355 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
356 pub fn set_port(&mut self, new_port: u16) {
357 self.inner.sin_port = htons(new_port);
362 /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
363 /// and the `flowinfo` and `scope_id` fields.
365 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
366 /// parameters, see [IETF RFC 2553, Section 3.3].
368 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
369 /// [`IPv6` address]: Ipv6Addr
374 /// use std::net::{SocketAddrV6, Ipv6Addr};
376 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
378 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
382 inner: c::sockaddr_in6 {
383 sin6_family: c::AF_INET6 as c::sa_family_t,
384 sin6_port: htons(port),
385 sin6_addr: *ip.as_inner(),
386 sin6_flowinfo: flowinfo,
387 sin6_scope_id: scope_id,
388 ..unsafe { mem::zeroed() }
393 /// Returns the IP address associated with this socket address.
398 /// use std::net::{SocketAddrV6, Ipv6Addr};
400 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
401 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
404 #[stable(feature = "rust1", since = "1.0.0")]
405 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
406 pub const fn ip(&self) -> &Ipv6Addr {
407 unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }
410 /// Changes the IP address associated with this socket address.
415 /// use std::net::{SocketAddrV6, Ipv6Addr};
417 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
418 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
419 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
421 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
422 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
423 self.inner.sin6_addr = *new_ip.as_inner()
426 /// Returns the port number associated with this socket address.
431 /// use std::net::{SocketAddrV6, Ipv6Addr};
433 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
434 /// assert_eq!(socket.port(), 8080);
437 #[stable(feature = "rust1", since = "1.0.0")]
438 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
439 pub const fn port(&self) -> u16 {
440 ntohs(self.inner.sin6_port)
443 /// Changes the port number associated with this socket address.
448 /// use std::net::{SocketAddrV6, Ipv6Addr};
450 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
451 /// socket.set_port(4242);
452 /// assert_eq!(socket.port(), 4242);
454 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
455 pub fn set_port(&mut self, new_port: u16) {
456 self.inner.sin6_port = htons(new_port);
459 /// Returns the flow information associated with this address.
461 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
462 /// as specified in [IETF RFC 2553, Section 3.3].
463 /// It combines information about the flow label and the traffic class as specified
464 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
466 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
467 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
468 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
469 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
474 /// use std::net::{SocketAddrV6, Ipv6Addr};
476 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
477 /// assert_eq!(socket.flowinfo(), 10);
480 #[stable(feature = "rust1", since = "1.0.0")]
481 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
482 pub const fn flowinfo(&self) -> u32 {
483 self.inner.sin6_flowinfo
486 /// Changes the flow information associated with this socket address.
488 /// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
493 /// use std::net::{SocketAddrV6, Ipv6Addr};
495 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
496 /// socket.set_flowinfo(56);
497 /// assert_eq!(socket.flowinfo(), 56);
499 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
500 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
501 self.inner.sin6_flowinfo = new_flowinfo;
504 /// Returns the scope ID associated with this address.
506 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
507 /// as specified in [IETF RFC 2553, Section 3.3].
509 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
514 /// use std::net::{SocketAddrV6, Ipv6Addr};
516 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
517 /// assert_eq!(socket.scope_id(), 78);
520 #[stable(feature = "rust1", since = "1.0.0")]
521 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
522 pub const fn scope_id(&self) -> u32 {
523 self.inner.sin6_scope_id
526 /// Changes the scope ID associated with this socket address.
528 /// See [`SocketAddrV6::scope_id`]'s documentation for more details.
533 /// use std::net::{SocketAddrV6, Ipv6Addr};
535 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
536 /// socket.set_scope_id(42);
537 /// assert_eq!(socket.scope_id(), 42);
539 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
540 pub fn set_scope_id(&mut self, new_scope_id: u32) {
541 self.inner.sin6_scope_id = new_scope_id;
545 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
546 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
547 SocketAddrV4 { inner: addr }
551 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
552 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
553 SocketAddrV6 { inner: addr }
557 #[stable(feature = "ip_from_ip", since = "1.16.0")]
558 impl From<SocketAddrV4> for SocketAddr {
559 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
560 fn from(sock4: SocketAddrV4) -> SocketAddr {
561 SocketAddr::V4(sock4)
565 #[stable(feature = "ip_from_ip", since = "1.16.0")]
566 impl From<SocketAddrV6> for SocketAddr {
567 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
568 fn from(sock6: SocketAddrV6) -> SocketAddr {
569 SocketAddr::V6(sock6)
573 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
574 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
575 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
577 /// This conversion creates a [`SocketAddr::V4`] for an [`IpAddr::V4`]
578 /// and creates a [`SocketAddr::V6`] for an [`IpAddr::V6`].
580 /// `u16` is treated as port of the newly created [`SocketAddr`].
581 fn from(pieces: (I, u16)) -> SocketAddr {
582 SocketAddr::new(pieces.0.into(), pieces.1)
586 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
587 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
589 SocketAddr::V4(ref a) => {
590 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
592 SocketAddr::V6(ref a) => {
593 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl fmt::Display for SocketAddr {
601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
603 SocketAddr::V4(ref a) => a.fmt(f),
604 SocketAddr::V6(ref a) => a.fmt(f),
609 #[stable(feature = "rust1", since = "1.0.0")]
610 impl fmt::Debug for SocketAddr {
611 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
612 fmt::Display::fmt(self, fmt)
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl fmt::Display for SocketAddrV4 {
618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619 // Fast path: if there's no alignment stuff, write to the output buffer
621 if f.precision().is_none() && f.width().is_none() {
622 write!(f, "{}:{}", self.ip(), self.port())
624 const IPV4_SOCKET_BUF_LEN: usize = (3 * 4) // the segments
625 + 3 // the separators
627 let mut buf = [0; IPV4_SOCKET_BUF_LEN];
628 let mut buf_slice = &mut buf[..];
630 // Unwrap is fine because writing to a sufficiently-sized
631 // buffer is infallible
632 write!(buf_slice, "{}:{}", self.ip(), self.port()).unwrap();
633 let len = IPV4_SOCKET_BUF_LEN - buf_slice.len();
635 // This unsafe is OK because we know what is being written to the buffer
636 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl fmt::Debug for SocketAddrV4 {
644 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
645 fmt::Display::fmt(self, fmt)
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl fmt::Display for SocketAddrV6 {
651 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652 // Fast path: if there's no alignment stuff, write to the output
654 if f.precision().is_none() && f.width().is_none() {
655 match self.scope_id() {
656 0 => write!(f, "[{}]:{}", self.ip(), self.port()),
657 scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
660 const IPV6_SOCKET_BUF_LEN: usize = (4 * 8) // The address
661 + 7 // The colon separators
663 + 1 + 10 // The scope id
666 let mut buf = [0; IPV6_SOCKET_BUF_LEN];
667 let mut buf_slice = &mut buf[..];
669 match self.scope_id() {
670 0 => write!(buf_slice, "[{}]:{}", self.ip(), self.port()),
671 scope_id => write!(buf_slice, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
673 // Unwrap is fine because writing to a sufficiently-sized
674 // buffer is infallible
676 let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
678 // This unsafe is OK because we know what is being written to the buffer
679 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
685 #[stable(feature = "rust1", since = "1.0.0")]
686 impl fmt::Debug for SocketAddrV6 {
687 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
688 fmt::Display::fmt(self, fmt)
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl Clone for SocketAddrV4 {
694 fn clone(&self) -> SocketAddrV4 {
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl Clone for SocketAddrV6 {
700 fn clone(&self) -> SocketAddrV6 {
705 #[stable(feature = "rust1", since = "1.0.0")]
706 impl PartialEq for SocketAddrV4 {
707 fn eq(&self, other: &SocketAddrV4) -> bool {
708 self.inner.sin_port == other.inner.sin_port
709 && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
712 #[stable(feature = "rust1", since = "1.0.0")]
713 impl PartialEq for SocketAddrV6 {
714 fn eq(&self, other: &SocketAddrV6) -> bool {
715 self.inner.sin6_port == other.inner.sin6_port
716 && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
717 && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
718 && self.inner.sin6_scope_id == other.inner.sin6_scope_id
721 #[stable(feature = "rust1", since = "1.0.0")]
722 impl Eq for SocketAddrV4 {}
723 #[stable(feature = "rust1", since = "1.0.0")]
724 impl Eq for SocketAddrV6 {}
726 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
727 impl PartialOrd for SocketAddrV4 {
728 fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
729 Some(self.cmp(other))
733 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
734 impl PartialOrd for SocketAddrV6 {
735 fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
736 Some(self.cmp(other))
740 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
741 impl Ord for SocketAddrV4 {
742 fn cmp(&self, other: &SocketAddrV4) -> Ordering {
743 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
747 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
748 impl Ord for SocketAddrV6 {
749 fn cmp(&self, other: &SocketAddrV6) -> Ordering {
750 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
754 #[stable(feature = "rust1", since = "1.0.0")]
755 impl hash::Hash for SocketAddrV4 {
756 fn hash<H: hash::Hasher>(&self, s: &mut H) {
757 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
760 #[stable(feature = "rust1", since = "1.0.0")]
761 impl hash::Hash for SocketAddrV6 {
762 fn hash<H: hash::Hasher>(&self, s: &mut H) {
764 self.inner.sin6_port,
765 &self.inner.sin6_addr.s6_addr,
766 self.inner.sin6_flowinfo,
767 self.inner.sin6_scope_id,
773 /// A trait for objects which can be converted or resolved to one or more
774 /// [`SocketAddr`] values.
776 /// This trait is used for generic address resolution when constructing network
777 /// objects. By default it is implemented for the following types:
779 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
781 /// * [`SocketAddrV4`], [`SocketAddrV6`], <code>([IpAddr], [u16])</code>,
782 /// <code>([Ipv4Addr], [u16])</code>, <code>([Ipv6Addr], [u16])</code>:
783 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
785 /// * <code>(&[str], [u16])</code>: <code>&[str]</code> should be either a string representation
786 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
787 /// name. [`u16`] is the port number.
789 /// * <code>&[str]</code>: the string should be either a string representation of a
790 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
791 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
793 /// This trait allows constructing network objects like [`TcpStream`] or
794 /// [`UdpSocket`] easily with values of various types for the bind/connection
795 /// address. It is needed because sometimes one type is more appropriate than
796 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
797 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
798 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
799 /// some other type (e.g., a string) just for it to be converted back to
800 /// [`SocketAddr`] in constructor methods is pointless.
802 /// Addresses returned by the operating system that are not IP addresses are
803 /// silently ignored.
805 /// [`FromStr`]: crate::str::FromStr "std::str::FromStr"
806 /// [`TcpStream`]: crate::net::TcpStream "net::TcpStream"
807 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
808 /// [`UdpSocket`]: crate::net::UdpSocket "net::UdpSocket"
812 /// Creating a [`SocketAddr`] iterator that yields one item:
815 /// use std::net::{ToSocketAddrs, SocketAddr};
817 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
818 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
820 /// assert_eq!(Some(addr), addrs_iter.next());
821 /// assert!(addrs_iter.next().is_none());
824 /// Creating a [`SocketAddr`] iterator from a hostname:
827 /// use std::net::{SocketAddr, ToSocketAddrs};
829 /// // assuming 'localhost' resolves to 127.0.0.1
830 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
831 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
832 /// assert!(addrs_iter.next().is_none());
834 /// // assuming 'foo' does not resolve
835 /// assert!("foo:443".to_socket_addrs().is_err());
838 /// Creating a [`SocketAddr`] iterator that yields multiple items:
841 /// use std::net::{SocketAddr, ToSocketAddrs};
843 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
844 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
845 /// let addrs = vec![addr1, addr2];
847 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
849 /// assert_eq!(Some(addr1), addrs_iter.next());
850 /// assert_eq!(Some(addr2), addrs_iter.next());
851 /// assert!(addrs_iter.next().is_none());
854 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
855 /// socket address `&str` (missing the port):
859 /// use std::net::ToSocketAddrs;
861 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
862 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
865 /// [`TcpStream::connect`] is an example of an function that utilizes
866 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
870 /// use std::net::{TcpStream, Ipv4Addr};
872 /// let stream = TcpStream::connect(("127.0.0.1", 443));
874 /// let stream = TcpStream::connect("127.0.0.1:443");
876 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
879 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
880 #[stable(feature = "rust1", since = "1.0.0")]
881 pub trait ToSocketAddrs {
882 /// Returned iterator over socket addresses which this type may correspond
884 #[stable(feature = "rust1", since = "1.0.0")]
885 type Iter: Iterator<Item = SocketAddr>;
887 /// Converts this object to an iterator of resolved [`SocketAddr`]s.
889 /// The returned iterator might not actually yield any values depending on the
890 /// outcome of any resolution performed.
892 /// Note that this function may block the current thread while resolution is
894 #[stable(feature = "rust1", since = "1.0.0")]
895 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl ToSocketAddrs for SocketAddr {
900 type Iter = option::IntoIter<SocketAddr>;
901 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
902 Ok(Some(*self).into_iter())
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl ToSocketAddrs for SocketAddrV4 {
908 type Iter = option::IntoIter<SocketAddr>;
909 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
910 SocketAddr::V4(*self).to_socket_addrs()
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl ToSocketAddrs for SocketAddrV6 {
916 type Iter = option::IntoIter<SocketAddr>;
917 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
918 SocketAddr::V6(*self).to_socket_addrs()
922 #[stable(feature = "rust1", since = "1.0.0")]
923 impl ToSocketAddrs for (IpAddr, u16) {
924 type Iter = option::IntoIter<SocketAddr>;
925 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
926 let (ip, port) = *self;
928 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
929 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl ToSocketAddrs for (Ipv4Addr, u16) {
936 type Iter = option::IntoIter<SocketAddr>;
937 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
938 let (ip, port) = *self;
939 SocketAddrV4::new(ip, port).to_socket_addrs()
943 #[stable(feature = "rust1", since = "1.0.0")]
944 impl ToSocketAddrs for (Ipv6Addr, u16) {
945 type Iter = option::IntoIter<SocketAddr>;
946 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
947 let (ip, port) = *self;
948 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
952 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl ToSocketAddrs for (&str, u16) {
965 type Iter = vec::IntoIter<SocketAddr>;
966 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
967 let (host, port) = *self;
969 // try to parse the host as a regular IP address first
970 if let Ok(addr) = host.parse::<Ipv4Addr>() {
971 let addr = SocketAddrV4::new(addr, port);
972 return Ok(vec![SocketAddr::V4(addr)].into_iter());
974 if let Ok(addr) = host.parse::<Ipv6Addr>() {
975 let addr = SocketAddrV6::new(addr, port, 0, 0);
976 return Ok(vec![SocketAddr::V6(addr)].into_iter());
979 resolve_socket_addr((host, port).try_into()?)
983 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
984 impl ToSocketAddrs for (String, u16) {
985 type Iter = vec::IntoIter<SocketAddr>;
986 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
987 (&*self.0, self.1).to_socket_addrs()
991 // accepts strings like 'localhost:12345'
992 #[stable(feature = "rust1", since = "1.0.0")]
993 impl ToSocketAddrs for str {
994 type Iter = vec::IntoIter<SocketAddr>;
995 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
996 // try to parse as a regular SocketAddr first
997 if let Ok(addr) = self.parse() {
998 return Ok(vec![addr].into_iter());
1001 resolve_socket_addr(self.try_into()?)
1005 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
1006 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
1007 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
1009 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
1010 Ok(self.iter().cloned())
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
1016 type Iter = T::Iter;
1017 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
1018 (**self).to_socket_addrs()
1022 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
1023 impl ToSocketAddrs for String {
1024 type Iter = vec::IntoIter<SocketAddr>;
1025 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
1026 (&**self).to_socket_addrs()