1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::cmp::Ordering;
7 use crate::io::{self, Write};
10 use crate::net::{htons, ntohs, IpAddr, Ipv4Addr, Ipv6Addr};
13 use crate::sys::net::netc as c;
14 use crate::sys_common::net::LookupHost;
15 use crate::sys_common::{AsInner, FromInner, IntoInner};
18 /// An internet socket address, either IPv4 or IPv6.
20 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
21 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
22 /// [`SocketAddrV6`]'s respective documentation for more details.
24 /// The size of a `SocketAddr` instance may vary depending on the target operating
27 /// [IP address]: IpAddr
32 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
34 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
36 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
37 /// assert_eq!(socket.port(), 8080);
38 /// assert_eq!(socket.is_ipv4(), true);
40 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
41 #[stable(feature = "rust1", since = "1.0.0")]
43 /// An IPv4 socket address.
44 #[stable(feature = "rust1", since = "1.0.0")]
45 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
46 /// An IPv6 socket address.
47 #[stable(feature = "rust1", since = "1.0.0")]
48 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
51 /// An IPv4 socket address.
53 /// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
54 /// stated in [IETF RFC 793].
56 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
58 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
59 /// system. Do not assume that this type has the same memory layout as the underlying
60 /// system representation.
62 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
63 /// [`IPv4` address]: Ipv4Addr
68 /// use std::net::{Ipv4Addr, SocketAddrV4};
70 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
72 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
73 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
74 /// assert_eq!(socket.port(), 8080);
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct SocketAddrV4 {
79 // Do not assume that this struct is implemented as the underlying system representation.
80 // The memory layout is not part of the stable interface that std exposes.
81 inner: c::sockaddr_in,
84 /// An IPv6 socket address.
86 /// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
87 /// as fields containing the traffic class, the flow label, and a scope identifier
88 /// (see [IETF RFC 2553, Section 3.3] for more details).
90 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
92 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
93 /// system. Do not assume that this type has the same memory layout as the underlying
94 /// system representation.
96 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
97 /// [`IPv6` address]: Ipv6Addr
102 /// use std::net::{Ipv6Addr, SocketAddrV6};
104 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
106 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
107 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
108 /// assert_eq!(socket.port(), 8080);
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct SocketAddrV6 {
113 // Do not assume that this struct is implemented as the underlying system representation.
114 // The memory layout is not part of the stable interface that std exposes.
115 inner: c::sockaddr_in6,
119 /// Creates a new socket address from an [IP address] and a port number.
121 /// [IP address]: IpAddr
126 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
128 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
129 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
130 /// assert_eq!(socket.port(), 8080);
132 #[stable(feature = "ip_addr", since = "1.7.0")]
134 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
136 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
137 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
141 /// Returns the IP address associated with this socket address.
146 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
148 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
149 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
152 #[stable(feature = "ip_addr", since = "1.7.0")]
153 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
154 pub const fn ip(&self) -> IpAddr {
156 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
157 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
161 /// Changes the IP address associated with this socket address.
166 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
168 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
169 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
170 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
172 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
173 pub fn set_ip(&mut self, new_ip: IpAddr) {
174 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
175 match (self, new_ip) {
176 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
177 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
178 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
182 /// Returns the port number associated with this socket address.
187 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
189 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
190 /// assert_eq!(socket.port(), 8080);
193 #[stable(feature = "rust1", since = "1.0.0")]
194 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
195 pub const fn port(&self) -> u16 {
197 SocketAddr::V4(ref a) => a.port(),
198 SocketAddr::V6(ref a) => a.port(),
202 /// Changes the port number associated with this socket address.
207 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
209 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
210 /// socket.set_port(1025);
211 /// assert_eq!(socket.port(), 1025);
213 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
214 pub fn set_port(&mut self, new_port: u16) {
216 SocketAddr::V4(ref mut a) => a.set_port(new_port),
217 SocketAddr::V6(ref mut a) => a.set_port(new_port),
221 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
222 /// [`IPv4` address], and [`false`] otherwise.
224 /// [IP address]: IpAddr
225 /// [`IPv4` address]: IpAddr::V4
230 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
232 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
233 /// assert_eq!(socket.is_ipv4(), true);
234 /// assert_eq!(socket.is_ipv6(), false);
237 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
238 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
239 pub const fn is_ipv4(&self) -> bool {
240 matches!(*self, SocketAddr::V4(_))
243 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
244 /// [`IPv6` address], and [`false`] otherwise.
246 /// [IP address]: IpAddr
247 /// [`IPv6` address]: IpAddr::V6
252 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
254 /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
255 /// assert_eq!(socket.is_ipv4(), false);
256 /// assert_eq!(socket.is_ipv6(), true);
259 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
260 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
261 pub const fn is_ipv6(&self) -> bool {
262 matches!(*self, SocketAddr::V6(_))
267 /// Creates a new socket address from an [`IPv4` address] and a port number.
269 /// [`IPv4` address]: Ipv4Addr
274 /// use std::net::{SocketAddrV4, Ipv4Addr};
276 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
278 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
282 inner: c::sockaddr_in {
283 sin_family: c::AF_INET as c::sa_family_t,
284 sin_port: htons(port),
285 sin_addr: ip.into_inner(),
286 ..unsafe { mem::zeroed() }
291 /// Returns the IP address associated with this socket address.
296 /// use std::net::{SocketAddrV4, Ipv4Addr};
298 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
299 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
302 #[stable(feature = "rust1", since = "1.0.0")]
303 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
304 pub const fn ip(&self) -> &Ipv4Addr {
305 // SAFETY: `Ipv4Addr` is `#[repr(C)] struct { _: in_addr; }`.
306 // It is safe to cast from `&in_addr` to `&Ipv4Addr`.
307 unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
310 /// Changes the IP address associated with this socket address.
315 /// use std::net::{SocketAddrV4, Ipv4Addr};
317 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
318 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
319 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
321 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
322 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
323 self.inner.sin_addr = new_ip.into_inner()
326 /// Returns the port number associated with this socket address.
331 /// use std::net::{SocketAddrV4, Ipv4Addr};
333 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
334 /// assert_eq!(socket.port(), 8080);
337 #[stable(feature = "rust1", since = "1.0.0")]
338 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
339 pub const fn port(&self) -> u16 {
340 ntohs(self.inner.sin_port)
343 /// Changes the port number associated with this socket address.
348 /// use std::net::{SocketAddrV4, Ipv4Addr};
350 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
351 /// socket.set_port(4242);
352 /// assert_eq!(socket.port(), 4242);
354 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
355 pub fn set_port(&mut self, new_port: u16) {
356 self.inner.sin_port = htons(new_port);
361 /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
362 /// and the `flowinfo` and `scope_id` fields.
364 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
365 /// parameters, see [IETF RFC 2553, Section 3.3].
367 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
368 /// [`IPv6` address]: Ipv6Addr
373 /// use std::net::{SocketAddrV6, Ipv6Addr};
375 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
377 #[stable(feature = "rust1", since = "1.0.0")]
379 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
381 inner: c::sockaddr_in6 {
382 sin6_family: c::AF_INET6 as c::sa_family_t,
383 sin6_port: htons(port),
384 sin6_addr: *ip.as_inner(),
385 sin6_flowinfo: flowinfo,
386 sin6_scope_id: scope_id,
387 ..unsafe { mem::zeroed() }
392 /// Returns the IP address associated with this socket address.
397 /// use std::net::{SocketAddrV6, Ipv6Addr};
399 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
400 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
403 #[stable(feature = "rust1", since = "1.0.0")]
404 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
405 pub const fn ip(&self) -> &Ipv6Addr {
406 unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }
409 /// Changes the IP address associated with this socket address.
414 /// use std::net::{SocketAddrV6, Ipv6Addr};
416 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
417 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
418 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
420 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
421 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
422 self.inner.sin6_addr = *new_ip.as_inner()
425 /// Returns the port number associated with this socket address.
430 /// use std::net::{SocketAddrV6, Ipv6Addr};
432 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
433 /// assert_eq!(socket.port(), 8080);
436 #[stable(feature = "rust1", since = "1.0.0")]
437 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
438 pub const fn port(&self) -> u16 {
439 ntohs(self.inner.sin6_port)
442 /// Changes the port number associated with this socket address.
447 /// use std::net::{SocketAddrV6, Ipv6Addr};
449 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
450 /// socket.set_port(4242);
451 /// assert_eq!(socket.port(), 4242);
453 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
454 pub fn set_port(&mut self, new_port: u16) {
455 self.inner.sin6_port = htons(new_port);
458 /// Returns the flow information associated with this address.
460 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
461 /// as specified in [IETF RFC 2553, Section 3.3].
462 /// It combines information about the flow label and the traffic class as specified
463 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
465 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
466 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
467 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
468 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
473 /// use std::net::{SocketAddrV6, Ipv6Addr};
475 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
476 /// assert_eq!(socket.flowinfo(), 10);
479 #[stable(feature = "rust1", since = "1.0.0")]
480 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
481 pub const fn flowinfo(&self) -> u32 {
482 self.inner.sin6_flowinfo
485 /// Changes the flow information associated with this socket address.
487 /// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
492 /// use std::net::{SocketAddrV6, Ipv6Addr};
494 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
495 /// socket.set_flowinfo(56);
496 /// assert_eq!(socket.flowinfo(), 56);
498 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
499 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
500 self.inner.sin6_flowinfo = new_flowinfo;
503 /// Returns the scope ID associated with this address.
505 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
506 /// as specified in [IETF RFC 2553, Section 3.3].
508 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
513 /// use std::net::{SocketAddrV6, Ipv6Addr};
515 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
516 /// assert_eq!(socket.scope_id(), 78);
519 #[stable(feature = "rust1", since = "1.0.0")]
520 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
521 pub const fn scope_id(&self) -> u32 {
522 self.inner.sin6_scope_id
525 /// Changes the scope ID associated with this socket address.
527 /// See [`SocketAddrV6::scope_id`]'s documentation for more details.
532 /// use std::net::{SocketAddrV6, Ipv6Addr};
534 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
535 /// socket.set_scope_id(42);
536 /// assert_eq!(socket.scope_id(), 42);
538 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
539 pub fn set_scope_id(&mut self, new_scope_id: u32) {
540 self.inner.sin6_scope_id = new_scope_id;
544 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
545 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
546 SocketAddrV4 { inner: addr }
550 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
551 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
552 SocketAddrV6 { inner: addr }
556 #[stable(feature = "ip_from_ip", since = "1.16.0")]
557 impl From<SocketAddrV4> for SocketAddr {
558 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
559 fn from(sock4: SocketAddrV4) -> SocketAddr {
560 SocketAddr::V4(sock4)
564 #[stable(feature = "ip_from_ip", since = "1.16.0")]
565 impl From<SocketAddrV6> for SocketAddr {
566 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
567 fn from(sock6: SocketAddrV6) -> SocketAddr {
568 SocketAddr::V6(sock6)
572 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
573 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
574 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
576 /// This conversion creates a [`SocketAddr::V4`] for an [`IpAddr::V4`]
577 /// and creates a [`SocketAddr::V6`] for an [`IpAddr::V6`].
579 /// `u16` is treated as port of the newly created [`SocketAddr`].
580 fn from(pieces: (I, u16)) -> SocketAddr {
581 SocketAddr::new(pieces.0.into(), pieces.1)
585 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
586 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
588 SocketAddr::V4(ref a) => {
589 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
591 SocketAddr::V6(ref a) => {
592 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl fmt::Display for SocketAddr {
600 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602 SocketAddr::V4(ref a) => a.fmt(f),
603 SocketAddr::V6(ref a) => a.fmt(f),
608 #[stable(feature = "rust1", since = "1.0.0")]
609 impl fmt::Debug for SocketAddr {
610 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
611 fmt::Display::fmt(self, fmt)
615 #[stable(feature = "rust1", since = "1.0.0")]
616 impl fmt::Display for SocketAddrV4 {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 // Fast path: if there's no alignment stuff, write to the output buffer
620 if f.precision().is_none() && f.width().is_none() {
621 write!(f, "{}:{}", self.ip(), self.port())
623 const IPV4_SOCKET_BUF_LEN: usize = (3 * 4) // the segments
624 + 3 // the separators
626 let mut buf = [0; IPV4_SOCKET_BUF_LEN];
627 let mut buf_slice = &mut buf[..];
629 // Unwrap is fine because writing to a sufficiently-sized
630 // buffer is infallible
631 write!(buf_slice, "{}:{}", self.ip(), self.port()).unwrap();
632 let len = IPV4_SOCKET_BUF_LEN - buf_slice.len();
634 // This unsafe is OK because we know what is being written to the buffer
635 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
641 #[stable(feature = "rust1", since = "1.0.0")]
642 impl fmt::Debug for SocketAddrV4 {
643 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
644 fmt::Display::fmt(self, fmt)
648 #[stable(feature = "rust1", since = "1.0.0")]
649 impl fmt::Display for SocketAddrV6 {
650 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
651 // Fast path: if there's no alignment stuff, write to the output
653 if f.precision().is_none() && f.width().is_none() {
654 match self.scope_id() {
655 0 => write!(f, "[{}]:{}", self.ip(), self.port()),
656 scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
659 const IPV6_SOCKET_BUF_LEN: usize = (4 * 8) // The address
660 + 7 // The colon separators
662 + 1 + 10 // The scope id
665 let mut buf = [0; IPV6_SOCKET_BUF_LEN];
666 let mut buf_slice = &mut buf[..];
668 match self.scope_id() {
669 0 => write!(buf_slice, "[{}]:{}", self.ip(), self.port()),
670 scope_id => write!(buf_slice, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
672 // Unwrap is fine because writing to a sufficiently-sized
673 // buffer is infallible
675 let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
677 // This unsafe is OK because we know what is being written to the buffer
678 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl fmt::Debug for SocketAddrV6 {
686 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
687 fmt::Display::fmt(self, fmt)
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl Clone for SocketAddrV4 {
693 fn clone(&self) -> SocketAddrV4 {
697 #[stable(feature = "rust1", since = "1.0.0")]
698 impl Clone for SocketAddrV6 {
699 fn clone(&self) -> SocketAddrV6 {
704 #[stable(feature = "rust1", since = "1.0.0")]
705 impl PartialEq for SocketAddrV4 {
706 fn eq(&self, other: &SocketAddrV4) -> bool {
707 self.inner.sin_port == other.inner.sin_port
708 && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
711 #[stable(feature = "rust1", since = "1.0.0")]
712 impl PartialEq for SocketAddrV6 {
713 fn eq(&self, other: &SocketAddrV6) -> bool {
714 self.inner.sin6_port == other.inner.sin6_port
715 && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
716 && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
717 && self.inner.sin6_scope_id == other.inner.sin6_scope_id
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl Eq for SocketAddrV4 {}
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl Eq for SocketAddrV6 {}
725 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
726 impl PartialOrd for SocketAddrV4 {
727 fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
728 Some(self.cmp(other))
732 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
733 impl PartialOrd for SocketAddrV6 {
734 fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
735 Some(self.cmp(other))
739 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
740 impl Ord for SocketAddrV4 {
741 fn cmp(&self, other: &SocketAddrV4) -> Ordering {
742 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
746 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
747 impl Ord for SocketAddrV6 {
748 fn cmp(&self, other: &SocketAddrV6) -> Ordering {
749 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl hash::Hash for SocketAddrV4 {
755 fn hash<H: hash::Hasher>(&self, s: &mut H) {
756 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
759 #[stable(feature = "rust1", since = "1.0.0")]
760 impl hash::Hash for SocketAddrV6 {
761 fn hash<H: hash::Hasher>(&self, s: &mut H) {
763 self.inner.sin6_port,
764 &self.inner.sin6_addr.s6_addr,
765 self.inner.sin6_flowinfo,
766 self.inner.sin6_scope_id,
772 /// A trait for objects which can be converted or resolved to one or more
773 /// [`SocketAddr`] values.
775 /// This trait is used for generic address resolution when constructing network
776 /// objects. By default it is implemented for the following types:
778 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
780 /// * [`SocketAddrV4`], [`SocketAddrV6`], <code>([IpAddr], [u16])</code>,
781 /// <code>([Ipv4Addr], [u16])</code>, <code>([Ipv6Addr], [u16])</code>:
782 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
784 /// * <code>(&[str], [u16])</code>: <code>&[str]</code> should be either a string representation
785 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
786 /// name. [`u16`] is the port number.
788 /// * <code>&[str]</code>: the string should be either a string representation of a
789 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
790 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
792 /// This trait allows constructing network objects like [`TcpStream`] or
793 /// [`UdpSocket`] easily with values of various types for the bind/connection
794 /// address. It is needed because sometimes one type is more appropriate than
795 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
796 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
797 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
798 /// some other type (e.g., a string) just for it to be converted back to
799 /// [`SocketAddr`] in constructor methods is pointless.
801 /// Addresses returned by the operating system that are not IP addresses are
802 /// silently ignored.
804 /// [`FromStr`]: crate::str::FromStr "std::str::FromStr"
805 /// [`TcpStream`]: crate::net::TcpStream "net::TcpStream"
806 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
807 /// [`UdpSocket`]: crate::net::UdpSocket "net::UdpSocket"
811 /// Creating a [`SocketAddr`] iterator that yields one item:
814 /// use std::net::{ToSocketAddrs, SocketAddr};
816 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
817 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
819 /// assert_eq!(Some(addr), addrs_iter.next());
820 /// assert!(addrs_iter.next().is_none());
823 /// Creating a [`SocketAddr`] iterator from a hostname:
826 /// use std::net::{SocketAddr, ToSocketAddrs};
828 /// // assuming 'localhost' resolves to 127.0.0.1
829 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
830 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
831 /// assert!(addrs_iter.next().is_none());
833 /// // assuming 'foo' does not resolve
834 /// assert!("foo:443".to_socket_addrs().is_err());
837 /// Creating a [`SocketAddr`] iterator that yields multiple items:
840 /// use std::net::{SocketAddr, ToSocketAddrs};
842 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
843 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
844 /// let addrs = vec![addr1, addr2];
846 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
848 /// assert_eq!(Some(addr1), addrs_iter.next());
849 /// assert_eq!(Some(addr2), addrs_iter.next());
850 /// assert!(addrs_iter.next().is_none());
853 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
854 /// socket address `&str` (missing the port):
858 /// use std::net::ToSocketAddrs;
860 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
861 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
864 /// [`TcpStream::connect`] is an example of an function that utilizes
865 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
869 /// use std::net::{TcpStream, Ipv4Addr};
871 /// let stream = TcpStream::connect(("127.0.0.1", 443));
873 /// let stream = TcpStream::connect("127.0.0.1:443");
875 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
878 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
879 #[stable(feature = "rust1", since = "1.0.0")]
880 pub trait ToSocketAddrs {
881 /// Returned iterator over socket addresses which this type may correspond
883 #[stable(feature = "rust1", since = "1.0.0")]
884 type Iter: Iterator<Item = SocketAddr>;
886 /// Converts this object to an iterator of resolved [`SocketAddr`]s.
888 /// The returned iterator might not actually yield any values depending on the
889 /// outcome of any resolution performed.
891 /// Note that this function may block the current thread while resolution is
893 #[stable(feature = "rust1", since = "1.0.0")]
894 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
897 #[stable(feature = "rust1", since = "1.0.0")]
898 impl ToSocketAddrs for SocketAddr {
899 type Iter = option::IntoIter<SocketAddr>;
900 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
901 Ok(Some(*self).into_iter())
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl ToSocketAddrs for SocketAddrV4 {
907 type Iter = option::IntoIter<SocketAddr>;
908 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
909 SocketAddr::V4(*self).to_socket_addrs()
913 #[stable(feature = "rust1", since = "1.0.0")]
914 impl ToSocketAddrs for SocketAddrV6 {
915 type Iter = option::IntoIter<SocketAddr>;
916 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
917 SocketAddr::V6(*self).to_socket_addrs()
921 #[stable(feature = "rust1", since = "1.0.0")]
922 impl ToSocketAddrs for (IpAddr, u16) {
923 type Iter = option::IntoIter<SocketAddr>;
924 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
925 let (ip, port) = *self;
927 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
928 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl ToSocketAddrs for (Ipv4Addr, u16) {
935 type Iter = option::IntoIter<SocketAddr>;
936 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
937 let (ip, port) = *self;
938 SocketAddrV4::new(ip, port).to_socket_addrs()
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl ToSocketAddrs for (Ipv6Addr, u16) {
944 type Iter = option::IntoIter<SocketAddr>;
945 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
946 let (ip, port) = *self;
947 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
951 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
962 #[stable(feature = "rust1", since = "1.0.0")]
963 impl ToSocketAddrs for (&str, u16) {
964 type Iter = vec::IntoIter<SocketAddr>;
965 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
966 let (host, port) = *self;
968 // try to parse the host as a regular IP address first
969 if let Ok(addr) = host.parse::<Ipv4Addr>() {
970 let addr = SocketAddrV4::new(addr, port);
971 return Ok(vec![SocketAddr::V4(addr)].into_iter());
973 if let Ok(addr) = host.parse::<Ipv6Addr>() {
974 let addr = SocketAddrV6::new(addr, port, 0, 0);
975 return Ok(vec![SocketAddr::V6(addr)].into_iter());
978 resolve_socket_addr((host, port).try_into()?)
982 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
983 impl ToSocketAddrs for (String, u16) {
984 type Iter = vec::IntoIter<SocketAddr>;
985 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
986 (&*self.0, self.1).to_socket_addrs()
990 // accepts strings like 'localhost:12345'
991 #[stable(feature = "rust1", since = "1.0.0")]
992 impl ToSocketAddrs for str {
993 type Iter = vec::IntoIter<SocketAddr>;
994 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
995 // try to parse as a regular SocketAddr first
996 if let Ok(addr) = self.parse() {
997 return Ok(vec![addr].into_iter());
1000 resolve_socket_addr(self.try_into()?)
1004 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
1005 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
1006 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
1008 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
1009 Ok(self.iter().cloned())
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
1015 type Iter = T::Iter;
1016 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
1017 (**self).to_socket_addrs()
1021 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
1022 impl ToSocketAddrs for String {
1023 type Iter = vec::IntoIter<SocketAddr>;
1024 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
1025 (&**self).to_socket_addrs()