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,
371 /// Returns the IP address associated with this socket address.
376 /// use std::net::{SocketAddrV6, Ipv6Addr};
378 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
379 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
381 #[stable(feature = "rust1", since = "1.0.0")]
382 pub fn ip(&self) -> &Ipv6Addr {
383 unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }
386 /// Changes the IP address associated with this socket address.
391 /// use std::net::{SocketAddrV6, Ipv6Addr};
393 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
394 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
395 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
397 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
398 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
399 self.inner.sin6_addr = *new_ip.as_inner()
402 /// Returns the port number associated with this socket address.
407 /// use std::net::{SocketAddrV6, Ipv6Addr};
409 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
410 /// assert_eq!(socket.port(), 8080);
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub fn port(&self) -> u16 {
414 ntohs(self.inner.sin6_port)
417 /// Changes the port number associated with this socket address.
422 /// use std::net::{SocketAddrV6, Ipv6Addr};
424 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
425 /// socket.set_port(4242);
426 /// assert_eq!(socket.port(), 4242);
428 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
429 pub fn set_port(&mut self, new_port: u16) {
430 self.inner.sin6_port = htons(new_port);
433 /// Returns the flow information associated with this address.
435 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
436 /// as specified in [IETF RFC 2553, Section 3.3].
437 /// It combines information about the flow label and the traffic class as specified
438 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
440 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
441 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
442 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
443 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
448 /// use std::net::{SocketAddrV6, Ipv6Addr};
450 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
451 /// assert_eq!(socket.flowinfo(), 10);
453 #[stable(feature = "rust1", since = "1.0.0")]
454 pub fn flowinfo(&self) -> u32 {
455 self.inner.sin6_flowinfo
458 /// Changes the flow information associated with this socket address.
460 /// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
465 /// use std::net::{SocketAddrV6, Ipv6Addr};
467 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
468 /// socket.set_flowinfo(56);
469 /// assert_eq!(socket.flowinfo(), 56);
471 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
472 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
473 self.inner.sin6_flowinfo = new_flowinfo;
476 /// Returns the scope ID associated with this address.
478 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
479 /// as specified in [IETF RFC 2553, Section 3.3].
481 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
486 /// use std::net::{SocketAddrV6, Ipv6Addr};
488 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
489 /// assert_eq!(socket.scope_id(), 78);
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub fn scope_id(&self) -> u32 {
493 self.inner.sin6_scope_id
496 /// Changes the scope ID associated with this socket address.
498 /// See [`SocketAddrV6::scope_id`]'s documentation for more details.
503 /// use std::net::{SocketAddrV6, Ipv6Addr};
505 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
506 /// socket.set_scope_id(42);
507 /// assert_eq!(socket.scope_id(), 42);
509 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
510 pub fn set_scope_id(&mut self, new_scope_id: u32) {
511 self.inner.sin6_scope_id = new_scope_id;
515 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
516 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
517 SocketAddrV4 { inner: addr }
521 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
522 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
523 SocketAddrV6 { inner: addr }
527 #[stable(feature = "ip_from_ip", since = "1.16.0")]
528 impl From<SocketAddrV4> for SocketAddr {
529 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
530 fn from(sock4: SocketAddrV4) -> SocketAddr {
531 SocketAddr::V4(sock4)
535 #[stable(feature = "ip_from_ip", since = "1.16.0")]
536 impl From<SocketAddrV6> for SocketAddr {
537 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
538 fn from(sock6: SocketAddrV6) -> SocketAddr {
539 SocketAddr::V6(sock6)
543 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
544 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
545 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
547 /// This conversion creates a [`SocketAddr::V4`] for a [`IpAddr::V4`]
548 /// and creates a [`SocketAddr::V6`] for a [`IpAddr::V6`].
550 /// `u16` is treated as port of the newly created [`SocketAddr`].
551 fn from(pieces: (I, u16)) -> SocketAddr {
552 SocketAddr::new(pieces.0.into(), pieces.1)
556 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
557 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
559 SocketAddr::V4(ref a) => {
560 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
562 SocketAddr::V6(ref a) => {
563 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
569 #[stable(feature = "rust1", since = "1.0.0")]
570 impl fmt::Display for SocketAddr {
571 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573 SocketAddr::V4(ref a) => a.fmt(f),
574 SocketAddr::V6(ref a) => a.fmt(f),
579 #[stable(feature = "rust1", since = "1.0.0")]
580 impl fmt::Debug for SocketAddr {
581 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
582 fmt::Display::fmt(self, fmt)
586 #[stable(feature = "rust1", since = "1.0.0")]
587 impl fmt::Display for SocketAddrV4 {
588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589 // Fast path: if there's no alignment stuff, write to the output buffer
591 if f.precision().is_none() && f.width().is_none() {
592 write!(f, "{}:{}", self.ip(), self.port())
594 const IPV4_SOCKET_BUF_LEN: usize = (3 * 4) // the segments
595 + 3 // the separators
597 let mut buf = [0; IPV4_SOCKET_BUF_LEN];
598 let mut buf_slice = &mut buf[..];
600 // Unwrap is fine because writing to a sufficiently-sized
601 // buffer is infallible
602 write!(buf_slice, "{}:{}", self.ip(), self.port()).unwrap();
603 let len = IPV4_SOCKET_BUF_LEN - buf_slice.len();
605 // This unsafe is OK because we know what is being written to the buffer
606 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl fmt::Debug for SocketAddrV4 {
614 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
615 fmt::Display::fmt(self, fmt)
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl fmt::Display for SocketAddrV6 {
621 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
622 // Fast path: if there's no alignment stuff, write to the output
624 if f.precision().is_none() && f.width().is_none() {
625 match self.scope_id() {
626 0 => write!(f, "[{}]:{}", self.ip(), self.port()),
627 scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
630 const IPV6_SOCKET_BUF_LEN: usize = (4 * 8) // The address
631 + 7 // The colon separators
633 + 1 + 10 // The scope id
636 let mut buf = [0; IPV6_SOCKET_BUF_LEN];
637 let mut buf_slice = &mut buf[..];
639 match self.scope_id() {
640 0 => write!(buf_slice, "[{}]:{}", self.ip(), self.port()),
641 scope_id => write!(buf_slice, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
643 // Unwrap is fine because writing to a sufficiently-sized
644 // buffer is infallible
646 let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
648 // This unsafe is OK because we know what is being written to the buffer
649 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
655 #[stable(feature = "rust1", since = "1.0.0")]
656 impl fmt::Debug for SocketAddrV6 {
657 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
658 fmt::Display::fmt(self, fmt)
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl Clone for SocketAddrV4 {
664 fn clone(&self) -> SocketAddrV4 {
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl Clone for SocketAddrV6 {
670 fn clone(&self) -> SocketAddrV6 {
675 #[stable(feature = "rust1", since = "1.0.0")]
676 impl PartialEq for SocketAddrV4 {
677 fn eq(&self, other: &SocketAddrV4) -> bool {
678 self.inner.sin_port == other.inner.sin_port
679 && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
682 #[stable(feature = "rust1", since = "1.0.0")]
683 impl PartialEq for SocketAddrV6 {
684 fn eq(&self, other: &SocketAddrV6) -> bool {
685 self.inner.sin6_port == other.inner.sin6_port
686 && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
687 && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
688 && self.inner.sin6_scope_id == other.inner.sin6_scope_id
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl Eq for SocketAddrV4 {}
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl Eq for SocketAddrV6 {}
696 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
697 impl PartialOrd for SocketAddrV4 {
698 fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
699 Some(self.cmp(other))
703 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
704 impl PartialOrd for SocketAddrV6 {
705 fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
706 Some(self.cmp(other))
710 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
711 impl Ord for SocketAddrV4 {
712 fn cmp(&self, other: &SocketAddrV4) -> Ordering {
713 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
717 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
718 impl Ord for SocketAddrV6 {
719 fn cmp(&self, other: &SocketAddrV6) -> Ordering {
720 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
724 #[stable(feature = "rust1", since = "1.0.0")]
725 impl hash::Hash for SocketAddrV4 {
726 fn hash<H: hash::Hasher>(&self, s: &mut H) {
727 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl hash::Hash for SocketAddrV6 {
732 fn hash<H: hash::Hasher>(&self, s: &mut H) {
734 self.inner.sin6_port,
735 &self.inner.sin6_addr.s6_addr,
736 self.inner.sin6_flowinfo,
737 self.inner.sin6_scope_id,
743 /// A trait for objects which can be converted or resolved to one or more
744 /// [`SocketAddr`] values.
746 /// This trait is used for generic address resolution when constructing network
747 /// objects. By default it is implemented for the following types:
749 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
751 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
752 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
753 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
755 /// * `(`[`&str`]`, `[`u16`]`)`: [`&str`] should be either a string representation
756 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
757 /// name. [`u16`] is the port number.
759 /// * [`&str`]: the string should be either a string representation of a
760 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
761 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
763 /// This trait allows constructing network objects like [`TcpStream`] or
764 /// [`UdpSocket`] easily with values of various types for the bind/connection
765 /// address. It is needed because sometimes one type is more appropriate than
766 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
767 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
768 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
769 /// some other type (e.g., a string) just for it to be converted back to
770 /// [`SocketAddr`] in constructor methods is pointless.
772 /// Addresses returned by the operating system that are not IP addresses are
773 /// silently ignored.
775 /// [`FromStr`]: crate::str::FromStr
777 /// [`TcpStream`]: crate::net::TcpStream
778 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
779 /// [`UdpSocket`]: crate::net::UdpSocket
783 /// Creating a [`SocketAddr`] iterator that yields one item:
786 /// use std::net::{ToSocketAddrs, SocketAddr};
788 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
789 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
791 /// assert_eq!(Some(addr), addrs_iter.next());
792 /// assert!(addrs_iter.next().is_none());
795 /// Creating a [`SocketAddr`] iterator from a hostname:
798 /// use std::net::{SocketAddr, ToSocketAddrs};
800 /// // assuming 'localhost' resolves to 127.0.0.1
801 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
802 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
803 /// assert!(addrs_iter.next().is_none());
805 /// // assuming 'foo' does not resolve
806 /// assert!("foo:443".to_socket_addrs().is_err());
809 /// Creating a [`SocketAddr`] iterator that yields multiple items:
812 /// use std::net::{SocketAddr, ToSocketAddrs};
814 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
815 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
816 /// let addrs = vec![addr1, addr2];
818 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
820 /// assert_eq!(Some(addr1), addrs_iter.next());
821 /// assert_eq!(Some(addr2), addrs_iter.next());
822 /// assert!(addrs_iter.next().is_none());
825 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
826 /// socket address `&str` (missing the port):
830 /// use std::net::ToSocketAddrs;
832 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
833 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
836 /// [`TcpStream::connect`] is an example of an function that utilizes
837 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
841 /// use std::net::{TcpStream, Ipv4Addr};
843 /// let stream = TcpStream::connect(("127.0.0.1", 443));
845 /// let stream = TcpStream::connect("127.0.0.1:443");
847 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
850 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
851 #[stable(feature = "rust1", since = "1.0.0")]
852 pub trait ToSocketAddrs {
853 /// Returned iterator over socket addresses which this type may correspond
855 #[stable(feature = "rust1", since = "1.0.0")]
856 type Iter: Iterator<Item = SocketAddr>;
858 /// Converts this object to an iterator of resolved `SocketAddr`s.
860 /// The returned iterator may not actually yield any values depending on the
861 /// outcome of any resolution performed.
863 /// Note that this function may block the current thread while resolution is
865 #[stable(feature = "rust1", since = "1.0.0")]
866 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl ToSocketAddrs for SocketAddr {
871 type Iter = option::IntoIter<SocketAddr>;
872 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
873 Ok(Some(*self).into_iter())
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl ToSocketAddrs for SocketAddrV4 {
879 type Iter = option::IntoIter<SocketAddr>;
880 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
881 SocketAddr::V4(*self).to_socket_addrs()
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl ToSocketAddrs for SocketAddrV6 {
887 type Iter = option::IntoIter<SocketAddr>;
888 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
889 SocketAddr::V6(*self).to_socket_addrs()
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl ToSocketAddrs for (IpAddr, u16) {
895 type Iter = option::IntoIter<SocketAddr>;
896 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
897 let (ip, port) = *self;
899 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
900 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl ToSocketAddrs for (Ipv4Addr, u16) {
907 type Iter = option::IntoIter<SocketAddr>;
908 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
909 let (ip, port) = *self;
910 SocketAddrV4::new(ip, port).to_socket_addrs()
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl ToSocketAddrs for (Ipv6Addr, u16) {
916 type Iter = option::IntoIter<SocketAddr>;
917 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
918 let (ip, port) = *self;
919 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
923 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl ToSocketAddrs for (&str, u16) {
936 type Iter = vec::IntoIter<SocketAddr>;
937 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
938 let (host, port) = *self;
940 // try to parse the host as a regular IP address first
941 if let Ok(addr) = host.parse::<Ipv4Addr>() {
942 let addr = SocketAddrV4::new(addr, port);
943 return Ok(vec![SocketAddr::V4(addr)].into_iter());
945 if let Ok(addr) = host.parse::<Ipv6Addr>() {
946 let addr = SocketAddrV6::new(addr, port, 0, 0);
947 return Ok(vec![SocketAddr::V6(addr)].into_iter());
950 resolve_socket_addr((host, port).try_into()?)
954 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
955 impl ToSocketAddrs for (String, u16) {
956 type Iter = vec::IntoIter<SocketAddr>;
957 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
958 (&*self.0, self.1).to_socket_addrs()
962 // accepts strings like 'localhost:12345'
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl ToSocketAddrs for str {
965 type Iter = vec::IntoIter<SocketAddr>;
966 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
967 // try to parse as a regular SocketAddr first
968 if let Ok(addr) = self.parse() {
969 return Ok(vec![addr].into_iter());
972 resolve_socket_addr(self.try_into()?)
976 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
977 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
978 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
980 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
981 Ok(self.iter().cloned())
985 #[stable(feature = "rust1", since = "1.0.0")]
986 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
988 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
989 (**self).to_socket_addrs()
993 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
994 impl ToSocketAddrs for String {
995 type Iter = vec::IntoIter<SocketAddr>;
996 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
997 (&**self).to_socket_addrs()