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.into_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 // SAFETY: `Ipv4Addr` is `#[repr(C)] struct { _: in_addr; }`.
290 // It is safe to cast from `&in_addr` to `&Ipv4Addr`.
291 unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
294 /// Changes the IP address associated with this socket address.
299 /// use std::net::{SocketAddrV4, Ipv4Addr};
301 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
302 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
303 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
305 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
306 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
307 self.inner.sin_addr = new_ip.into_inner()
310 /// Returns the port number associated with this socket address.
315 /// use std::net::{SocketAddrV4, Ipv4Addr};
317 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
318 /// assert_eq!(socket.port(), 8080);
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn port(&self) -> u16 {
322 ntohs(self.inner.sin_port)
325 /// Changes the port number associated with this socket address.
330 /// use std::net::{SocketAddrV4, Ipv4Addr};
332 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
333 /// socket.set_port(4242);
334 /// assert_eq!(socket.port(), 4242);
336 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
337 pub fn set_port(&mut self, new_port: u16) {
338 self.inner.sin_port = htons(new_port);
343 /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
344 /// and the `flowinfo` and `scope_id` fields.
346 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
347 /// parameters, see [IETF RFC 2553, Section 3.3].
349 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
350 /// [`IPv6` address]: Ipv6Addr
355 /// use std::net::{SocketAddrV6, Ipv6Addr};
357 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
362 inner: c::sockaddr_in6 {
363 sin6_family: c::AF_INET6 as c::sa_family_t,
364 sin6_port: htons(port),
365 sin6_addr: *ip.as_inner(),
366 sin6_flowinfo: flowinfo,
367 sin6_scope_id: scope_id,
368 ..unsafe { mem::zeroed() }
373 /// Returns the IP address associated with this socket address.
378 /// use std::net::{SocketAddrV6, Ipv6Addr};
380 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
381 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
383 #[stable(feature = "rust1", since = "1.0.0")]
384 pub fn ip(&self) -> &Ipv6Addr {
385 unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }
388 /// Changes the IP address associated with this socket address.
393 /// use std::net::{SocketAddrV6, Ipv6Addr};
395 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
396 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
397 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
399 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
400 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
401 self.inner.sin6_addr = *new_ip.as_inner()
404 /// Returns the port number associated with this socket address.
409 /// use std::net::{SocketAddrV6, Ipv6Addr};
411 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
412 /// assert_eq!(socket.port(), 8080);
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn port(&self) -> u16 {
416 ntohs(self.inner.sin6_port)
419 /// Changes the port number associated with this socket address.
424 /// use std::net::{SocketAddrV6, Ipv6Addr};
426 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
427 /// socket.set_port(4242);
428 /// assert_eq!(socket.port(), 4242);
430 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
431 pub fn set_port(&mut self, new_port: u16) {
432 self.inner.sin6_port = htons(new_port);
435 /// Returns the flow information associated with this address.
437 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
438 /// as specified in [IETF RFC 2553, Section 3.3].
439 /// It combines information about the flow label and the traffic class as specified
440 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
442 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
443 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
444 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
445 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
450 /// use std::net::{SocketAddrV6, Ipv6Addr};
452 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
453 /// assert_eq!(socket.flowinfo(), 10);
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn flowinfo(&self) -> u32 {
457 self.inner.sin6_flowinfo
460 /// Changes the flow information associated with this socket address.
462 /// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
467 /// use std::net::{SocketAddrV6, Ipv6Addr};
469 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
470 /// socket.set_flowinfo(56);
471 /// assert_eq!(socket.flowinfo(), 56);
473 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
474 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
475 self.inner.sin6_flowinfo = new_flowinfo;
478 /// Returns the scope ID associated with this address.
480 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
481 /// as specified in [IETF RFC 2553, Section 3.3].
483 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
488 /// use std::net::{SocketAddrV6, Ipv6Addr};
490 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
491 /// assert_eq!(socket.scope_id(), 78);
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub fn scope_id(&self) -> u32 {
495 self.inner.sin6_scope_id
498 /// Changes the scope ID associated with this socket address.
500 /// See [`SocketAddrV6::scope_id`]'s documentation for more details.
505 /// use std::net::{SocketAddrV6, Ipv6Addr};
507 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
508 /// socket.set_scope_id(42);
509 /// assert_eq!(socket.scope_id(), 42);
511 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
512 pub fn set_scope_id(&mut self, new_scope_id: u32) {
513 self.inner.sin6_scope_id = new_scope_id;
517 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
518 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
519 SocketAddrV4 { inner: addr }
523 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
524 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
525 SocketAddrV6 { inner: addr }
529 #[stable(feature = "ip_from_ip", since = "1.16.0")]
530 impl From<SocketAddrV4> for SocketAddr {
531 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
532 fn from(sock4: SocketAddrV4) -> SocketAddr {
533 SocketAddr::V4(sock4)
537 #[stable(feature = "ip_from_ip", since = "1.16.0")]
538 impl From<SocketAddrV6> for SocketAddr {
539 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
540 fn from(sock6: SocketAddrV6) -> SocketAddr {
541 SocketAddr::V6(sock6)
545 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
546 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
547 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
549 /// This conversion creates a [`SocketAddr::V4`] for a [`IpAddr::V4`]
550 /// and creates a [`SocketAddr::V6`] for a [`IpAddr::V6`].
552 /// `u16` is treated as port of the newly created [`SocketAddr`].
553 fn from(pieces: (I, u16)) -> SocketAddr {
554 SocketAddr::new(pieces.0.into(), pieces.1)
558 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
559 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
561 SocketAddr::V4(ref a) => {
562 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
564 SocketAddr::V6(ref a) => {
565 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
571 #[stable(feature = "rust1", since = "1.0.0")]
572 impl fmt::Display for SocketAddr {
573 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575 SocketAddr::V4(ref a) => a.fmt(f),
576 SocketAddr::V6(ref a) => a.fmt(f),
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl fmt::Debug for SocketAddr {
583 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
584 fmt::Display::fmt(self, fmt)
588 #[stable(feature = "rust1", since = "1.0.0")]
589 impl fmt::Display for SocketAddrV4 {
590 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
591 // Fast path: if there's no alignment stuff, write to the output buffer
593 if f.precision().is_none() && f.width().is_none() {
594 write!(f, "{}:{}", self.ip(), self.port())
596 const IPV4_SOCKET_BUF_LEN: usize = (3 * 4) // the segments
597 + 3 // the separators
599 let mut buf = [0; IPV4_SOCKET_BUF_LEN];
600 let mut buf_slice = &mut buf[..];
602 // Unwrap is fine because writing to a sufficiently-sized
603 // buffer is infallible
604 write!(buf_slice, "{}:{}", self.ip(), self.port()).unwrap();
605 let len = IPV4_SOCKET_BUF_LEN - buf_slice.len();
607 // This unsafe is OK because we know what is being written to the buffer
608 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
614 #[stable(feature = "rust1", since = "1.0.0")]
615 impl fmt::Debug for SocketAddrV4 {
616 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
617 fmt::Display::fmt(self, fmt)
621 #[stable(feature = "rust1", since = "1.0.0")]
622 impl fmt::Display for SocketAddrV6 {
623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624 // Fast path: if there's no alignment stuff, write to the output
626 if f.precision().is_none() && f.width().is_none() {
627 write!(f, "[{}]:{}", self.ip(), self.port())
629 const IPV6_SOCKET_BUF_LEN: usize = (4 * 8) // The address
630 + 7 // The colon separators
634 let mut buf = [0; IPV6_SOCKET_BUF_LEN];
635 let mut buf_slice = &mut buf[..];
637 // Unwrap is fine because writing to a sufficiently-sized
638 // buffer is infallible
639 write!(buf_slice, "[{}]:{}", self.ip(), self.port()).unwrap();
640 let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
642 // This unsafe is OK because we know what is being written to the buffer
643 let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl fmt::Debug for SocketAddrV6 {
651 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
652 fmt::Display::fmt(self, fmt)
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl Clone for SocketAddrV4 {
658 fn clone(&self) -> SocketAddrV4 {
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl Clone for SocketAddrV6 {
664 fn clone(&self) -> SocketAddrV6 {
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl PartialEq for SocketAddrV4 {
671 fn eq(&self, other: &SocketAddrV4) -> bool {
672 self.inner.sin_port == other.inner.sin_port
673 && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl PartialEq for SocketAddrV6 {
678 fn eq(&self, other: &SocketAddrV6) -> bool {
679 self.inner.sin6_port == other.inner.sin6_port
680 && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
681 && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
682 && self.inner.sin6_scope_id == other.inner.sin6_scope_id
685 #[stable(feature = "rust1", since = "1.0.0")]
686 impl Eq for SocketAddrV4 {}
687 #[stable(feature = "rust1", since = "1.0.0")]
688 impl Eq for SocketAddrV6 {}
690 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
691 impl PartialOrd for SocketAddrV4 {
692 fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
693 Some(self.cmp(other))
697 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
698 impl PartialOrd for SocketAddrV6 {
699 fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
700 Some(self.cmp(other))
704 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
705 impl Ord for SocketAddrV4 {
706 fn cmp(&self, other: &SocketAddrV4) -> Ordering {
707 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
711 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
712 impl Ord for SocketAddrV6 {
713 fn cmp(&self, other: &SocketAddrV6) -> Ordering {
714 self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl hash::Hash for SocketAddrV4 {
720 fn hash<H: hash::Hasher>(&self, s: &mut H) {
721 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
724 #[stable(feature = "rust1", since = "1.0.0")]
725 impl hash::Hash for SocketAddrV6 {
726 fn hash<H: hash::Hasher>(&self, s: &mut H) {
728 self.inner.sin6_port,
729 &self.inner.sin6_addr.s6_addr,
730 self.inner.sin6_flowinfo,
731 self.inner.sin6_scope_id,
737 /// A trait for objects which can be converted or resolved to one or more
738 /// [`SocketAddr`] values.
740 /// This trait is used for generic address resolution when constructing network
741 /// objects. By default it is implemented for the following types:
743 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
745 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
746 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
747 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
749 /// * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
750 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
753 /// * [`&str`]: the string should be either a string representation of a
754 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
755 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
757 /// This trait allows constructing network objects like [`TcpStream`] or
758 /// [`UdpSocket`] easily with values of various types for the bind/connection
759 /// address. It is needed because sometimes one type is more appropriate than
760 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
761 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
762 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
763 /// some other type (e.g., a string) just for it to be converted back to
764 /// [`SocketAddr`] in constructor methods is pointless.
766 /// Addresses returned by the operating system that are not IP addresses are
767 /// silently ignored.
769 /// [`FromStr`]: crate::str::FromStr
771 /// [`TcpStream`]: crate::net::TcpStream
772 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
773 /// [`UdpSocket`]: crate::net::UdpSocket
777 /// Creating a [`SocketAddr`] iterator that yields one item:
780 /// use std::net::{ToSocketAddrs, SocketAddr};
782 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
783 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
785 /// assert_eq!(Some(addr), addrs_iter.next());
786 /// assert!(addrs_iter.next().is_none());
789 /// Creating a [`SocketAddr`] iterator from a hostname:
792 /// use std::net::{SocketAddr, ToSocketAddrs};
794 /// // assuming 'localhost' resolves to 127.0.0.1
795 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
796 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
797 /// assert!(addrs_iter.next().is_none());
799 /// // assuming 'foo' does not resolve
800 /// assert!("foo:443".to_socket_addrs().is_err());
803 /// Creating a [`SocketAddr`] iterator that yields multiple items:
806 /// use std::net::{SocketAddr, ToSocketAddrs};
808 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
809 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
810 /// let addrs = vec![addr1, addr2];
812 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
814 /// assert_eq!(Some(addr1), addrs_iter.next());
815 /// assert_eq!(Some(addr2), addrs_iter.next());
816 /// assert!(addrs_iter.next().is_none());
819 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
820 /// socket address `&str` (missing the port):
824 /// use std::net::ToSocketAddrs;
826 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
827 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
830 /// [`TcpStream::connect`] is an example of an function that utilizes
831 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
835 /// use std::net::{TcpStream, Ipv4Addr};
837 /// let stream = TcpStream::connect(("127.0.0.1", 443));
839 /// let stream = TcpStream::connect("127.0.0.1:443");
841 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
844 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
845 #[stable(feature = "rust1", since = "1.0.0")]
846 pub trait ToSocketAddrs {
847 /// Returned iterator over socket addresses which this type may correspond
849 #[stable(feature = "rust1", since = "1.0.0")]
850 type Iter: Iterator<Item = SocketAddr>;
852 /// Converts this object to an iterator of resolved `SocketAddr`s.
854 /// The returned iterator may not actually yield any values depending on the
855 /// outcome of any resolution performed.
857 /// Note that this function may block the current thread while resolution is
859 #[stable(feature = "rust1", since = "1.0.0")]
860 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl ToSocketAddrs for SocketAddr {
865 type Iter = option::IntoIter<SocketAddr>;
866 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
867 Ok(Some(*self).into_iter())
871 #[stable(feature = "rust1", since = "1.0.0")]
872 impl ToSocketAddrs for SocketAddrV4 {
873 type Iter = option::IntoIter<SocketAddr>;
874 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
875 SocketAddr::V4(*self).to_socket_addrs()
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl ToSocketAddrs for SocketAddrV6 {
881 type Iter = option::IntoIter<SocketAddr>;
882 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
883 SocketAddr::V6(*self).to_socket_addrs()
887 #[stable(feature = "rust1", since = "1.0.0")]
888 impl ToSocketAddrs for (IpAddr, u16) {
889 type Iter = option::IntoIter<SocketAddr>;
890 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
891 let (ip, port) = *self;
893 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
894 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
899 #[stable(feature = "rust1", since = "1.0.0")]
900 impl ToSocketAddrs for (Ipv4Addr, u16) {
901 type Iter = option::IntoIter<SocketAddr>;
902 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
903 let (ip, port) = *self;
904 SocketAddrV4::new(ip, port).to_socket_addrs()
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl ToSocketAddrs for (Ipv6Addr, u16) {
910 type Iter = option::IntoIter<SocketAddr>;
911 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
912 let (ip, port) = *self;
913 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
917 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl ToSocketAddrs for (&str, u16) {
930 type Iter = vec::IntoIter<SocketAddr>;
931 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
932 let (host, port) = *self;
934 // try to parse the host as a regular IP address first
935 if let Ok(addr) = host.parse::<Ipv4Addr>() {
936 let addr = SocketAddrV4::new(addr, port);
937 return Ok(vec![SocketAddr::V4(addr)].into_iter());
939 if let Ok(addr) = host.parse::<Ipv6Addr>() {
940 let addr = SocketAddrV6::new(addr, port, 0, 0);
941 return Ok(vec![SocketAddr::V6(addr)].into_iter());
944 resolve_socket_addr((host, port).try_into()?)
948 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
949 impl ToSocketAddrs for (String, u16) {
950 type Iter = vec::IntoIter<SocketAddr>;
951 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
952 (&*self.0, self.1).to_socket_addrs()
956 // accepts strings like 'localhost:12345'
957 #[stable(feature = "rust1", since = "1.0.0")]
958 impl ToSocketAddrs for str {
959 type Iter = vec::IntoIter<SocketAddr>;
960 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
961 // try to parse as a regular SocketAddr first
962 if let Ok(addr) = self.parse() {
963 return Ok(vec![addr].into_iter());
966 resolve_socket_addr(self.try_into()?)
970 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
971 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
972 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
974 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
975 Ok(self.iter().cloned())
979 #[stable(feature = "rust1", since = "1.0.0")]
980 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
982 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
983 (**self).to_socket_addrs()
987 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
988 impl ToSocketAddrs for String {
989 type Iter = vec::IntoIter<SocketAddr>;
990 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
991 (&**self).to_socket_addrs()
995 #[cfg(all(test, not(target_os = "emscripten")))]
997 use crate::net::test::{sa4, sa6, tsa};
1001 fn to_socket_addr_ipaddr_u16() {
1002 let a = Ipv4Addr::new(77, 88, 21, 11);
1004 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
1005 assert_eq!(Ok(vec![e]), tsa((a, p)));
1009 fn to_socket_addr_str_u16() {
1010 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
1011 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
1013 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
1014 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
1016 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
1017 #[cfg(not(target_env = "sgx"))]
1018 assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
1019 #[cfg(target_env = "sgx")]
1024 fn to_socket_addr_str() {
1025 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
1026 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
1028 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
1029 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
1031 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
1032 #[cfg(not(target_env = "sgx"))]
1033 assert!(tsa("localhost:23924").unwrap().contains(&a));
1034 #[cfg(target_env = "sgx")]
1039 fn to_socket_addr_string() {
1040 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
1041 assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
1042 assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
1043 assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
1045 let s = format!("{}:{}", "77.88.21.11", "24352");
1046 assert_eq!(Ok(vec![a]), tsa(s));
1047 // s has been moved into the tsa call
1051 fn bind_udp_socket_bad() {
1052 // rust-lang/rust#53957: This is a regression test for a parsing problem
1053 // discovered as part of issue rust-lang/rust#23076, where we were
1054 // incorrectly parsing invalid input and then that would result in a
1055 // successful `UdpSocket` binding when we would expect failure.
1057 // At one time, this test was written as a call to `tsa` with
1058 // INPUT_23076. However, that structure yields an unreliable test,
1059 // because it ends up passing junk input to the DNS server, and some DNS
1060 // servers will respond with `Ok` to such input, with the ip address of
1061 // the DNS server itself.
1063 // This form of the test is more robust: even when the DNS server
1064 // returns its own address, it is still an error to bind a UDP socket to
1065 // a non-local address, and so we still get an error here in that case.
1067 const INPUT_23076: &'static str = "1200::AB00:1234::2552:7777:1313:34300";
1069 assert!(crate::net::UdpSocket::bind(INPUT_23076).is_err())
1074 fn ip4(low: u8) -> Ipv4Addr {
1075 Ipv4Addr::new(77, 88, 21, low)
1077 fn ip6(low: u16) -> Ipv6Addr {
1078 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low)
1081 let mut v4 = SocketAddrV4::new(ip4(11), 80);
1082 assert_eq!(v4.ip(), &ip4(11));
1084 assert_eq!(v4.ip(), &ip4(12));
1086 let mut addr = SocketAddr::V4(v4);
1087 assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
1088 addr.set_ip(IpAddr::V4(ip4(13)));
1089 assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
1090 addr.set_ip(IpAddr::V6(ip6(14)));
1091 assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
1093 let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1094 assert_eq!(v6.ip(), &ip6(1));
1096 assert_eq!(v6.ip(), &ip6(2));
1098 let mut addr = SocketAddr::V6(v6);
1099 assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
1100 addr.set_ip(IpAddr::V6(ip6(3)));
1101 assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
1102 addr.set_ip(IpAddr::V4(ip4(4)));
1103 assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
1108 let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1109 assert_eq!(v4.port(), 80);
1111 assert_eq!(v4.port(), 443);
1113 let mut addr = SocketAddr::V4(v4);
1114 assert_eq!(addr.port(), 443);
1115 addr.set_port(8080);
1116 assert_eq!(addr.port(), 8080);
1118 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1119 assert_eq!(v6.port(), 80);
1121 assert_eq!(v6.port(), 443);
1123 let mut addr = SocketAddr::V6(v6);
1124 assert_eq!(addr.port(), 443);
1125 addr.set_port(8080);
1126 assert_eq!(addr.port(), 8080);
1131 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1132 assert_eq!(v6.flowinfo(), 10);
1133 v6.set_flowinfo(20);
1134 assert_eq!(v6.flowinfo(), 20);
1139 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1140 assert_eq!(v6.scope_id(), 10);
1141 v6.set_scope_id(20);
1142 assert_eq!(v6.scope_id(), 20);
1147 let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1148 assert!(v4.is_ipv4());
1149 assert!(!v4.is_ipv6());
1154 let v6 = SocketAddr::V6(SocketAddrV6::new(
1155 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1),
1160 assert!(!v6.is_ipv4());
1161 assert!(v6.is_ipv6());
1165 fn socket_v4_to_str() {
1166 let socket = SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 8080);
1168 assert_eq!(format!("{}", socket), "192.168.0.1:8080");
1169 assert_eq!(format!("{:<20}", socket), "192.168.0.1:8080 ");
1170 assert_eq!(format!("{:>20}", socket), " 192.168.0.1:8080");
1171 assert_eq!(format!("{:^20}", socket), " 192.168.0.1:8080 ");
1172 assert_eq!(format!("{:.10}", socket), "192.168.0.");
1176 fn socket_v6_to_str() {
1177 let socket: SocketAddrV6 = "[2a02:6b8:0:1::1]:53".parse().unwrap();
1179 assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1]:53");
1180 assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1]:53 ");
1181 assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1]:53");
1182 assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1]:53 ");
1183 assert_eq!(format!("{:.15}", socket), "[2a02:6b8:0:1::");
1188 let v4_1 = "224.120.45.1:23456".parse::<SocketAddrV4>().unwrap();
1189 let v4_2 = "224.210.103.5:12345".parse::<SocketAddrV4>().unwrap();
1190 let v4_3 = "224.210.103.5:23456".parse::<SocketAddrV4>().unwrap();
1191 let v6_1 = "[2001:db8:f00::1002]:23456".parse::<SocketAddrV6>().unwrap();
1192 let v6_2 = "[2001:db8:f00::2001]:12345".parse::<SocketAddrV6>().unwrap();
1193 let v6_3 = "[2001:db8:f00::2001]:23456".parse::<SocketAddrV6>().unwrap();
1196 assert_eq!(v4_1, v4_1);
1197 assert_eq!(v6_1, v6_1);
1198 assert_eq!(SocketAddr::V4(v4_1), SocketAddr::V4(v4_1));
1199 assert_eq!(SocketAddr::V6(v6_1), SocketAddr::V6(v6_1));
1200 assert!(v4_1 != v4_2);
1201 assert!(v6_1 != v6_2);
1203 // compare different addresses
1204 assert!(v4_1 < v4_2);
1205 assert!(v6_1 < v6_2);
1206 assert!(v4_2 > v4_1);
1207 assert!(v6_2 > v6_1);
1209 // compare the same address with different ports
1210 assert!(v4_2 < v4_3);
1211 assert!(v6_2 < v6_3);
1212 assert!(v4_3 > v4_2);
1213 assert!(v6_3 > v6_2);
1215 // compare different addresses with the same port
1216 assert!(v4_1 < v4_3);
1217 assert!(v6_1 < v6_3);
1218 assert!(v4_3 > v4_1);
1219 assert!(v6_3 > v6_1);
1221 // compare with an inferred right-hand side
1222 assert_eq!(v4_1, "224.120.45.1:23456".parse().unwrap());
1223 assert_eq!(v6_1, "[2001:db8:f00::1002]:23456".parse().unwrap());
1224 assert_eq!(SocketAddr::V4(v4_1), "224.120.45.1:23456".parse().unwrap());