1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::cmp::Ordering;
5 use crate::fmt::{self, Write};
10 use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr};
13 use crate::sys::net::netc as c;
14 use crate::sys_common::net::LookupHost;
15 use crate::sys_common::{FromInner, IntoInner};
18 use super::display_buffer::DisplayBuffer;
20 /// An internet socket address, either IPv4 or IPv6.
22 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
23 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
24 /// [`SocketAddrV6`]'s respective documentation for more details.
26 /// The size of a `SocketAddr` instance may vary depending on the target operating
29 /// [IP address]: IpAddr
34 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
36 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
38 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
39 /// assert_eq!(socket.port(), 8080);
40 /// assert_eq!(socket.is_ipv4(), true);
42 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
43 #[stable(feature = "rust1", since = "1.0.0")]
45 /// An IPv4 socket address.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
48 /// An IPv6 socket address.
49 #[stable(feature = "rust1", since = "1.0.0")]
50 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
53 /// An IPv4 socket address.
55 /// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
56 /// stated in [IETF RFC 793].
58 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
60 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
61 /// system. Do not assume that this type has the same memory layout as the underlying
62 /// system representation.
64 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
65 /// [`IPv4` address]: Ipv4Addr
70 /// use std::net::{Ipv4Addr, SocketAddrV4};
72 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
74 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
75 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
76 /// assert_eq!(socket.port(), 8080);
78 #[derive(Copy, Clone, Eq, PartialEq)]
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub struct SocketAddrV4 {
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);
111 #[derive(Copy, Clone, Eq, PartialEq)]
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub struct SocketAddrV6 {
121 /// Creates a new socket address from an [IP address] and a port number.
123 /// [IP address]: IpAddr
128 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
130 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
131 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
132 /// assert_eq!(socket.port(), 8080);
134 #[stable(feature = "ip_addr", since = "1.7.0")]
136 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
137 pub const fn new(ip: IpAddr, port: u16) -> SocketAddr {
139 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
140 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
144 /// Returns the IP address associated with this socket address.
149 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
151 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
152 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
155 #[stable(feature = "ip_addr", since = "1.7.0")]
156 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
157 pub const fn ip(&self) -> IpAddr {
159 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
160 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
164 /// Changes the IP address associated with this socket address.
169 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
171 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
172 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
173 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
175 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
176 pub fn set_ip(&mut self, new_ip: IpAddr) {
177 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
178 match (self, new_ip) {
179 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
180 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
181 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
185 /// Returns the port number associated with this socket address.
190 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
192 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
193 /// assert_eq!(socket.port(), 8080);
196 #[stable(feature = "rust1", since = "1.0.0")]
197 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
198 pub const fn port(&self) -> u16 {
200 SocketAddr::V4(ref a) => a.port(),
201 SocketAddr::V6(ref a) => a.port(),
205 /// Changes the port number associated with this socket address.
210 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
212 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
213 /// socket.set_port(1025);
214 /// assert_eq!(socket.port(), 1025);
216 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
217 pub fn set_port(&mut self, new_port: u16) {
219 SocketAddr::V4(ref mut a) => a.set_port(new_port),
220 SocketAddr::V6(ref mut a) => a.set_port(new_port),
224 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
225 /// [`IPv4` address], and [`false`] otherwise.
227 /// [IP address]: IpAddr
228 /// [`IPv4` address]: IpAddr::V4
233 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
235 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
236 /// assert_eq!(socket.is_ipv4(), true);
237 /// assert_eq!(socket.is_ipv6(), false);
240 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
241 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
242 pub const fn is_ipv4(&self) -> bool {
243 matches!(*self, SocketAddr::V4(_))
246 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
247 /// [`IPv6` address], and [`false`] otherwise.
249 /// [IP address]: IpAddr
250 /// [`IPv6` address]: IpAddr::V6
255 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
257 /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
258 /// assert_eq!(socket.is_ipv4(), false);
259 /// assert_eq!(socket.is_ipv6(), true);
262 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
263 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
264 pub const fn is_ipv6(&self) -> bool {
265 matches!(*self, SocketAddr::V6(_))
270 /// Creates a new socket address from an [`IPv4` address] and a port number.
272 /// [`IPv4` address]: Ipv4Addr
277 /// use std::net::{SocketAddrV4, Ipv4Addr};
279 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
281 #[stable(feature = "rust1", since = "1.0.0")]
283 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
284 pub const fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
285 SocketAddrV4 { ip, port }
288 /// Returns the IP address associated with this socket address.
293 /// use std::net::{SocketAddrV4, Ipv4Addr};
295 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
296 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
299 #[stable(feature = "rust1", since = "1.0.0")]
300 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
301 pub const fn ip(&self) -> &Ipv4Addr {
305 /// Changes the IP address associated with this socket address.
310 /// use std::net::{SocketAddrV4, Ipv4Addr};
312 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
313 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
314 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
316 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
317 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
321 /// Returns the port number associated with this socket address.
326 /// use std::net::{SocketAddrV4, Ipv4Addr};
328 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
329 /// assert_eq!(socket.port(), 8080);
332 #[stable(feature = "rust1", since = "1.0.0")]
333 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
334 pub const fn port(&self) -> u16 {
338 /// Changes the port number associated with this socket address.
343 /// use std::net::{SocketAddrV4, Ipv4Addr};
345 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
346 /// socket.set_port(4242);
347 /// assert_eq!(socket.port(), 4242);
349 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
350 pub fn set_port(&mut self, new_port: u16) {
351 self.port = new_port;
356 /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
357 /// and the `flowinfo` and `scope_id` fields.
359 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
360 /// parameters, see [IETF RFC 2553, Section 3.3].
362 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
363 /// [`IPv6` address]: Ipv6Addr
368 /// use std::net::{SocketAddrV6, Ipv6Addr};
370 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
372 #[stable(feature = "rust1", since = "1.0.0")]
374 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
375 pub const fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
376 SocketAddrV6 { ip, port, flowinfo, scope_id }
379 /// Returns the IP address associated with this socket address.
384 /// use std::net::{SocketAddrV6, Ipv6Addr};
386 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
387 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
390 #[stable(feature = "rust1", since = "1.0.0")]
391 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
392 pub const fn ip(&self) -> &Ipv6Addr {
396 /// Changes the IP address associated with this socket address.
401 /// use std::net::{SocketAddrV6, Ipv6Addr};
403 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
404 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
405 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
407 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
408 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
412 /// Returns the port number associated with this socket address.
417 /// use std::net::{SocketAddrV6, Ipv6Addr};
419 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
420 /// assert_eq!(socket.port(), 8080);
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
425 pub const fn port(&self) -> u16 {
429 /// Changes the port number associated with this socket address.
434 /// use std::net::{SocketAddrV6, Ipv6Addr};
436 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
437 /// socket.set_port(4242);
438 /// assert_eq!(socket.port(), 4242);
440 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
441 pub fn set_port(&mut self, new_port: u16) {
442 self.port = new_port;
445 /// Returns the flow information associated with this address.
447 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
448 /// as specified in [IETF RFC 2553, Section 3.3].
449 /// It combines information about the flow label and the traffic class as specified
450 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
452 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
453 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
454 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
455 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
460 /// use std::net::{SocketAddrV6, Ipv6Addr};
462 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
463 /// assert_eq!(socket.flowinfo(), 10);
466 #[stable(feature = "rust1", since = "1.0.0")]
467 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
468 pub const fn flowinfo(&self) -> u32 {
472 /// Changes the flow information associated with this socket address.
474 /// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
479 /// use std::net::{SocketAddrV6, Ipv6Addr};
481 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
482 /// socket.set_flowinfo(56);
483 /// assert_eq!(socket.flowinfo(), 56);
485 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
486 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
487 self.flowinfo = new_flowinfo;
490 /// Returns the scope ID associated with this address.
492 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
493 /// as specified in [IETF RFC 2553, Section 3.3].
495 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
500 /// use std::net::{SocketAddrV6, Ipv6Addr};
502 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
503 /// assert_eq!(socket.scope_id(), 78);
506 #[stable(feature = "rust1", since = "1.0.0")]
507 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
508 pub const fn scope_id(&self) -> u32 {
512 /// Changes the scope ID associated with this socket address.
514 /// See [`SocketAddrV6::scope_id`]'s documentation for more details.
519 /// use std::net::{SocketAddrV6, Ipv6Addr};
521 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
522 /// socket.set_scope_id(42);
523 /// assert_eq!(socket.scope_id(), 42);
525 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
526 pub fn set_scope_id(&mut self, new_scope_id: u32) {
527 self.scope_id = new_scope_id;
531 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
532 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
533 SocketAddrV4 { ip: Ipv4Addr::from_inner(addr.sin_addr), port: u16::from_be(addr.sin_port) }
537 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
538 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
540 ip: Ipv6Addr::from_inner(addr.sin6_addr),
541 port: u16::from_be(addr.sin6_port),
542 flowinfo: addr.sin6_flowinfo,
543 scope_id: addr.sin6_scope_id,
548 impl IntoInner<c::sockaddr_in> for SocketAddrV4 {
549 fn into_inner(self) -> c::sockaddr_in {
551 sin_family: c::AF_INET as c::sa_family_t,
552 sin_port: self.port.to_be(),
553 sin_addr: self.ip.into_inner(),
554 ..unsafe { mem::zeroed() }
559 impl IntoInner<c::sockaddr_in6> for SocketAddrV6 {
560 fn into_inner(self) -> c::sockaddr_in6 {
562 sin6_family: c::AF_INET6 as c::sa_family_t,
563 sin6_port: self.port.to_be(),
564 sin6_addr: self.ip.into_inner(),
565 sin6_flowinfo: self.flowinfo,
566 sin6_scope_id: self.scope_id,
567 ..unsafe { mem::zeroed() }
572 #[stable(feature = "ip_from_ip", since = "1.16.0")]
573 impl From<SocketAddrV4> for SocketAddr {
574 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
575 fn from(sock4: SocketAddrV4) -> SocketAddr {
576 SocketAddr::V4(sock4)
580 #[stable(feature = "ip_from_ip", since = "1.16.0")]
581 impl From<SocketAddrV6> for SocketAddr {
582 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
583 fn from(sock6: SocketAddrV6) -> SocketAddr {
584 SocketAddr::V6(sock6)
588 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
589 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
590 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
592 /// This conversion creates a [`SocketAddr::V4`] for an [`IpAddr::V4`]
593 /// and creates a [`SocketAddr::V6`] for an [`IpAddr::V6`].
595 /// `u16` is treated as port of the newly created [`SocketAddr`].
596 fn from(pieces: (I, u16)) -> SocketAddr {
597 SocketAddr::new(pieces.0.into(), pieces.1)
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl fmt::Display for SocketAddr {
603 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605 SocketAddr::V4(ref a) => a.fmt(f),
606 SocketAddr::V6(ref a) => a.fmt(f),
611 #[stable(feature = "rust1", since = "1.0.0")]
612 impl fmt::Debug for SocketAddr {
613 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
614 fmt::Display::fmt(self, fmt)
618 #[stable(feature = "rust1", since = "1.0.0")]
619 impl fmt::Display for SocketAddrV4 {
620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621 // If there are no alignment requirements, write the socket address directly to `f`.
622 // Otherwise, write it to a local buffer and then use `f.pad`.
623 if f.precision().is_none() && f.width().is_none() {
624 write!(f, "{}:{}", self.ip(), self.port())
626 const LONGEST_IPV4_SOCKET_ADDR: &str = "255.255.255.255:65536";
628 let mut buf = DisplayBuffer::<{ LONGEST_IPV4_SOCKET_ADDR.len() }>::new();
629 // Buffer is long enough for the longest possible IPv4 socket address, so this should never fail.
630 write!(buf, "{}:{}", self.ip(), self.port()).unwrap();
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl fmt::Debug for SocketAddrV4 {
639 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
640 fmt::Display::fmt(self, fmt)
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl fmt::Display for SocketAddrV6 {
646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647 // If there are no alignment requirements, write the socket address directly to `f`.
648 // Otherwise, write it to a local buffer and then use `f.pad`.
649 if f.precision().is_none() && f.width().is_none() {
650 match self.scope_id() {
651 0 => write!(f, "[{}]:{}", self.ip(), self.port()),
652 scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
655 const LONGEST_IPV6_SOCKET_ADDR: &str =
656 "[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%4294967296]:65536";
658 let mut buf = DisplayBuffer::<{ LONGEST_IPV6_SOCKET_ADDR.len() }>::new();
659 match self.scope_id() {
660 0 => write!(buf, "[{}]:{}", self.ip(), self.port()),
661 scope_id => write!(buf, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
663 // Buffer is long enough for the longest possible IPv6 socket address, so this should never fail.
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl fmt::Debug for SocketAddrV6 {
673 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
674 fmt::Display::fmt(self, fmt)
678 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
679 impl PartialOrd for SocketAddrV4 {
680 fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
681 Some(self.cmp(other))
685 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
686 impl PartialOrd for SocketAddrV6 {
687 fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
688 Some(self.cmp(other))
692 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
693 impl Ord for SocketAddrV4 {
694 fn cmp(&self, other: &SocketAddrV4) -> Ordering {
695 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
699 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
700 impl Ord for SocketAddrV6 {
701 fn cmp(&self, other: &SocketAddrV6) -> Ordering {
702 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
706 #[stable(feature = "rust1", since = "1.0.0")]
707 impl hash::Hash for SocketAddrV4 {
708 fn hash<H: hash::Hasher>(&self, s: &mut H) {
709 (self.port, self.ip).hash(s)
712 #[stable(feature = "rust1", since = "1.0.0")]
713 impl hash::Hash for SocketAddrV6 {
714 fn hash<H: hash::Hasher>(&self, s: &mut H) {
715 (self.port, &self.ip, self.flowinfo, self.scope_id).hash(s)
719 /// A trait for objects which can be converted or resolved to one or more
720 /// [`SocketAddr`] values.
722 /// This trait is used for generic address resolution when constructing network
723 /// objects. By default it is implemented for the following types:
725 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
727 /// * [`SocketAddrV4`], [`SocketAddrV6`], <code>([IpAddr], [u16])</code>,
728 /// <code>([Ipv4Addr], [u16])</code>, <code>([Ipv6Addr], [u16])</code>:
729 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
731 /// * <code>(&[str], [u16])</code>: <code>&[str]</code> should be either a string representation
732 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
733 /// name. [`u16`] is the port number.
735 /// * <code>&[str]</code>: the string should be either a string representation of a
736 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
737 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
739 /// This trait allows constructing network objects like [`TcpStream`] or
740 /// [`UdpSocket`] easily with values of various types for the bind/connection
741 /// address. It is needed because sometimes one type is more appropriate than
742 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
743 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
744 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
745 /// some other type (e.g., a string) just for it to be converted back to
746 /// [`SocketAddr`] in constructor methods is pointless.
748 /// Addresses returned by the operating system that are not IP addresses are
749 /// silently ignored.
751 /// [`FromStr`]: crate::str::FromStr "std::str::FromStr"
752 /// [`TcpStream`]: crate::net::TcpStream "net::TcpStream"
753 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
754 /// [`UdpSocket`]: crate::net::UdpSocket "net::UdpSocket"
758 /// Creating a [`SocketAddr`] iterator that yields one item:
761 /// use std::net::{ToSocketAddrs, SocketAddr};
763 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
764 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
766 /// assert_eq!(Some(addr), addrs_iter.next());
767 /// assert!(addrs_iter.next().is_none());
770 /// Creating a [`SocketAddr`] iterator from a hostname:
773 /// use std::net::{SocketAddr, ToSocketAddrs};
775 /// // assuming 'localhost' resolves to 127.0.0.1
776 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
777 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
778 /// assert!(addrs_iter.next().is_none());
780 /// // assuming 'foo' does not resolve
781 /// assert!("foo:443".to_socket_addrs().is_err());
784 /// Creating a [`SocketAddr`] iterator that yields multiple items:
787 /// use std::net::{SocketAddr, ToSocketAddrs};
789 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
790 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
791 /// let addrs = vec![addr1, addr2];
793 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
795 /// assert_eq!(Some(addr1), addrs_iter.next());
796 /// assert_eq!(Some(addr2), addrs_iter.next());
797 /// assert!(addrs_iter.next().is_none());
800 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
801 /// socket address `&str` (missing the port):
805 /// use std::net::ToSocketAddrs;
807 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
808 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
811 /// [`TcpStream::connect`] is an example of an function that utilizes
812 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
816 /// use std::net::{TcpStream, Ipv4Addr};
818 /// let stream = TcpStream::connect(("127.0.0.1", 443));
820 /// let stream = TcpStream::connect("127.0.0.1:443");
822 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
825 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
826 #[stable(feature = "rust1", since = "1.0.0")]
827 pub trait ToSocketAddrs {
828 /// Returned iterator over socket addresses which this type may correspond
830 #[stable(feature = "rust1", since = "1.0.0")]
831 type Iter: Iterator<Item = SocketAddr>;
833 /// Converts this object to an iterator of resolved [`SocketAddr`]s.
835 /// The returned iterator might not actually yield any values depending on the
836 /// outcome of any resolution performed.
838 /// Note that this function may block the current thread while resolution is
840 #[stable(feature = "rust1", since = "1.0.0")]
841 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
844 #[stable(feature = "rust1", since = "1.0.0")]
845 impl ToSocketAddrs for SocketAddr {
846 type Iter = option::IntoIter<SocketAddr>;
847 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
848 Ok(Some(*self).into_iter())
852 #[stable(feature = "rust1", since = "1.0.0")]
853 impl ToSocketAddrs for SocketAddrV4 {
854 type Iter = option::IntoIter<SocketAddr>;
855 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
856 SocketAddr::V4(*self).to_socket_addrs()
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl ToSocketAddrs for SocketAddrV6 {
862 type Iter = option::IntoIter<SocketAddr>;
863 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
864 SocketAddr::V6(*self).to_socket_addrs()
868 #[stable(feature = "rust1", since = "1.0.0")]
869 impl ToSocketAddrs for (IpAddr, u16) {
870 type Iter = option::IntoIter<SocketAddr>;
871 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
872 let (ip, port) = *self;
874 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
875 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl ToSocketAddrs for (Ipv4Addr, u16) {
882 type Iter = option::IntoIter<SocketAddr>;
883 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
884 let (ip, port) = *self;
885 SocketAddrV4::new(ip, port).to_socket_addrs()
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl ToSocketAddrs for (Ipv6Addr, u16) {
891 type Iter = option::IntoIter<SocketAddr>;
892 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
893 let (ip, port) = *self;
894 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
898 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl ToSocketAddrs for (&str, u16) {
911 type Iter = vec::IntoIter<SocketAddr>;
912 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
913 let (host, port) = *self;
915 // try to parse the host as a regular IP address first
916 if let Ok(addr) = host.parse::<Ipv4Addr>() {
917 let addr = SocketAddrV4::new(addr, port);
918 return Ok(vec![SocketAddr::V4(addr)].into_iter());
920 if let Ok(addr) = host.parse::<Ipv6Addr>() {
921 let addr = SocketAddrV6::new(addr, port, 0, 0);
922 return Ok(vec![SocketAddr::V6(addr)].into_iter());
925 resolve_socket_addr((host, port).try_into()?)
929 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
930 impl ToSocketAddrs for (String, u16) {
931 type Iter = vec::IntoIter<SocketAddr>;
932 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
933 (&*self.0, self.1).to_socket_addrs()
937 // accepts strings like 'localhost:12345'
938 #[stable(feature = "rust1", since = "1.0.0")]
939 impl ToSocketAddrs for str {
940 type Iter = vec::IntoIter<SocketAddr>;
941 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
942 // try to parse as a regular SocketAddr first
943 if let Ok(addr) = self.parse() {
944 return Ok(vec![addr].into_iter());
947 resolve_socket_addr(self.try_into()?)
951 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
952 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
953 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
955 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
956 Ok(self.iter().cloned())
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
963 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
964 (**self).to_socket_addrs()
968 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
969 impl ToSocketAddrs for String {
970 type Iter = vec::IntoIter<SocketAddr>;
971 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
972 (&**self).to_socket_addrs()