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
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 inner: c::sockaddr_in,
82 /// An IPv6 socket address.
84 /// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
85 /// as fields containing the traffic class, the flow label, and a scope identifier
86 /// (see [IETF RFC 2553, Section 3.3] for more details).
88 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
90 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
93 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
94 /// [`IPv6` address]: Ipv6Addr
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]: IpAddr
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 /// [IP address]: IpAddr
215 /// [`IPv4` address]: IpAddr::V4
220 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
222 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
223 /// assert_eq!(socket.is_ipv4(), true);
224 /// assert_eq!(socket.is_ipv6(), false);
226 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
227 pub fn is_ipv4(&self) -> bool {
228 matches!(*self, SocketAddr::V4(_))
231 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
232 /// [`IPv6` address], and [`false`] otherwise.
234 /// [IP address]: IpAddr
235 /// [`IPv6` address]: IpAddr::V6
240 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
242 /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
243 /// assert_eq!(socket.is_ipv4(), false);
244 /// assert_eq!(socket.is_ipv6(), true);
246 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
247 pub fn is_ipv6(&self) -> bool {
248 matches!(*self, SocketAddr::V6(_))
253 /// Creates a new socket address from an [`IPv4` address] and a port number.
255 /// [`IPv4` address]: Ipv4Addr
260 /// use std::net::{SocketAddrV4, Ipv4Addr};
262 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
264 #[stable(feature = "rust1", since = "1.0.0")]
265 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
267 inner: c::sockaddr_in {
268 sin_family: c::AF_INET as c::sa_family_t,
269 sin_port: htons(port),
270 sin_addr: ip.into_inner(),
271 ..unsafe { mem::zeroed() }
276 /// Returns the IP address associated with this socket address.
281 /// use std::net::{SocketAddrV4, Ipv4Addr};
283 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
284 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn ip(&self) -> &Ipv4Addr {
288 // SAFETY: `Ipv4Addr` is `#[repr(C)] struct { _: in_addr; }`.
289 // It is safe to cast from `&in_addr` to `&Ipv4Addr`.
290 unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
293 /// Changes the IP address associated with this socket address.
298 /// use std::net::{SocketAddrV4, Ipv4Addr};
300 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
301 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
302 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
304 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
305 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
306 self.inner.sin_addr = new_ip.into_inner()
309 /// Returns the port number associated with this socket address.
314 /// use std::net::{SocketAddrV4, Ipv4Addr};
316 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
317 /// assert_eq!(socket.port(), 8080);
319 #[stable(feature = "rust1", since = "1.0.0")]
320 pub fn port(&self) -> u16 {
321 ntohs(self.inner.sin_port)
324 /// Changes the port number associated with this socket address.
329 /// use std::net::{SocketAddrV4, Ipv4Addr};
331 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
332 /// socket.set_port(4242);
333 /// assert_eq!(socket.port(), 4242);
335 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
336 pub fn set_port(&mut self, new_port: u16) {
337 self.inner.sin_port = htons(new_port);
342 /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
343 /// and the `flowinfo` and `scope_id` fields.
345 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
346 /// parameters, see [IETF RFC 2553, Section 3.3].
348 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
349 /// [`IPv6` address]: Ipv6Addr
354 /// use std::net::{SocketAddrV6, Ipv6Addr};
356 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
358 #[stable(feature = "rust1", since = "1.0.0")]
359 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
361 inner: c::sockaddr_in6 {
362 sin6_family: c::AF_INET6 as c::sa_family_t,
363 sin6_port: htons(port),
364 sin6_addr: *ip.as_inner(),
365 sin6_flowinfo: flowinfo,
366 sin6_scope_id: scope_id,
367 ..unsafe { mem::zeroed() }
372 /// Returns the IP address associated with this socket address.
377 /// use std::net::{SocketAddrV6, Ipv6Addr};
379 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
380 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
382 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn ip(&self) -> &Ipv6Addr {
384 unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }
387 /// Changes the IP address associated with this socket address.
392 /// use std::net::{SocketAddrV6, Ipv6Addr};
394 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
395 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
396 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
398 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
399 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
400 self.inner.sin6_addr = *new_ip.as_inner()
403 /// Returns the port number associated with this socket address.
408 /// use std::net::{SocketAddrV6, Ipv6Addr};
410 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
411 /// assert_eq!(socket.port(), 8080);
413 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn port(&self) -> u16 {
415 ntohs(self.inner.sin6_port)
418 /// Changes the port number associated with this socket address.
423 /// use std::net::{SocketAddrV6, Ipv6Addr};
425 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
426 /// socket.set_port(4242);
427 /// assert_eq!(socket.port(), 4242);
429 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
430 pub fn set_port(&mut self, new_port: u16) {
431 self.inner.sin6_port = htons(new_port);
434 /// Returns the flow information associated with this address.
436 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
437 /// as specified in [IETF RFC 2553, Section 3.3].
438 /// It combines information about the flow label and the traffic class as specified
439 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
441 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
442 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
443 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
444 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
449 /// use std::net::{SocketAddrV6, Ipv6Addr};
451 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
452 /// assert_eq!(socket.flowinfo(), 10);
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn flowinfo(&self) -> u32 {
456 self.inner.sin6_flowinfo
459 /// Changes the flow information associated with this socket address.
461 /// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
466 /// use std::net::{SocketAddrV6, Ipv6Addr};
468 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
469 /// socket.set_flowinfo(56);
470 /// assert_eq!(socket.flowinfo(), 56);
472 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
473 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
474 self.inner.sin6_flowinfo = new_flowinfo;
477 /// Returns the scope ID associated with this address.
479 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
480 /// as specified in [IETF RFC 2553, Section 3.3].
482 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
487 /// use std::net::{SocketAddrV6, Ipv6Addr};
489 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
490 /// assert_eq!(socket.scope_id(), 78);
492 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn scope_id(&self) -> u32 {
494 self.inner.sin6_scope_id
497 /// Changes the scope ID associated with this socket address.
499 /// See [`SocketAddrV6::scope_id`]'s documentation for more details.
504 /// use std::net::{SocketAddrV6, Ipv6Addr};
506 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
507 /// socket.set_scope_id(42);
508 /// assert_eq!(socket.scope_id(), 42);
510 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
511 pub fn set_scope_id(&mut self, new_scope_id: u32) {
512 self.inner.sin6_scope_id = new_scope_id;
516 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
517 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
518 SocketAddrV4 { inner: addr }
522 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
523 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
524 SocketAddrV6 { inner: addr }
528 #[stable(feature = "ip_from_ip", since = "1.16.0")]
529 impl From<SocketAddrV4> for SocketAddr {
530 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
531 fn from(sock4: SocketAddrV4) -> SocketAddr {
532 SocketAddr::V4(sock4)
536 #[stable(feature = "ip_from_ip", since = "1.16.0")]
537 impl From<SocketAddrV6> for SocketAddr {
538 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
539 fn from(sock6: SocketAddrV6) -> SocketAddr {
540 SocketAddr::V6(sock6)
544 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
545 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
546 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
548 /// This conversion creates a [`SocketAddr::V4`] for a [`IpAddr::V4`]
549 /// and creates a [`SocketAddr::V6`] for a [`IpAddr::V6`].
551 /// `u16` is treated as port of the newly created [`SocketAddr`].
552 fn from(pieces: (I, u16)) -> SocketAddr {
553 SocketAddr::new(pieces.0.into(), pieces.1)
557 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
558 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
560 SocketAddr::V4(ref a) => {
561 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
563 SocketAddr::V6(ref a) => {
564 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl fmt::Display for SocketAddr {
572 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
574 SocketAddr::V4(ref a) => a.fmt(f),
575 SocketAddr::V6(ref a) => a.fmt(f),
580 #[stable(feature = "rust1", since = "1.0.0")]
581 impl fmt::Debug for SocketAddr {
582 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
583 fmt::Display::fmt(self, fmt)
587 #[stable(feature = "rust1", since = "1.0.0")]
588 impl fmt::Display for SocketAddrV4 {
589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
590 // Fast path: if there's no alignment stuff, write to the output buffer
592 if f.precision().is_none() && f.width().is_none() {
593 write!(f, "{}:{}", self.ip(), self.port())
595 const IPV4_SOCKET_BUF_LEN: usize = (3 * 4) // the segments
596 + 3 // the separators
598 let mut buf = [0; IPV4_SOCKET_BUF_LEN];
599 let mut buf_slice = &mut buf[..];
601 // Unwrap is fine because writing to a sufficiently-sized
602 // buffer is infallible
603 write!(buf_slice, "{}:{}", self.ip(), self.port()).unwrap();
604 let len = IPV4_SOCKET_BUF_LEN - buf_slice.len();
606 // This unsafe is OK because we know what is being written to the buffer
607 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
613 #[stable(feature = "rust1", since = "1.0.0")]
614 impl fmt::Debug for SocketAddrV4 {
615 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
616 fmt::Display::fmt(self, fmt)
620 #[stable(feature = "rust1", since = "1.0.0")]
621 impl fmt::Display for SocketAddrV6 {
622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623 // Fast path: if there's no alignment stuff, write to the output
625 if f.precision().is_none() && f.width().is_none() {
626 match self.scope_id() {
627 0 => write!(f, "[{}]:{}", self.ip(), self.port()),
628 scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
631 const IPV6_SOCKET_BUF_LEN: usize = (4 * 8) // The address
632 + 7 // The colon separators
634 + 1 + 10 // The scope id
637 let mut buf = [0; IPV6_SOCKET_BUF_LEN];
638 let mut buf_slice = &mut buf[..];
640 match self.scope_id() {
641 0 => write!(buf_slice, "[{}]:{}", self.ip(), self.port()),
642 scope_id => write!(buf_slice, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
644 // Unwrap is fine because writing to a sufficiently-sized
645 // buffer is infallible
647 let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
649 // This unsafe is OK because we know what is being written to the buffer
650 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl fmt::Debug for SocketAddrV6 {
658 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
659 fmt::Display::fmt(self, fmt)
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl Clone for SocketAddrV4 {
665 fn clone(&self) -> SocketAddrV4 {
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl Clone for SocketAddrV6 {
671 fn clone(&self) -> SocketAddrV6 {
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl PartialEq for SocketAddrV4 {
678 fn eq(&self, other: &SocketAddrV4) -> bool {
679 self.inner.sin_port == other.inner.sin_port
680 && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl PartialEq for SocketAddrV6 {
685 fn eq(&self, other: &SocketAddrV6) -> bool {
686 self.inner.sin6_port == other.inner.sin6_port
687 && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
688 && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
689 && self.inner.sin6_scope_id == other.inner.sin6_scope_id
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl Eq for SocketAddrV4 {}
694 #[stable(feature = "rust1", since = "1.0.0")]
695 impl Eq for SocketAddrV6 {}
697 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
698 impl PartialOrd for SocketAddrV4 {
699 fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
700 Some(self.cmp(other))
704 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
705 impl PartialOrd for SocketAddrV6 {
706 fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
707 Some(self.cmp(other))
711 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
712 impl Ord for SocketAddrV4 {
713 fn cmp(&self, other: &SocketAddrV4) -> Ordering {
714 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
718 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
719 impl Ord for SocketAddrV6 {
720 fn cmp(&self, other: &SocketAddrV6) -> Ordering {
721 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
725 #[stable(feature = "rust1", since = "1.0.0")]
726 impl hash::Hash for SocketAddrV4 {
727 fn hash<H: hash::Hasher>(&self, s: &mut H) {
728 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl hash::Hash for SocketAddrV6 {
733 fn hash<H: hash::Hasher>(&self, s: &mut H) {
735 self.inner.sin6_port,
736 &self.inner.sin6_addr.s6_addr,
737 self.inner.sin6_flowinfo,
738 self.inner.sin6_scope_id,
744 /// A trait for objects which can be converted or resolved to one or more
745 /// [`SocketAddr`] values.
747 /// This trait is used for generic address resolution when constructing network
748 /// objects. By default it is implemented for the following types:
750 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
752 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
753 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
754 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
756 /// * `(`[`&str`]`, `[`u16`]`)`: [`&str`] should be either a string representation
757 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
758 /// name. [`u16`] is the port number.
760 /// * [`&str`]: the string should be either a string representation of a
761 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
762 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
764 /// This trait allows constructing network objects like [`TcpStream`] or
765 /// [`UdpSocket`] easily with values of various types for the bind/connection
766 /// address. It is needed because sometimes one type is more appropriate than
767 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
768 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
769 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
770 /// some other type (e.g., a string) just for it to be converted back to
771 /// [`SocketAddr`] in constructor methods is pointless.
773 /// Addresses returned by the operating system that are not IP addresses are
774 /// silently ignored.
776 /// [`FromStr`]: crate::str::FromStr
778 /// [`TcpStream`]: crate::net::TcpStream
779 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
780 /// [`UdpSocket`]: crate::net::UdpSocket
784 /// Creating a [`SocketAddr`] iterator that yields one item:
787 /// use std::net::{ToSocketAddrs, SocketAddr};
789 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
790 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
792 /// assert_eq!(Some(addr), addrs_iter.next());
793 /// assert!(addrs_iter.next().is_none());
796 /// Creating a [`SocketAddr`] iterator from a hostname:
799 /// use std::net::{SocketAddr, ToSocketAddrs};
801 /// // assuming 'localhost' resolves to 127.0.0.1
802 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
803 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
804 /// assert!(addrs_iter.next().is_none());
806 /// // assuming 'foo' does not resolve
807 /// assert!("foo:443".to_socket_addrs().is_err());
810 /// Creating a [`SocketAddr`] iterator that yields multiple items:
813 /// use std::net::{SocketAddr, ToSocketAddrs};
815 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
816 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
817 /// let addrs = vec![addr1, addr2];
819 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
821 /// assert_eq!(Some(addr1), addrs_iter.next());
822 /// assert_eq!(Some(addr2), addrs_iter.next());
823 /// assert!(addrs_iter.next().is_none());
826 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
827 /// socket address `&str` (missing the port):
831 /// use std::net::ToSocketAddrs;
833 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
834 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
837 /// [`TcpStream::connect`] is an example of an function that utilizes
838 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
842 /// use std::net::{TcpStream, Ipv4Addr};
844 /// let stream = TcpStream::connect(("127.0.0.1", 443));
846 /// let stream = TcpStream::connect("127.0.0.1:443");
848 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
851 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
852 #[stable(feature = "rust1", since = "1.0.0")]
853 pub trait ToSocketAddrs {
854 /// Returned iterator over socket addresses which this type may correspond
856 #[stable(feature = "rust1", since = "1.0.0")]
857 type Iter: Iterator<Item = SocketAddr>;
859 /// Converts this object to an iterator of resolved `SocketAddr`s.
861 /// The returned iterator may not actually yield any values depending on the
862 /// outcome of any resolution performed.
864 /// Note that this function may block the current thread while resolution is
866 #[stable(feature = "rust1", since = "1.0.0")]
867 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
870 #[stable(feature = "rust1", since = "1.0.0")]
871 impl ToSocketAddrs for SocketAddr {
872 type Iter = option::IntoIter<SocketAddr>;
873 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
874 Ok(Some(*self).into_iter())
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl ToSocketAddrs for SocketAddrV4 {
880 type Iter = option::IntoIter<SocketAddr>;
881 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
882 SocketAddr::V4(*self).to_socket_addrs()
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl ToSocketAddrs for SocketAddrV6 {
888 type Iter = option::IntoIter<SocketAddr>;
889 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
890 SocketAddr::V6(*self).to_socket_addrs()
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl ToSocketAddrs for (IpAddr, u16) {
896 type Iter = option::IntoIter<SocketAddr>;
897 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
898 let (ip, port) = *self;
900 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
901 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl ToSocketAddrs for (Ipv4Addr, u16) {
908 type Iter = option::IntoIter<SocketAddr>;
909 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
910 let (ip, port) = *self;
911 SocketAddrV4::new(ip, port).to_socket_addrs()
915 #[stable(feature = "rust1", since = "1.0.0")]
916 impl ToSocketAddrs for (Ipv6Addr, u16) {
917 type Iter = option::IntoIter<SocketAddr>;
918 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
919 let (ip, port) = *self;
920 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
924 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl ToSocketAddrs for (&str, u16) {
937 type Iter = vec::IntoIter<SocketAddr>;
938 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
939 let (host, port) = *self;
941 // try to parse the host as a regular IP address first
942 if let Ok(addr) = host.parse::<Ipv4Addr>() {
943 let addr = SocketAddrV4::new(addr, port);
944 return Ok(vec![SocketAddr::V4(addr)].into_iter());
946 if let Ok(addr) = host.parse::<Ipv6Addr>() {
947 let addr = SocketAddrV6::new(addr, port, 0, 0);
948 return Ok(vec![SocketAddr::V6(addr)].into_iter());
951 resolve_socket_addr((host, port).try_into()?)
955 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
956 impl ToSocketAddrs for (String, u16) {
957 type Iter = vec::IntoIter<SocketAddr>;
958 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
959 (&*self.0, self.1).to_socket_addrs()
963 // accepts strings like 'localhost:12345'
964 #[stable(feature = "rust1", since = "1.0.0")]
965 impl ToSocketAddrs for str {
966 type Iter = vec::IntoIter<SocketAddr>;
967 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
968 // try to parse as a regular SocketAddr first
969 if let Ok(addr) = self.parse() {
970 return Ok(vec![addr].into_iter());
973 resolve_socket_addr(self.try_into()?)
977 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
978 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
979 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
981 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
982 Ok(self.iter().cloned())
986 #[stable(feature = "rust1", since = "1.0.0")]
987 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
989 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
990 (**self).to_socket_addrs()
994 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
995 impl ToSocketAddrs for String {
996 type Iter = vec::IntoIter<SocketAddr>;
997 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
998 (&**self).to_socket_addrs()