1 use crate::cmp::Ordering;
2 use crate::convert::TryInto;
5 use crate::io::{self, Write};
8 use crate::net::{htons, ntohs, IpAddr, Ipv4Addr, Ipv6Addr};
11 use crate::sys::net::netc as c;
12 use crate::sys_common::net::LookupHost;
13 use crate::sys_common::{AsInner, FromInner, IntoInner};
16 /// An internet socket address, either IPv4 or IPv6.
18 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
19 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
20 /// [`SocketAddrV6`]'s respective documentation for more details.
22 /// The size of a `SocketAddr` instance may vary depending on the target operating
25 /// [IP address]: IpAddr
30 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
32 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
34 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
35 /// assert_eq!(socket.port(), 8080);
36 /// assert_eq!(socket.is_ipv4(), true);
38 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
39 #[stable(feature = "rust1", since = "1.0.0")]
41 /// An IPv4 socket address.
42 #[stable(feature = "rust1", since = "1.0.0")]
43 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
44 /// An IPv6 socket address.
45 #[stable(feature = "rust1", since = "1.0.0")]
46 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
49 /// An IPv4 socket address.
51 /// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
52 /// stated in [IETF RFC 793].
54 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
56 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
59 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
60 /// [`IPv4` address]: Ipv4Addr
65 /// use std::net::{Ipv4Addr, SocketAddrV4};
67 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
69 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
70 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
71 /// assert_eq!(socket.port(), 8080);
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub struct SocketAddrV4 {
76 inner: c::sockaddr_in,
79 /// An IPv6 socket address.
81 /// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
82 /// as fields containing the traffic class, the flow label, and a scope identifier
83 /// (see [IETF RFC 2553, Section 3.3] for more details).
85 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
87 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
90 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
91 /// [`IPv6` address]: Ipv6Addr
96 /// use std::net::{Ipv6Addr, SocketAddrV6};
98 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
100 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
101 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
102 /// assert_eq!(socket.port(), 8080);
105 #[stable(feature = "rust1", since = "1.0.0")]
106 pub struct SocketAddrV6 {
107 inner: c::sockaddr_in6,
111 /// Creates a new socket address from an [IP address] and a port number.
113 /// [IP address]: IpAddr
118 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
120 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
121 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
122 /// assert_eq!(socket.port(), 8080);
124 #[stable(feature = "ip_addr", since = "1.7.0")]
125 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
127 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
128 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
132 /// Returns the IP address associated with this socket address.
137 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
139 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
140 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
142 #[stable(feature = "ip_addr", since = "1.7.0")]
143 pub fn ip(&self) -> IpAddr {
145 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
146 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
150 /// Changes the IP address associated with this socket address.
155 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
157 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
158 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
159 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
161 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
162 pub fn set_ip(&mut self, new_ip: IpAddr) {
163 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
164 match (self, new_ip) {
165 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
166 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
167 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
171 /// Returns the port number associated with this socket address.
176 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
178 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
179 /// assert_eq!(socket.port(), 8080);
181 #[stable(feature = "rust1", since = "1.0.0")]
182 pub fn port(&self) -> u16 {
184 SocketAddr::V4(ref a) => a.port(),
185 SocketAddr::V6(ref a) => a.port(),
189 /// Changes the port number associated with this socket address.
194 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
196 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
197 /// socket.set_port(1025);
198 /// assert_eq!(socket.port(), 1025);
200 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
201 pub fn set_port(&mut self, new_port: u16) {
203 SocketAddr::V4(ref mut a) => a.set_port(new_port),
204 SocketAddr::V6(ref mut a) => a.set_port(new_port),
208 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
209 /// [`IPv4` address], and [`false`] otherwise.
211 /// [IP address]: IpAddr
212 /// [`IPv4` address]: IpAddr::V4
213 /// [`false`]: ../../std/primitive.bool.html
214 /// [`true`]: ../../std/primitive.bool.html
219 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
221 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
222 /// assert_eq!(socket.is_ipv4(), true);
223 /// assert_eq!(socket.is_ipv6(), false);
225 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
226 pub fn is_ipv4(&self) -> bool {
227 matches!(*self, SocketAddr::V4(_))
230 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
231 /// [`IPv6` address], and [`false`] otherwise.
233 /// [IP address]: IpAddr
234 /// [`IPv6` address]: IpAddr::V6
235 /// [`false`]: ../../std/primitive.bool.html
236 /// [`true`]: ../../std/primitive.bool.html
241 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
243 /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
244 /// assert_eq!(socket.is_ipv4(), false);
245 /// assert_eq!(socket.is_ipv6(), true);
247 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
248 pub fn is_ipv6(&self) -> bool {
249 matches!(*self, SocketAddr::V6(_))
254 /// Creates a new socket address from an [`IPv4` address] and a port number.
256 /// [`IPv4` address]: Ipv4Addr
261 /// use std::net::{SocketAddrV4, Ipv4Addr};
263 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
268 inner: c::sockaddr_in {
269 sin_family: c::AF_INET as c::sa_family_t,
270 sin_port: htons(port),
271 sin_addr: *ip.as_inner(),
272 ..unsafe { mem::zeroed() }
277 /// Returns the IP address associated with this socket address.
282 /// use std::net::{SocketAddrV4, Ipv4Addr};
284 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
285 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub fn ip(&self) -> &Ipv4Addr {
289 unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
292 /// Changes the IP address associated with this socket address.
297 /// use std::net::{SocketAddrV4, Ipv4Addr};
299 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
300 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
301 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
303 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
304 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
305 self.inner.sin_addr = *new_ip.as_inner()
308 /// Returns the port number associated with this socket address.
313 /// use std::net::{SocketAddrV4, Ipv4Addr};
315 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
316 /// assert_eq!(socket.port(), 8080);
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn port(&self) -> u16 {
320 ntohs(self.inner.sin_port)
323 /// Changes the port number associated with this socket address.
328 /// use std::net::{SocketAddrV4, Ipv4Addr};
330 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
331 /// socket.set_port(4242);
332 /// assert_eq!(socket.port(), 4242);
334 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
335 pub fn set_port(&mut self, new_port: u16) {
336 self.inner.sin_port = htons(new_port);
341 /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
342 /// and the `flowinfo` and `scope_id` fields.
344 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
345 /// parameters, see [IETF RFC 2553, Section 3.3].
347 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
348 /// [`IPv6` address]: Ipv6Addr
353 /// use std::net::{SocketAddrV6, Ipv6Addr};
355 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
360 inner: c::sockaddr_in6 {
361 sin6_family: c::AF_INET6 as c::sa_family_t,
362 sin6_port: htons(port),
363 sin6_addr: *ip.as_inner(),
364 sin6_flowinfo: flowinfo,
365 sin6_scope_id: scope_id,
366 ..unsafe { mem::zeroed() }
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 write!(f, "[{}]:{}", self.ip(), self.port())
627 const IPV6_SOCKET_BUF_LEN: usize = (4 * 8) // The address
628 + 7 // The colon separators
632 let mut buf = [0; IPV6_SOCKET_BUF_LEN];
633 let mut buf_slice = &mut buf[..];
635 // Unwrap is fine because writing to a sufficiently-sized
636 // buffer is infallible
637 write!(buf_slice, "[{}]:{}", self.ip(), self.port()).unwrap();
638 let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
640 // This unsafe is OK because we know what is being written to the buffer
641 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl fmt::Debug for SocketAddrV6 {
649 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
650 fmt::Display::fmt(self, fmt)
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl Clone for SocketAddrV4 {
656 fn clone(&self) -> SocketAddrV4 {
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl Clone for SocketAddrV6 {
662 fn clone(&self) -> SocketAddrV6 {
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl PartialEq for SocketAddrV4 {
669 fn eq(&self, other: &SocketAddrV4) -> bool {
670 self.inner.sin_port == other.inner.sin_port
671 && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl PartialEq for SocketAddrV6 {
676 fn eq(&self, other: &SocketAddrV6) -> bool {
677 self.inner.sin6_port == other.inner.sin6_port
678 && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
679 && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
680 && self.inner.sin6_scope_id == other.inner.sin6_scope_id
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl Eq for SocketAddrV4 {}
685 #[stable(feature = "rust1", since = "1.0.0")]
686 impl Eq for SocketAddrV6 {}
688 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
689 impl PartialOrd for SocketAddrV4 {
690 fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
691 Some(self.cmp(other))
695 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
696 impl PartialOrd for SocketAddrV6 {
697 fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
698 Some(self.cmp(other))
702 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
703 impl Ord for SocketAddrV4 {
704 fn cmp(&self, other: &SocketAddrV4) -> Ordering {
705 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
709 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
710 impl Ord for SocketAddrV6 {
711 fn cmp(&self, other: &SocketAddrV6) -> Ordering {
712 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl hash::Hash for SocketAddrV4 {
718 fn hash<H: hash::Hasher>(&self, s: &mut H) {
719 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl hash::Hash for SocketAddrV6 {
724 fn hash<H: hash::Hasher>(&self, s: &mut H) {
726 self.inner.sin6_port,
727 &self.inner.sin6_addr.s6_addr,
728 self.inner.sin6_flowinfo,
729 self.inner.sin6_scope_id,
735 /// A trait for objects which can be converted or resolved to one or more
736 /// [`SocketAddr`] values.
738 /// This trait is used for generic address resolution when constructing network
739 /// objects. By default it is implemented for the following types:
741 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
743 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
744 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
745 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
747 /// * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
748 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
751 /// * [`&str`]: the string should be either a string representation of a
752 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
753 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
755 /// This trait allows constructing network objects like [`TcpStream`] or
756 /// [`UdpSocket`] easily with values of various types for the bind/connection
757 /// address. It is needed because sometimes one type is more appropriate than
758 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
759 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
760 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
761 /// some other type (e.g., a string) just for it to be converted back to
762 /// [`SocketAddr`] in constructor methods is pointless.
764 /// Addresses returned by the operating system that are not IP addresses are
765 /// silently ignored.
767 /// [`FromStr`]: crate::str::FromStr
769 /// [`TcpStream`]: crate::net::TcpStream
770 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
771 /// [`UdpSocket`]: crate::net::UdpSocket
775 /// Creating a [`SocketAddr`] iterator that yields one item:
778 /// use std::net::{ToSocketAddrs, SocketAddr};
780 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
781 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
783 /// assert_eq!(Some(addr), addrs_iter.next());
784 /// assert!(addrs_iter.next().is_none());
787 /// Creating a [`SocketAddr`] iterator from a hostname:
790 /// use std::net::{SocketAddr, ToSocketAddrs};
792 /// // assuming 'localhost' resolves to 127.0.0.1
793 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
794 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
795 /// assert!(addrs_iter.next().is_none());
797 /// // assuming 'foo' does not resolve
798 /// assert!("foo:443".to_socket_addrs().is_err());
801 /// Creating a [`SocketAddr`] iterator that yields multiple items:
804 /// use std::net::{SocketAddr, ToSocketAddrs};
806 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
807 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
808 /// let addrs = vec![addr1, addr2];
810 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
812 /// assert_eq!(Some(addr1), addrs_iter.next());
813 /// assert_eq!(Some(addr2), addrs_iter.next());
814 /// assert!(addrs_iter.next().is_none());
817 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
818 /// socket address `&str` (missing the port):
822 /// use std::net::ToSocketAddrs;
824 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
825 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
828 /// [`TcpStream::connect`] is an example of an function that utilizes
829 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
833 /// use std::net::{TcpStream, Ipv4Addr};
835 /// let stream = TcpStream::connect(("127.0.0.1", 443));
837 /// let stream = TcpStream::connect("127.0.0.1:443");
839 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
842 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
843 #[stable(feature = "rust1", since = "1.0.0")]
844 pub trait ToSocketAddrs {
845 /// Returned iterator over socket addresses which this type may correspond
847 #[stable(feature = "rust1", since = "1.0.0")]
848 type Iter: Iterator<Item = SocketAddr>;
850 /// Converts this object to an iterator of resolved `SocketAddr`s.
852 /// The returned iterator may not actually yield any values depending on the
853 /// outcome of any resolution performed.
855 /// Note that this function may block the current thread while resolution is
857 #[stable(feature = "rust1", since = "1.0.0")]
858 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl ToSocketAddrs for SocketAddr {
863 type Iter = option::IntoIter<SocketAddr>;
864 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
865 Ok(Some(*self).into_iter())
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl ToSocketAddrs for SocketAddrV4 {
871 type Iter = option::IntoIter<SocketAddr>;
872 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
873 SocketAddr::V4(*self).to_socket_addrs()
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl ToSocketAddrs for SocketAddrV6 {
879 type Iter = option::IntoIter<SocketAddr>;
880 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
881 SocketAddr::V6(*self).to_socket_addrs()
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl ToSocketAddrs for (IpAddr, u16) {
887 type Iter = option::IntoIter<SocketAddr>;
888 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
889 let (ip, port) = *self;
891 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
892 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
897 #[stable(feature = "rust1", since = "1.0.0")]
898 impl ToSocketAddrs for (Ipv4Addr, u16) {
899 type Iter = option::IntoIter<SocketAddr>;
900 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
901 let (ip, port) = *self;
902 SocketAddrV4::new(ip, port).to_socket_addrs()
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl ToSocketAddrs for (Ipv6Addr, u16) {
908 type Iter = option::IntoIter<SocketAddr>;
909 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
910 let (ip, port) = *self;
911 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
915 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl ToSocketAddrs for (&str, u16) {
928 type Iter = vec::IntoIter<SocketAddr>;
929 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
930 let (host, port) = *self;
932 // try to parse the host as a regular IP address first
933 if let Ok(addr) = host.parse::<Ipv4Addr>() {
934 let addr = SocketAddrV4::new(addr, port);
935 return Ok(vec![SocketAddr::V4(addr)].into_iter());
937 if let Ok(addr) = host.parse::<Ipv6Addr>() {
938 let addr = SocketAddrV6::new(addr, port, 0, 0);
939 return Ok(vec![SocketAddr::V6(addr)].into_iter());
942 resolve_socket_addr((host, port).try_into()?)
946 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
947 impl ToSocketAddrs for (String, u16) {
948 type Iter = vec::IntoIter<SocketAddr>;
949 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
950 (&*self.0, self.1).to_socket_addrs()
954 // accepts strings like 'localhost:12345'
955 #[stable(feature = "rust1", since = "1.0.0")]
956 impl ToSocketAddrs for str {
957 type Iter = vec::IntoIter<SocketAddr>;
958 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
959 // try to parse as a regular SocketAddr first
960 if let Ok(addr) = self.parse() {
961 return Ok(vec![addr].into_iter());
964 resolve_socket_addr(self.try_into()?)
968 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
969 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
970 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
972 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
973 Ok(self.iter().cloned())
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
980 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
981 (**self).to_socket_addrs()
985 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
986 impl ToSocketAddrs for String {
987 type Iter = vec::IntoIter<SocketAddr>;
988 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
989 (&**self).to_socket_addrs()
993 #[cfg(all(test, not(target_os = "emscripten")))]
995 use crate::net::test::{sa4, sa6, tsa};
999 fn to_socket_addr_ipaddr_u16() {
1000 let a = Ipv4Addr::new(77, 88, 21, 11);
1002 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
1003 assert_eq!(Ok(vec![e]), tsa((a, p)));
1007 fn to_socket_addr_str_u16() {
1008 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
1009 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
1011 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
1012 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
1014 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
1015 #[cfg(not(target_env = "sgx"))]
1016 assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
1017 #[cfg(target_env = "sgx")]
1022 fn to_socket_addr_str() {
1023 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
1024 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
1026 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
1027 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
1029 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
1030 #[cfg(not(target_env = "sgx"))]
1031 assert!(tsa("localhost:23924").unwrap().contains(&a));
1032 #[cfg(target_env = "sgx")]
1037 fn to_socket_addr_string() {
1038 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
1039 assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
1040 assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
1041 assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
1043 let s = format!("{}:{}", "77.88.21.11", "24352");
1044 assert_eq!(Ok(vec![a]), tsa(s));
1045 // s has been moved into the tsa call
1049 fn bind_udp_socket_bad() {
1050 // rust-lang/rust#53957: This is a regression test for a parsing problem
1051 // discovered as part of issue rust-lang/rust#23076, where we were
1052 // incorrectly parsing invalid input and then that would result in a
1053 // successful `UdpSocket` binding when we would expect failure.
1055 // At one time, this test was written as a call to `tsa` with
1056 // INPUT_23076. However, that structure yields an unreliable test,
1057 // because it ends up passing junk input to the DNS server, and some DNS
1058 // servers will respond with `Ok` to such input, with the ip address of
1059 // the DNS server itself.
1061 // This form of the test is more robust: even when the DNS server
1062 // returns its own address, it is still an error to bind a UDP socket to
1063 // a non-local address, and so we still get an error here in that case.
1065 const INPUT_23076: &'static str = "1200::AB00:1234::2552:7777:1313:34300";
1067 assert!(crate::net::UdpSocket::bind(INPUT_23076).is_err())
1072 fn ip4(low: u8) -> Ipv4Addr {
1073 Ipv4Addr::new(77, 88, 21, low)
1075 fn ip6(low: u16) -> Ipv6Addr {
1076 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low)
1079 let mut v4 = SocketAddrV4::new(ip4(11), 80);
1080 assert_eq!(v4.ip(), &ip4(11));
1082 assert_eq!(v4.ip(), &ip4(12));
1084 let mut addr = SocketAddr::V4(v4);
1085 assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
1086 addr.set_ip(IpAddr::V4(ip4(13)));
1087 assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
1088 addr.set_ip(IpAddr::V6(ip6(14)));
1089 assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
1091 let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1092 assert_eq!(v6.ip(), &ip6(1));
1094 assert_eq!(v6.ip(), &ip6(2));
1096 let mut addr = SocketAddr::V6(v6);
1097 assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
1098 addr.set_ip(IpAddr::V6(ip6(3)));
1099 assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
1100 addr.set_ip(IpAddr::V4(ip4(4)));
1101 assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
1106 let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1107 assert_eq!(v4.port(), 80);
1109 assert_eq!(v4.port(), 443);
1111 let mut addr = SocketAddr::V4(v4);
1112 assert_eq!(addr.port(), 443);
1113 addr.set_port(8080);
1114 assert_eq!(addr.port(), 8080);
1116 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1117 assert_eq!(v6.port(), 80);
1119 assert_eq!(v6.port(), 443);
1121 let mut addr = SocketAddr::V6(v6);
1122 assert_eq!(addr.port(), 443);
1123 addr.set_port(8080);
1124 assert_eq!(addr.port(), 8080);
1129 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1130 assert_eq!(v6.flowinfo(), 10);
1131 v6.set_flowinfo(20);
1132 assert_eq!(v6.flowinfo(), 20);
1137 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1138 assert_eq!(v6.scope_id(), 10);
1139 v6.set_scope_id(20);
1140 assert_eq!(v6.scope_id(), 20);
1145 let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1146 assert!(v4.is_ipv4());
1147 assert!(!v4.is_ipv6());
1152 let v6 = SocketAddr::V6(SocketAddrV6::new(
1153 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1),
1158 assert!(!v6.is_ipv4());
1159 assert!(v6.is_ipv6());
1163 fn socket_v4_to_str() {
1164 let socket = SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 8080);
1166 assert_eq!(format!("{}", socket), "192.168.0.1:8080");
1167 assert_eq!(format!("{:<20}", socket), "192.168.0.1:8080 ");
1168 assert_eq!(format!("{:>20}", socket), " 192.168.0.1:8080");
1169 assert_eq!(format!("{:^20}", socket), " 192.168.0.1:8080 ");
1170 assert_eq!(format!("{:.10}", socket), "192.168.0.");
1174 fn socket_v6_to_str() {
1175 let socket: SocketAddrV6 = "[2a02:6b8:0:1::1]:53".parse().unwrap();
1177 assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1]:53");
1178 assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1]:53 ");
1179 assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1]:53");
1180 assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1]:53 ");
1181 assert_eq!(format!("{:.15}", socket), "[2a02:6b8:0:1::");
1186 let v4_1 = "224.120.45.1:23456".parse::<SocketAddrV4>().unwrap();
1187 let v4_2 = "224.210.103.5:12345".parse::<SocketAddrV4>().unwrap();
1188 let v4_3 = "224.210.103.5:23456".parse::<SocketAddrV4>().unwrap();
1189 let v6_1 = "[2001:db8:f00::1002]:23456".parse::<SocketAddrV6>().unwrap();
1190 let v6_2 = "[2001:db8:f00::2001]:12345".parse::<SocketAddrV6>().unwrap();
1191 let v6_3 = "[2001:db8:f00::2001]:23456".parse::<SocketAddrV6>().unwrap();
1194 assert_eq!(v4_1, v4_1);
1195 assert_eq!(v6_1, v6_1);
1196 assert_eq!(SocketAddr::V4(v4_1), SocketAddr::V4(v4_1));
1197 assert_eq!(SocketAddr::V6(v6_1), SocketAddr::V6(v6_1));
1198 assert!(v4_1 != v4_2);
1199 assert!(v6_1 != v6_2);
1201 // compare different addresses
1202 assert!(v4_1 < v4_2);
1203 assert!(v6_1 < v6_2);
1204 assert!(v4_2 > v4_1);
1205 assert!(v6_2 > v6_1);
1207 // compare the same address with different ports
1208 assert!(v4_2 < v4_3);
1209 assert!(v6_2 < v6_3);
1210 assert!(v4_3 > v4_2);
1211 assert!(v6_3 > v6_2);
1213 // compare different addresses with the same port
1214 assert!(v4_1 < v4_3);
1215 assert!(v6_1 < v6_3);
1216 assert!(v4_3 > v4_1);
1217 assert!(v6_3 > v6_1);
1219 // compare with an inferred right-hand side
1220 assert_eq!(v4_1, "224.120.45.1:23456".parse().unwrap());
1221 assert_eq!(v6_1, "[2001:db8:f00::1002]:23456".parse().unwrap());
1222 assert_eq!(SocketAddr::V4(v4_1), "224.120.45.1:23456".parse().unwrap());