1 #[cfg(all(test, not(target_os = "emscripten")))]
4 use crate::cmp
::Ordering
;
7 use crate::io
::{self, Write}
;
10 use crate::net
::{IpAddr, Ipv4Addr, Ipv6Addr}
;
13 use crate::sys
::net
::netc
as c
;
14 use crate::sys_common
::net
::LookupHost
;
15 use crate::sys_common
::{FromInner, IntoInner}
;
18 /// An internet socket address, either IPv4 or IPv6.
20 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
21 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
22 /// [`SocketAddrV6`]'s respective documentation for more details.
24 /// The size of a `SocketAddr` instance may vary depending on the target operating
27 /// [IP address]: IpAddr
32 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
34 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
36 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
37 /// assert_eq!(socket.port(), 8080);
38 /// assert_eq!(socket.is_ipv4(), true);
40 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
41 #[stable(feature = "rust1", since = "1.0.0")]
43 /// An IPv4 socket address.
44 #[stable(feature = "rust1", since = "1.0.0")]
45 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
46 /// An IPv6 socket address.
47 #[stable(feature = "rust1", since = "1.0.0")]
48 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
51 /// An IPv4 socket address.
53 /// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
54 /// stated in [IETF RFC 793].
56 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
58 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
59 /// system. Do not assume that this type has the same memory layout as the underlying
60 /// system representation.
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);
76 #[derive(Copy, Clone, Eq, PartialEq)]
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct SocketAddrV4
{
83 /// An IPv6 socket address.
85 /// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
86 /// as fields containing the traffic class, the flow label, and a scope identifier
87 /// (see [IETF RFC 2553, Section 3.3] for more details).
89 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
91 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
92 /// system. Do not assume that this type has the same memory layout as the underlying
93 /// system representation.
95 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
96 /// [`IPv6` address]: Ipv6Addr
101 /// use std::net::{Ipv6Addr, SocketAddrV6};
103 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
105 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
106 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
107 /// assert_eq!(socket.port(), 8080);
109 #[derive(Copy, Clone, Eq, PartialEq)]
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub struct SocketAddrV6
{
119 /// Creates a new socket address from an [IP address] and a port number.
121 /// [IP address]: IpAddr
126 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
128 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
129 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
130 /// assert_eq!(socket.port(), 8080);
132 #[stable(feature = "ip_addr", since = "1.7.0")]
134 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
135 pub const fn new(ip
: IpAddr
, port
: u16) -> SocketAddr
{
137 IpAddr
::V4(a
) => SocketAddr
::V4(SocketAddrV4
::new(a
, port
)),
138 IpAddr
::V6(a
) => SocketAddr
::V6(SocketAddrV6
::new(a
, port
, 0, 0)),
142 /// Returns the IP address associated with this socket address.
147 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
149 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
150 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
153 #[stable(feature = "ip_addr", since = "1.7.0")]
154 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
155 pub const fn ip(&self) -> IpAddr
{
157 SocketAddr
::V4(ref a
) => IpAddr
::V4(*a
.ip()),
158 SocketAddr
::V6(ref a
) => IpAddr
::V6(*a
.ip()),
162 /// Changes the IP address associated with this socket address.
167 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
169 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
170 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
171 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
173 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
174 pub fn set_ip(&mut self, new_ip
: IpAddr
) {
175 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
176 match (self, new_ip
) {
177 (&mut SocketAddr
::V4(ref mut a
), IpAddr
::V4(new_ip
)) => a
.set_ip(new_ip
),
178 (&mut SocketAddr
::V6(ref mut a
), IpAddr
::V6(new_ip
)) => a
.set_ip(new_ip
),
179 (self_
, new_ip
) => *self_
= Self::new(new_ip
, self_
.port()),
183 /// Returns the port number associated with this socket address.
188 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
190 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
191 /// assert_eq!(socket.port(), 8080);
194 #[stable(feature = "rust1", since = "1.0.0")]
195 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
196 pub const fn port(&self) -> u16 {
198 SocketAddr
::V4(ref a
) => a
.port(),
199 SocketAddr
::V6(ref a
) => a
.port(),
203 /// Changes the port number associated with this socket address.
208 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
210 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
211 /// socket.set_port(1025);
212 /// assert_eq!(socket.port(), 1025);
214 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
215 pub fn set_port(&mut self, new_port
: u16) {
217 SocketAddr
::V4(ref mut a
) => a
.set_port(new_port
),
218 SocketAddr
::V6(ref mut a
) => a
.set_port(new_port
),
222 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
223 /// [`IPv4` address], and [`false`] otherwise.
225 /// [IP address]: IpAddr
226 /// [`IPv4` address]: IpAddr::V4
231 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
233 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
234 /// assert_eq!(socket.is_ipv4(), true);
235 /// assert_eq!(socket.is_ipv6(), false);
238 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
239 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
240 pub const fn is_ipv4(&self) -> bool
{
241 matches
!(*self, SocketAddr
::V4(_
))
244 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
245 /// [`IPv6` address], and [`false`] otherwise.
247 /// [IP address]: IpAddr
248 /// [`IPv6` address]: IpAddr::V6
253 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
255 /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
256 /// assert_eq!(socket.is_ipv4(), false);
257 /// assert_eq!(socket.is_ipv6(), true);
260 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
261 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
262 pub const fn is_ipv6(&self) -> bool
{
263 matches
!(*self, SocketAddr
::V6(_
))
268 /// Creates a new socket address from an [`IPv4` address] and a port number.
270 /// [`IPv4` address]: Ipv4Addr
275 /// use std::net::{SocketAddrV4, Ipv4Addr};
277 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
279 #[stable(feature = "rust1", since = "1.0.0")]
281 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
282 pub const fn new(ip
: Ipv4Addr
, port
: u16) -> SocketAddrV4
{
283 SocketAddrV4 { ip, port }
286 /// Returns the IP address associated with this socket address.
291 /// use std::net::{SocketAddrV4, Ipv4Addr};
293 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
294 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
297 #[stable(feature = "rust1", since = "1.0.0")]
298 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
299 pub const fn ip(&self) -> &Ipv4Addr
{
303 /// Changes the IP address associated with this socket address.
308 /// use std::net::{SocketAddrV4, Ipv4Addr};
310 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
311 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
312 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
314 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
315 pub fn set_ip(&mut self, new_ip
: Ipv4Addr
) {
319 /// Returns the port number associated with this socket address.
324 /// use std::net::{SocketAddrV4, Ipv4Addr};
326 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
327 /// assert_eq!(socket.port(), 8080);
330 #[stable(feature = "rust1", since = "1.0.0")]
331 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
332 pub const fn port(&self) -> u16 {
336 /// Changes the port number associated with this socket address.
341 /// use std::net::{SocketAddrV4, Ipv4Addr};
343 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
344 /// socket.set_port(4242);
345 /// assert_eq!(socket.port(), 4242);
347 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
348 pub fn set_port(&mut self, new_port
: u16) {
349 self.port
= new_port
;
354 /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
355 /// and the `flowinfo` and `scope_id` fields.
357 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
358 /// parameters, see [IETF RFC 2553, Section 3.3].
360 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
361 /// [`IPv6` address]: Ipv6Addr
366 /// use std::net::{SocketAddrV6, Ipv6Addr};
368 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
370 #[stable(feature = "rust1", since = "1.0.0")]
372 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
373 pub const fn new(ip
: Ipv6Addr
, port
: u16, flowinfo
: u32, scope_id
: u32) -> SocketAddrV6
{
374 SocketAddrV6 { ip, port, flowinfo, scope_id }
377 /// Returns the IP address associated with this socket address.
382 /// use std::net::{SocketAddrV6, Ipv6Addr};
384 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
385 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
388 #[stable(feature = "rust1", since = "1.0.0")]
389 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
390 pub const fn ip(&self) -> &Ipv6Addr
{
394 /// Changes the IP address associated with this socket address.
399 /// use std::net::{SocketAddrV6, Ipv6Addr};
401 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
402 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
403 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
405 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
406 pub fn set_ip(&mut self, new_ip
: Ipv6Addr
) {
410 /// Returns the port number associated with this socket address.
415 /// use std::net::{SocketAddrV6, Ipv6Addr};
417 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
418 /// assert_eq!(socket.port(), 8080);
421 #[stable(feature = "rust1", since = "1.0.0")]
422 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
423 pub const fn port(&self) -> u16 {
427 /// Changes the port number associated with this socket address.
432 /// use std::net::{SocketAddrV6, Ipv6Addr};
434 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
435 /// socket.set_port(4242);
436 /// assert_eq!(socket.port(), 4242);
438 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
439 pub fn set_port(&mut self, new_port
: u16) {
440 self.port
= new_port
;
443 /// Returns the flow information associated with this address.
445 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
446 /// as specified in [IETF RFC 2553, Section 3.3].
447 /// It combines information about the flow label and the traffic class as specified
448 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
450 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
451 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
452 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
453 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
458 /// use std::net::{SocketAddrV6, Ipv6Addr};
460 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
461 /// assert_eq!(socket.flowinfo(), 10);
464 #[stable(feature = "rust1", since = "1.0.0")]
465 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
466 pub const fn flowinfo(&self) -> u32 {
470 /// Changes the flow information associated with this socket address.
472 /// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
477 /// use std::net::{SocketAddrV6, Ipv6Addr};
479 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
480 /// socket.set_flowinfo(56);
481 /// assert_eq!(socket.flowinfo(), 56);
483 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
484 pub fn set_flowinfo(&mut self, new_flowinfo
: u32) {
485 self.flowinfo
= new_flowinfo
;
488 /// Returns the scope ID associated with this address.
490 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
491 /// as specified in [IETF RFC 2553, Section 3.3].
493 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
498 /// use std::net::{SocketAddrV6, Ipv6Addr};
500 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
501 /// assert_eq!(socket.scope_id(), 78);
504 #[stable(feature = "rust1", since = "1.0.0")]
505 #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")]
506 pub const fn scope_id(&self) -> u32 {
510 /// Changes the scope ID associated with this socket address.
512 /// See [`SocketAddrV6::scope_id`]'s documentation for more details.
517 /// use std::net::{SocketAddrV6, Ipv6Addr};
519 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
520 /// socket.set_scope_id(42);
521 /// assert_eq!(socket.scope_id(), 42);
523 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
524 pub fn set_scope_id(&mut self, new_scope_id
: u32) {
525 self.scope_id
= new_scope_id
;
529 impl FromInner
<c
::sockaddr_in
> for SocketAddrV4
{
530 fn from_inner(addr
: c
::sockaddr_in
) -> SocketAddrV4
{
531 SocketAddrV4 { ip: Ipv4Addr::from_inner(addr.sin_addr), port: u16::from_be(addr.sin_port) }
535 impl FromInner
<c
::sockaddr_in6
> for SocketAddrV6
{
536 fn from_inner(addr
: c
::sockaddr_in6
) -> SocketAddrV6
{
538 ip
: Ipv6Addr
::from_inner(addr
.sin6_addr
),
539 port
: u16::from_be(addr
.sin6_port
),
540 flowinfo
: addr
.sin6_flowinfo
,
541 scope_id
: addr
.sin6_scope_id
,
546 impl IntoInner
<c
::sockaddr_in
> for SocketAddrV4
{
547 fn into_inner(self) -> c
::sockaddr_in
{
549 sin_family
: c
::AF_INET
as c
::sa_family_t
,
550 sin_port
: self.port
.to_be(),
551 sin_addr
: self.ip
.into_inner(),
552 ..unsafe { mem::zeroed() }
557 impl IntoInner
<c
::sockaddr_in6
> for SocketAddrV6
{
558 fn into_inner(self) -> c
::sockaddr_in6
{
560 sin6_family
: c
::AF_INET6
as c
::sa_family_t
,
561 sin6_port
: self.port
.to_be(),
562 sin6_addr
: self.ip
.into_inner(),
563 sin6_flowinfo
: self.flowinfo
,
564 sin6_scope_id
: self.scope_id
,
565 ..unsafe { mem::zeroed() }
570 #[stable(feature = "ip_from_ip", since = "1.16.0")]
571 impl From
<SocketAddrV4
> for SocketAddr
{
572 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
573 fn from(sock4
: SocketAddrV4
) -> SocketAddr
{
574 SocketAddr
::V4(sock4
)
578 #[stable(feature = "ip_from_ip", since = "1.16.0")]
579 impl From
<SocketAddrV6
> for SocketAddr
{
580 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
581 fn from(sock6
: SocketAddrV6
) -> SocketAddr
{
582 SocketAddr
::V6(sock6
)
586 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
587 impl<I
: Into
<IpAddr
>> From
<(I
, u16)> for SocketAddr
{
588 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
590 /// This conversion creates a [`SocketAddr::V4`] for an [`IpAddr::V4`]
591 /// and creates a [`SocketAddr::V6`] for an [`IpAddr::V6`].
593 /// `u16` is treated as port of the newly created [`SocketAddr`].
594 fn from(pieces
: (I
, u16)) -> SocketAddr
{
595 SocketAddr
::new(pieces
.0.into
(), pieces
.1)
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl fmt
::Display
for SocketAddr
{
601 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
603 SocketAddr
::V4(ref a
) => a
.fmt(f
),
604 SocketAddr
::V6(ref a
) => a
.fmt(f
),
609 #[stable(feature = "rust1", since = "1.0.0")]
610 impl fmt
::Debug
for SocketAddr
{
611 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
612 fmt
::Display
::fmt(self, fmt
)
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl fmt
::Display
for SocketAddrV4
{
618 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
619 // Fast path: if there's no alignment stuff, write to the output buffer
621 if f
.precision().is_none() && f
.width().is_none() {
622 write
!(f
, "{}:{}", self.ip(), self.port())
624 const IPV4_SOCKET_BUF_LEN
: usize = (3 * 4) // the segments
625 + 3 // the separators
627 let mut buf
= [0; IPV4_SOCKET_BUF_LEN
];
628 let mut buf_slice
= &mut buf
[..];
630 // Unwrap is fine because writing to a sufficiently-sized
631 // buffer is infallible
632 write
!(buf_slice
, "{}:{}", self.ip(), self.port()).unwrap();
633 let len
= IPV4_SOCKET_BUF_LEN
- buf_slice
.len();
635 // This unsafe is OK because we know what is being written to the buffer
636 let buf
= unsafe { crate::str::from_utf8_unchecked(&buf[..len]) }
;
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl fmt
::Debug
for SocketAddrV4
{
644 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
645 fmt
::Display
::fmt(self, fmt
)
649 #[stable(feature = "rust1", since = "1.0.0")]
650 impl fmt
::Display
for SocketAddrV6
{
651 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
652 // Fast path: if there's no alignment stuff, write to the output
654 if f
.precision().is_none() && f
.width().is_none() {
655 match self.scope_id() {
656 0 => write
!(f
, "[{}]:{}", self.ip(), self.port()),
657 scope_id
=> write
!(f
, "[{}%{}]:{}", self.ip(), scope_id
, self.port()),
660 const IPV6_SOCKET_BUF_LEN
: usize = (4 * 8) // The address
661 + 7 // The colon separators
663 + 1 + 10 // The scope id
666 let mut buf
= [0; IPV6_SOCKET_BUF_LEN
];
667 let mut buf_slice
= &mut buf
[..];
669 match self.scope_id() {
670 0 => write
!(buf_slice
, "[{}]:{}", self.ip(), self.port()),
671 scope_id
=> write
!(buf_slice
, "[{}%{}]:{}", self.ip(), scope_id
, self.port()),
673 // Unwrap is fine because writing to a sufficiently-sized
674 // buffer is infallible
676 let len
= IPV6_SOCKET_BUF_LEN
- buf_slice
.len();
678 // This unsafe is OK because we know what is being written to the buffer
679 let buf
= unsafe { crate::str::from_utf8_unchecked(&buf[..len]) }
;
685 #[stable(feature = "rust1", since = "1.0.0")]
686 impl fmt
::Debug
for SocketAddrV6
{
687 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
688 fmt
::Display
::fmt(self, fmt
)
692 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
693 impl PartialOrd
for SocketAddrV4
{
694 fn partial_cmp(&self, other
: &SocketAddrV4
) -> Option
<Ordering
> {
695 Some(self.cmp(other
))
699 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
700 impl PartialOrd
for SocketAddrV6
{
701 fn partial_cmp(&self, other
: &SocketAddrV6
) -> Option
<Ordering
> {
702 Some(self.cmp(other
))
706 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
707 impl Ord
for SocketAddrV4
{
708 fn cmp(&self, other
: &SocketAddrV4
) -> Ordering
{
709 self.ip().cmp(other
.ip()).then(self.port().cmp(&other
.port()))
713 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
714 impl Ord
for SocketAddrV6
{
715 fn cmp(&self, other
: &SocketAddrV6
) -> Ordering
{
716 self.ip().cmp(other
.ip()).then(self.port().cmp(&other
.port()))
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl hash
::Hash
for SocketAddrV4
{
722 fn hash
<H
: hash
::Hasher
>(&self, s
: &mut H
) {
723 (self.port
, self.ip
).hash(s
)
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl hash
::Hash
for SocketAddrV6
{
728 fn hash
<H
: hash
::Hasher
>(&self, s
: &mut H
) {
729 (self.port
, &self.ip
, self.flowinfo
, self.scope_id
).hash(s
)
733 /// A trait for objects which can be converted or resolved to one or more
734 /// [`SocketAddr`] values.
736 /// This trait is used for generic address resolution when constructing network
737 /// objects. By default it is implemented for the following types:
739 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
741 /// * [`SocketAddrV4`], [`SocketAddrV6`], <code>([IpAddr], [u16])</code>,
742 /// <code>([Ipv4Addr], [u16])</code>, <code>([Ipv6Addr], [u16])</code>:
743 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
745 /// * <code>(&[str], [u16])</code>: <code>&[str]</code> should be either a string representation
746 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
747 /// name. [`u16`] is the port number.
749 /// * <code>&[str]</code>: the string should be either a string representation of a
750 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
751 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
753 /// This trait allows constructing network objects like [`TcpStream`] or
754 /// [`UdpSocket`] easily with values of various types for the bind/connection
755 /// address. It is needed because sometimes one type is more appropriate than
756 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
757 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
758 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
759 /// some other type (e.g., a string) just for it to be converted back to
760 /// [`SocketAddr`] in constructor methods is pointless.
762 /// Addresses returned by the operating system that are not IP addresses are
763 /// silently ignored.
765 /// [`FromStr`]: crate::str::FromStr "std::str::FromStr"
766 /// [`TcpStream`]: crate::net::TcpStream "net::TcpStream"
767 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
768 /// [`UdpSocket`]: crate::net::UdpSocket "net::UdpSocket"
772 /// Creating a [`SocketAddr`] iterator that yields one item:
775 /// use std::net::{ToSocketAddrs, SocketAddr};
777 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
778 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
780 /// assert_eq!(Some(addr), addrs_iter.next());
781 /// assert!(addrs_iter.next().is_none());
784 /// Creating a [`SocketAddr`] iterator from a hostname:
787 /// use std::net::{SocketAddr, ToSocketAddrs};
789 /// // assuming 'localhost' resolves to 127.0.0.1
790 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
791 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
792 /// assert!(addrs_iter.next().is_none());
794 /// // assuming 'foo' does not resolve
795 /// assert!("foo:443".to_socket_addrs().is_err());
798 /// Creating a [`SocketAddr`] iterator that yields multiple items:
801 /// use std::net::{SocketAddr, ToSocketAddrs};
803 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
804 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
805 /// let addrs = vec![addr1, addr2];
807 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
809 /// assert_eq!(Some(addr1), addrs_iter.next());
810 /// assert_eq!(Some(addr2), addrs_iter.next());
811 /// assert!(addrs_iter.next().is_none());
814 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
815 /// socket address `&str` (missing the port):
819 /// use std::net::ToSocketAddrs;
821 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
822 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
825 /// [`TcpStream::connect`] is an example of an function that utilizes
826 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
830 /// use std::net::{TcpStream, Ipv4Addr};
832 /// let stream = TcpStream::connect(("127.0.0.1", 443));
834 /// let stream = TcpStream::connect("127.0.0.1:443");
836 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
839 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
840 #[stable(feature = "rust1", since = "1.0.0")]
841 pub trait ToSocketAddrs
{
842 /// Returned iterator over socket addresses which this type may correspond
844 #[stable(feature = "rust1", since = "1.0.0")]
845 type Iter
: Iterator
<Item
= SocketAddr
>;
847 /// Converts this object to an iterator of resolved [`SocketAddr`]s.
849 /// The returned iterator might not actually yield any values depending on the
850 /// outcome of any resolution performed.
852 /// Note that this function may block the current thread while resolution is
854 #[stable(feature = "rust1", since = "1.0.0")]
855 fn to_socket_addrs(&self) -> io
::Result
<Self::Iter
>;
858 #[stable(feature = "rust1", since = "1.0.0")]
859 impl ToSocketAddrs
for SocketAddr
{
860 type Iter
= option
::IntoIter
<SocketAddr
>;
861 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
862 Ok(Some(*self).into_iter())
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl ToSocketAddrs
for SocketAddrV4
{
868 type Iter
= option
::IntoIter
<SocketAddr
>;
869 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
870 SocketAddr
::V4(*self).to_socket_addrs()
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl ToSocketAddrs
for SocketAddrV6
{
876 type Iter
= option
::IntoIter
<SocketAddr
>;
877 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
878 SocketAddr
::V6(*self).to_socket_addrs()
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl ToSocketAddrs
for (IpAddr
, u16) {
884 type Iter
= option
::IntoIter
<SocketAddr
>;
885 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
886 let (ip
, port
) = *self;
888 IpAddr
::V4(ref a
) => (*a
, port
).to_socket_addrs(),
889 IpAddr
::V6(ref a
) => (*a
, port
).to_socket_addrs(),
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl ToSocketAddrs
for (Ipv4Addr
, u16) {
896 type Iter
= option
::IntoIter
<SocketAddr
>;
897 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
898 let (ip
, port
) = *self;
899 SocketAddrV4
::new(ip
, port
).to_socket_addrs()
903 #[stable(feature = "rust1", since = "1.0.0")]
904 impl ToSocketAddrs
for (Ipv6Addr
, u16) {
905 type Iter
= option
::IntoIter
<SocketAddr
>;
906 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
907 let (ip
, port
) = *self;
908 SocketAddrV6
::new(ip
, port
, 0, 0).to_socket_addrs()
912 fn resolve_socket_addr(lh
: LookupHost
) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
923 #[stable(feature = "rust1", since = "1.0.0")]
924 impl ToSocketAddrs
for (&str, u16) {
925 type Iter
= vec
::IntoIter
<SocketAddr
>;
926 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
927 let (host
, port
) = *self;
929 // try to parse the host as a regular IP address first
930 if let Ok(addr
) = host
.parse
::<Ipv4Addr
>() {
931 let addr
= SocketAddrV4
::new(addr
, port
);
932 return Ok(vec
![SocketAddr
::V4(addr
)].into_iter());
934 if let Ok(addr
) = host
.parse
::<Ipv6Addr
>() {
935 let addr
= SocketAddrV6
::new(addr
, port
, 0, 0);
936 return Ok(vec
![SocketAddr
::V6(addr
)].into_iter());
939 resolve_socket_addr((host
, port
).try_into()?
)
943 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
944 impl ToSocketAddrs
for (String
, u16) {
945 type Iter
= vec
::IntoIter
<SocketAddr
>;
946 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
947 (&*self.0, self.1).to_socket_addrs()
951 // accepts strings like 'localhost:12345'
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl ToSocketAddrs
for str {
954 type Iter
= vec
::IntoIter
<SocketAddr
>;
955 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
956 // try to parse as a regular SocketAddr first
957 if let Ok(addr
) = self.parse() {
958 return Ok(vec
![addr
].into_iter());
961 resolve_socket_addr(self.try_into()?
)
965 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
966 impl<'a
> ToSocketAddrs
for &'a
[SocketAddr
] {
967 type Iter
= iter
::Cloned
<slice
::Iter
<'a
, SocketAddr
>>;
969 fn to_socket_addrs(&self) -> io
::Result
<Self::Iter
> {
970 Ok(self.iter().cloned())
974 #[stable(feature = "rust1", since = "1.0.0")]
975 impl<T
: ToSocketAddrs
+ ?Sized
> ToSocketAddrs
for &T
{
977 fn to_socket_addrs(&self) -> io
::Result
<T
::Iter
> {
978 (**self).to_socket_addrs()
982 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
983 impl ToSocketAddrs
for String
{
984 type Iter
= vec
::IntoIter
<SocketAddr
>;
985 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
986 (&**self).to_socket_addrs()