1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 use net
::{lookup_host, ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr}
;
17 use sys
::net
::netc
as c
;
18 use sys_common
::{FromInner, AsInner, IntoInner}
;
23 /// An internet socket address, either IPv4 or IPv6.
25 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
26 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
27 /// [`SocketAddrV6`]'s respective documentation for more details.
29 /// [IP address]: ../../std/net/enum.IpAddr.html
30 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
31 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
36 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
38 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
40 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
41 /// assert_eq!(socket.port(), 8080);
42 /// assert_eq!(socket.is_ipv4(), true);
44 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
45 #[stable(feature = "rust1", since = "1.0.0")]
47 /// An IPv4 socket address.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
50 /// An IPv6 socket address.
51 #[stable(feature = "rust1", since = "1.0.0")]
52 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
55 /// An IPv4 socket address.
57 /// IPv4 socket addresses consist of an [IPv4 address] and a 16-bit port number, as
58 /// stated in [IETF RFC 793].
60 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
62 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
63 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
64 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
69 /// use std::net::{Ipv4Addr, SocketAddrV4};
71 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
73 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
74 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
75 /// assert_eq!(socket.port(), 8080);
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub struct SocketAddrV4 { inner: c::sockaddr_in }
81 /// An IPv6 socket address.
83 /// IPv6 socket addresses consist of an [Ipv6 address], a 16-bit port number, as well
84 /// as fields containing the traffic class, the flow label, and a scope identifier
85 /// (see [IETF RFC 2553, Section 3.3] for more details).
87 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
89 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
90 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
91 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
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 { inner: c::sockaddr_in6 }
109 /// Creates a new socket address from an [IP address] and a port number.
111 /// [IP address]: ../../std/net/enum.IpAddr.html
116 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
118 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
119 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
120 /// assert_eq!(socket.port(), 8080);
122 #[stable(feature = "ip_addr", since = "1.7.0")]
123 pub fn new(ip
: IpAddr
, port
: u16) -> SocketAddr
{
125 IpAddr
::V4(a
) => SocketAddr
::V4(SocketAddrV4
::new(a
, port
)),
126 IpAddr
::V6(a
) => SocketAddr
::V6(SocketAddrV6
::new(a
, port
, 0, 0)),
130 /// Returns the IP address associated with this socket address.
135 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
137 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
138 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
140 #[stable(feature = "ip_addr", since = "1.7.0")]
141 pub fn ip(&self) -> IpAddr
{
143 SocketAddr
::V4(ref a
) => IpAddr
::V4(*a
.ip()),
144 SocketAddr
::V6(ref a
) => IpAddr
::V6(*a
.ip()),
148 /// Changes the IP address associated with this socket address.
153 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
155 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
156 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
157 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
159 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
160 pub fn set_ip(&mut self, new_ip
: IpAddr
) {
161 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
162 match (self, new_ip
) {
163 (&mut SocketAddr
::V4(ref mut a
), IpAddr
::V4(new_ip
)) => a
.set_ip(new_ip
),
164 (&mut SocketAddr
::V6(ref mut a
), IpAddr
::V6(new_ip
)) => a
.set_ip(new_ip
),
165 (self_
, new_ip
) => *self_
= Self::new(new_ip
, self_
.port()),
169 /// Returns the port number associated with this socket address.
174 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
176 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
177 /// assert_eq!(socket.port(), 8080);
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub fn port(&self) -> u16 {
182 SocketAddr
::V4(ref a
) => a
.port(),
183 SocketAddr
::V6(ref a
) => a
.port(),
187 /// Changes the port number associated with this socket address.
192 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
194 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
195 /// socket.set_port(1025);
196 /// assert_eq!(socket.port(), 1025);
198 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
199 pub fn set_port(&mut self, new_port
: u16) {
201 SocketAddr
::V4(ref mut a
) => a
.set_port(new_port
),
202 SocketAddr
::V6(ref mut a
) => a
.set_port(new_port
),
206 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
207 /// [IPv4 address], and [`false`] otherwise.
209 /// [`true`]: ../../std/primitive.bool.html
210 /// [`false`]: ../../std/primitive.bool.html
211 /// [IP address]: ../../std/net/enum.IpAddr.html
212 /// [IPv4 address]: ../../std/net/enum.IpAddr.html#variant.V4
217 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
220 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
221 /// assert_eq!(socket.is_ipv4(), true);
222 /// assert_eq!(socket.is_ipv6(), false);
225 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
226 pub fn is_ipv4(&self) -> bool
{
228 SocketAddr
::V4(_
) => true,
229 SocketAddr
::V6(_
) => false,
233 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
234 /// [IPv6 address], and [`false`] otherwise.
236 /// [`true`]: ../../std/primitive.bool.html
237 /// [`false`]: ../../std/primitive.bool.html
238 /// [IP address]: ../../std/net/enum.IpAddr.html
239 /// [IPv6 address]: ../../std/net/enum.IpAddr.html#variant.V6
244 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
247 /// let socket = SocketAddr::new(
248 /// IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
249 /// assert_eq!(socket.is_ipv4(), false);
250 /// assert_eq!(socket.is_ipv6(), true);
253 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
254 pub fn is_ipv6(&self) -> bool
{
256 SocketAddr
::V4(_
) => false,
257 SocketAddr
::V6(_
) => true,
263 /// Creates a new socket address from an [IPv4 address] and a port number.
265 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
270 /// use std::net::{SocketAddrV4, Ipv4Addr};
272 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn new(ip
: Ipv4Addr
, port
: u16) -> SocketAddrV4
{
277 inner
: c
::sockaddr_in
{
278 sin_family
: c
::AF_INET
as c
::sa_family_t
,
279 sin_port
: hton(port
),
280 sin_addr
: *ip
.as_inner(),
281 .. unsafe { mem::zeroed() }
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));
296 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn ip(&self) -> &Ipv4Addr
{
299 &*(&self.inner
.sin_addr
as *const c
::in_addr
as *const 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
) {
316 self.inner
.sin_addr
= *new_ip
.as_inner()
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);
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn port(&self) -> u16 {
331 ntoh(self.inner
.sin_port
)
334 /// Changes the port number associated with this socket address.
339 /// use std::net::{SocketAddrV4, Ipv4Addr};
341 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
342 /// socket.set_port(4242);
343 /// assert_eq!(socket.port(), 4242);
345 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
346 pub fn set_port(&mut self, new_port
: u16) {
347 self.inner
.sin_port
= hton(new_port
);
352 /// Creates a new socket address from an [IPv6 address], a 16-bit port number,
353 /// and the `flowinfo` and `scope_id` fields.
355 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
356 /// parameters, see [IETF RFC 2553, Section 3.3].
358 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
359 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
364 /// use std::net::{SocketAddrV6, Ipv6Addr};
366 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
368 #[stable(feature = "rust1", since = "1.0.0")]
369 pub fn new(ip
: Ipv6Addr
, port
: u16, flowinfo
: u32, scope_id
: u32)
372 inner
: c
::sockaddr_in6
{
373 sin6_family
: c
::AF_INET6
as c
::sa_family_t
,
374 sin6_port
: hton(port
),
375 sin6_addr
: *ip
.as_inner(),
376 sin6_flowinfo
: flowinfo
,
377 sin6_scope_id
: scope_id
,
378 .. unsafe { mem::zeroed() }
383 /// Returns the IP address associated with this socket address.
388 /// use std::net::{SocketAddrV6, Ipv6Addr};
390 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
391 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn ip(&self) -> &Ipv6Addr
{
396 &*(&self.inner
.sin6_addr
as *const c
::in6_addr
as *const Ipv6Addr
)
400 /// Changes the IP address associated with this socket address.
405 /// use std::net::{SocketAddrV6, Ipv6Addr};
407 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
408 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
409 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
411 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
412 pub fn set_ip(&mut self, new_ip
: Ipv6Addr
) {
413 self.inner
.sin6_addr
= *new_ip
.as_inner()
416 /// Returns the port number associated with this socket address.
421 /// use std::net::{SocketAddrV6, Ipv6Addr};
423 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
424 /// assert_eq!(socket.port(), 8080);
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn port(&self) -> u16 {
428 ntoh(self.inner
.sin6_port
)
431 /// Changes the port number associated with this socket address.
436 /// use std::net::{SocketAddrV6, Ipv6Addr};
438 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
439 /// socket.set_port(4242);
440 /// assert_eq!(socket.port(), 4242);
442 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
443 pub fn set_port(&mut self, new_port
: u16) {
444 self.inner
.sin6_port
= hton(new_port
);
447 /// Returns the flow information associated with this address.
449 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
450 /// as specified in [IETF RFC 2553, Section 3.3].
451 /// It combines information about the flow label and the traffic class as specified
452 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
454 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
455 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
456 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
457 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
462 /// use std::net::{SocketAddrV6, Ipv6Addr};
464 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
465 /// assert_eq!(socket.flowinfo(), 10);
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub fn flowinfo(&self) -> u32 {
469 self.inner
.sin6_flowinfo
472 /// Changes the flow information associated with this socket address.
474 /// See the [`flowinfo`] method's documentation for more details.
476 /// [`flowinfo`]: #method.flowinfo
481 /// use std::net::{SocketAddrV6, Ipv6Addr};
483 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
484 /// socket.set_flowinfo(56);
485 /// assert_eq!(socket.flowinfo(), 56);
487 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
488 pub fn set_flowinfo(&mut self, new_flowinfo
: u32) {
489 self.inner
.sin6_flowinfo
= new_flowinfo
;
492 /// Returns the scope ID associated with this address.
494 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
495 /// as specified in [IETF RFC 2553, Section 3.3].
497 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
502 /// use std::net::{SocketAddrV6, Ipv6Addr};
504 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
505 /// assert_eq!(socket.scope_id(), 78);
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn scope_id(&self) -> u32 {
509 self.inner
.sin6_scope_id
512 /// Change the scope ID associated with this socket address.
514 /// See the [`scope_id`] method's documentation for more details.
516 /// [`scope_id`]: #method.scope_id
521 /// use std::net::{SocketAddrV6, Ipv6Addr};
523 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
524 /// socket.set_scope_id(42);
525 /// assert_eq!(socket.scope_id(), 42);
527 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
528 pub fn set_scope_id(&mut self, new_scope_id
: u32) {
529 self.inner
.sin6_scope_id
= new_scope_id
;
533 impl FromInner
<c
::sockaddr_in
> for SocketAddrV4
{
534 fn from_inner(addr
: c
::sockaddr_in
) -> SocketAddrV4
{
535 SocketAddrV4 { inner: addr }
539 impl FromInner
<c
::sockaddr_in6
> for SocketAddrV6
{
540 fn from_inner(addr
: c
::sockaddr_in6
) -> SocketAddrV6
{
541 SocketAddrV6 { inner: addr }
545 #[stable(feature = "ip_from_ip", since = "1.16.0")]
546 impl From
<SocketAddrV4
> for SocketAddr
{
547 fn from(sock4
: SocketAddrV4
) -> SocketAddr
{
548 SocketAddr
::V4(sock4
)
552 #[stable(feature = "ip_from_ip", since = "1.16.0")]
553 impl From
<SocketAddrV6
> for SocketAddr
{
554 fn from(sock6
: SocketAddrV6
) -> SocketAddr
{
555 SocketAddr
::V6(sock6
)
559 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
560 impl<I
: Into
<IpAddr
>> From
<(I
, u16)> for SocketAddr
{
561 fn from(pieces
: (I
, u16)) -> SocketAddr
{
562 SocketAddr
::new(pieces
.0.into
(), pieces
.1)
566 impl<'a
> IntoInner
<(*const c
::sockaddr
, c
::socklen_t
)> for &'a SocketAddr
{
567 fn into_inner(self) -> (*const c
::sockaddr
, c
::socklen_t
) {
569 SocketAddr
::V4(ref a
) => {
570 (a
as *const _
as *const _
, mem
::size_of_val(a
) as c
::socklen_t
)
572 SocketAddr
::V6(ref a
) => {
573 (a
as *const _
as *const _
, mem
::size_of_val(a
) as c
::socklen_t
)
579 #[stable(feature = "rust1", since = "1.0.0")]
580 impl fmt
::Display
for SocketAddr
{
581 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
583 SocketAddr
::V4(ref a
) => a
.fmt(f
),
584 SocketAddr
::V6(ref a
) => a
.fmt(f
),
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl fmt
::Display
for SocketAddrV4
{
591 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
592 write
!(f
, "{}:{}", self.ip(), self.port())
596 #[stable(feature = "rust1", since = "1.0.0")]
597 impl fmt
::Debug
for SocketAddrV4
{
598 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
599 fmt
::Display
::fmt(self, fmt
)
603 #[stable(feature = "rust1", since = "1.0.0")]
604 impl fmt
::Display
for SocketAddrV6
{
605 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
606 write
!(f
, "[{}]:{}", self.ip(), self.port())
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl fmt
::Debug
for SocketAddrV6
{
612 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
613 fmt
::Display
::fmt(self, fmt
)
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl Clone
for SocketAddrV4
{
619 fn clone(&self) -> SocketAddrV4 { *self }
621 #[stable(feature = "rust1", since = "1.0.0")]
622 impl Clone
for SocketAddrV6
{
623 fn clone(&self) -> SocketAddrV6 { *self }
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl PartialEq
for SocketAddrV4
{
628 fn eq(&self, other
: &SocketAddrV4
) -> bool
{
629 self.inner
.sin_port
== other
.inner
.sin_port
&&
630 self.inner
.sin_addr
.s_addr
== other
.inner
.sin_addr
.s_addr
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl PartialEq
for SocketAddrV6
{
635 fn eq(&self, other
: &SocketAddrV6
) -> bool
{
636 self.inner
.sin6_port
== other
.inner
.sin6_port
&&
637 self.inner
.sin6_addr
.s6_addr
== other
.inner
.sin6_addr
.s6_addr
&&
638 self.inner
.sin6_flowinfo
== other
.inner
.sin6_flowinfo
&&
639 self.inner
.sin6_scope_id
== other
.inner
.sin6_scope_id
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl Eq
for SocketAddrV4 {}
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl Eq
for SocketAddrV6 {}
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl hash
::Hash
for SocketAddrV4
{
649 fn hash
<H
: hash
::Hasher
>(&self, s
: &mut H
) {
650 (self.inner
.sin_port
, self.inner
.sin_addr
.s_addr
).hash(s
)
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl hash
::Hash
for SocketAddrV6
{
655 fn hash
<H
: hash
::Hasher
>(&self, s
: &mut H
) {
656 (self.inner
.sin6_port
, &self.inner
.sin6_addr
.s6_addr
,
657 self.inner
.sin6_flowinfo
, self.inner
.sin6_scope_id
).hash(s
)
661 /// A trait for objects which can be converted or resolved to one or more
662 /// [`SocketAddr`] values.
664 /// This trait is used for generic address resolution when constructing network
665 /// objects. By default it is implemented for the following types:
667 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
669 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
670 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
671 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
673 /// * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
674 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
677 /// * [`&str`]: the string should be either a string representation of a
678 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
679 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
681 /// This trait allows constructing network objects like [`TcpStream`] or
682 /// [`UdpSocket`] easily with values of various types for the bind/connection
683 /// address. It is needed because sometimes one type is more appropriate than
684 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
685 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
686 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
687 /// some other type (e.g. a string) just for it to be converted back to
688 /// [`SocketAddr`] in constructor methods is pointless.
690 /// Addresses returned by the operating system that are not IP addresses are
691 /// silently ignored.
693 /// [`FromStr`]: ../../std/str/trait.FromStr.html
694 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
695 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
696 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
697 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
698 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
699 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
700 /// [`&str`]: ../../std/primitive.str.html
701 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
702 /// [`to_socket_addrs`]: #tymethod.to_socket_addrs
703 /// [`UdpSocket`]: ../../std/net/struct.UdpSocket.html
704 /// [`u16`]: ../../std/primitive.u16.html
708 /// Creating a [`SocketAddr`] iterator that yields one item:
711 /// use std::net::{ToSocketAddrs, SocketAddr};
713 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
714 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
716 /// assert_eq!(Some(addr), addrs_iter.next());
717 /// assert!(addrs_iter.next().is_none());
720 /// Creating a [`SocketAddr`] iterator from a hostname:
723 /// use std::net::{SocketAddr, ToSocketAddrs};
725 /// // assuming 'localhost' resolves to 127.0.0.1
726 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
727 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
728 /// assert!(addrs_iter.next().is_none());
730 /// // assuming 'foo' does not resolve
731 /// assert!("foo:443".to_socket_addrs().is_err());
734 /// Creating a [`SocketAddr`] iterator that yields multiple items:
737 /// use std::net::{SocketAddr, ToSocketAddrs};
739 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
740 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
741 /// let addrs = vec![addr1, addr2];
743 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
745 /// assert_eq!(Some(addr1), addrs_iter.next());
746 /// assert_eq!(Some(addr2), addrs_iter.next());
747 /// assert!(addrs_iter.next().is_none());
750 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
751 /// socket address `&str` (missing the port):
755 /// use std::net::ToSocketAddrs;
757 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
758 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
761 /// [`TcpStream::connect`] is an example of an function that utilizes
762 /// `ToSocketsAddr` as a trait bound on its parameter in order to accept
766 /// use std::net::{TcpStream, Ipv4Addr};
768 /// let stream = TcpStream::connect(("127.0.0.1", 443));
770 /// let stream = TcpStream::connect("127.0.0.1:443");
772 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
775 /// [`TcpStream::connect`]: ../../std/net/struct.TcpStream.html#method.connect
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub trait ToSocketAddrs
{
778 /// Returned iterator over socket addresses which this type may correspond
780 #[stable(feature = "rust1", since = "1.0.0")]
781 type Iter
: Iterator
<Item
=SocketAddr
>;
783 /// Converts this object to an iterator of resolved `SocketAddr`s.
785 /// The returned iterator may not actually yield any values depending on the
786 /// outcome of any resolution performed.
788 /// Note that this function may block the current thread while resolution is
790 #[stable(feature = "rust1", since = "1.0.0")]
791 fn to_socket_addrs(&self) -> io
::Result
<Self::Iter
>;
794 #[stable(feature = "rust1", since = "1.0.0")]
795 impl ToSocketAddrs
for SocketAddr
{
796 type Iter
= option
::IntoIter
<SocketAddr
>;
797 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
798 Ok(Some(*self).into_iter())
802 #[stable(feature = "rust1", since = "1.0.0")]
803 impl ToSocketAddrs
for SocketAddrV4
{
804 type Iter
= option
::IntoIter
<SocketAddr
>;
805 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
806 SocketAddr
::V4(*self).to_socket_addrs()
810 #[stable(feature = "rust1", since = "1.0.0")]
811 impl ToSocketAddrs
for SocketAddrV6
{
812 type Iter
= option
::IntoIter
<SocketAddr
>;
813 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
814 SocketAddr
::V6(*self).to_socket_addrs()
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl ToSocketAddrs
for (IpAddr
, u16) {
820 type Iter
= option
::IntoIter
<SocketAddr
>;
821 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
822 let (ip
, port
) = *self;
824 IpAddr
::V4(ref a
) => (*a
, port
).to_socket_addrs(),
825 IpAddr
::V6(ref a
) => (*a
, port
).to_socket_addrs(),
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl ToSocketAddrs
for (Ipv4Addr
, u16) {
832 type Iter
= option
::IntoIter
<SocketAddr
>;
833 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
834 let (ip
, port
) = *self;
835 SocketAddrV4
::new(ip
, port
).to_socket_addrs()
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl ToSocketAddrs
for (Ipv6Addr
, u16) {
841 type Iter
= option
::IntoIter
<SocketAddr
>;
842 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
843 let (ip
, port
) = *self;
844 SocketAddrV6
::new(ip
, port
, 0, 0).to_socket_addrs()
848 fn resolve_socket_addr(s
: &str, p
: u16) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
849 let ips
= lookup_host(s
)?
;
850 let v
: Vec
<_
> = ips
.map(|mut a
| { a.set_port(p); a }
).collect();
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl<'a
> ToSocketAddrs
for (&'a
str, u16) {
856 type Iter
= vec
::IntoIter
<SocketAddr
>;
857 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
858 let (host
, port
) = *self;
860 // try to parse the host as a regular IP address first
861 if let Ok(addr
) = host
.parse
::<Ipv4Addr
>() {
862 let addr
= SocketAddrV4
::new(addr
, port
);
863 return Ok(vec
![SocketAddr
::V4(addr
)].into_iter())
865 if let Ok(addr
) = host
.parse
::<Ipv6Addr
>() {
866 let addr
= SocketAddrV6
::new(addr
, port
, 0, 0);
867 return Ok(vec
![SocketAddr
::V6(addr
)].into_iter())
870 resolve_socket_addr(host
, port
)
874 // accepts strings like 'localhost:12345'
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl ToSocketAddrs
for str {
877 type Iter
= vec
::IntoIter
<SocketAddr
>;
878 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
879 // try to parse as a regular SocketAddr first
880 if let Some(addr
) = self.parse().ok() {
881 return Ok(vec
![addr
].into_iter());
884 macro_rules
! try_opt
{
885 ($e
:expr
, $msg
:expr
) => (
888 None
=> return Err(io
::Error
::new(io
::ErrorKind
::InvalidInput
,
894 // split the string by ':' and convert the second part to u16
895 let mut parts_iter
= self.rsplitn(2, '
:'
);
896 let port_str
= try_opt
!(parts_iter
.next(), "invalid socket address");
897 let host
= try_opt
!(parts_iter
.next(), "invalid socket address");
898 let port
: u16 = try_opt
!(port_str
.parse().ok(), "invalid port value");
899 resolve_socket_addr(host
, port
)
903 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
904 impl<'a
> ToSocketAddrs
for &'a
[SocketAddr
] {
905 type Iter
= iter
::Cloned
<slice
::Iter
<'a
, SocketAddr
>>;
907 fn to_socket_addrs(&self) -> io
::Result
<Self::Iter
> {
908 Ok(self.iter().cloned())
912 #[stable(feature = "rust1", since = "1.0.0")]
913 impl<'a
, T
: ToSocketAddrs
+ ?Sized
> ToSocketAddrs
for &'a T
{
915 fn to_socket_addrs(&self) -> io
::Result
<T
::Iter
> {
916 (**self).to_socket_addrs()
920 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
921 impl ToSocketAddrs
for String
{
922 type Iter
= vec
::IntoIter
<SocketAddr
>;
923 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
924 (&**self).to_socket_addrs()
928 #[cfg(all(test, not(target_os = "emscripten")))]
931 use net
::test
::{tsa, sa6, sa4}
;
934 fn to_socket_addr_ipaddr_u16() {
935 let a
= Ipv4Addr
::new(77, 88, 21, 11);
937 let e
= SocketAddr
::V4(SocketAddrV4
::new(a
, p
));
938 assert_eq
!(Ok(vec
![e
]), tsa((a
, p
)));
942 fn to_socket_addr_str_u16() {
943 let a
= sa4(Ipv4Addr
::new(77, 88, 21, 11), 24352);
944 assert_eq
!(Ok(vec
![a
]), tsa(("77.88.21.11", 24352)));
946 let a
= sa6(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
947 assert_eq
!(Ok(vec
![a
]), tsa(("2a02:6b8:0:1::1", 53)));
949 let a
= sa4(Ipv4Addr
::new(127, 0, 0, 1), 23924);
950 assert
!(tsa(("localhost", 23924)).unwrap().contains(&a
));
954 fn to_socket_addr_str() {
955 let a
= sa4(Ipv4Addr
::new(77, 88, 21, 11), 24352);
956 assert_eq
!(Ok(vec
![a
]), tsa("77.88.21.11:24352"));
958 let a
= sa6(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
959 assert_eq
!(Ok(vec
![a
]), tsa("[2a02:6b8:0:1::1]:53"));
961 let a
= sa4(Ipv4Addr
::new(127, 0, 0, 1), 23924);
962 assert
!(tsa("localhost:23924").unwrap().contains(&a
));
966 fn to_socket_addr_string() {
967 let a
= sa4(Ipv4Addr
::new(77, 88, 21, 11), 24352);
968 assert_eq
!(Ok(vec
![a
]), tsa(&*format
!("{}:{}", "77.88.21.11", "24352")));
969 assert_eq
!(Ok(vec
![a
]), tsa(&format
!("{}:{}", "77.88.21.11", "24352")));
970 assert_eq
!(Ok(vec
![a
]), tsa(format
!("{}:{}", "77.88.21.11", "24352")));
972 let s
= format
!("{}:{}", "77.88.21.11", "24352");
973 assert_eq
!(Ok(vec
![a
]), tsa(s
));
974 // s has been moved into the tsa call
977 // FIXME: figure out why this fails on openbsd and bitrig and fix it
979 #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
980 fn to_socket_addr_str_bad() {
981 assert
!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
986 fn ip4(low
: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
987 fn ip6(low
: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
989 let mut v4
= SocketAddrV4
::new(ip4(11), 80);
990 assert_eq
!(v4
.ip(), &ip4(11));
992 assert_eq
!(v4
.ip(), &ip4(12));
994 let mut addr
= SocketAddr
::V4(v4
);
995 assert_eq
!(addr
.ip(), IpAddr
::V4(ip4(12)));
996 addr
.set_ip(IpAddr
::V4(ip4(13)));
997 assert_eq
!(addr
.ip(), IpAddr
::V4(ip4(13)));
998 addr
.set_ip(IpAddr
::V6(ip6(14)));
999 assert_eq
!(addr
.ip(), IpAddr
::V6(ip6(14)));
1001 let mut v6
= SocketAddrV6
::new(ip6(1), 80, 0, 0);
1002 assert_eq
!(v6
.ip(), &ip6(1));
1004 assert_eq
!(v6
.ip(), &ip6(2));
1006 let mut addr
= SocketAddr
::V6(v6
);
1007 assert_eq
!(addr
.ip(), IpAddr
::V6(ip6(2)));
1008 addr
.set_ip(IpAddr
::V6(ip6(3)));
1009 assert_eq
!(addr
.ip(), IpAddr
::V6(ip6(3)));
1010 addr
.set_ip(IpAddr
::V4(ip4(4)));
1011 assert_eq
!(addr
.ip(), IpAddr
::V4(ip4(4)));
1016 let mut v4
= SocketAddrV4
::new(Ipv4Addr
::new(77, 88, 21, 11), 80);
1017 assert_eq
!(v4
.port(), 80);
1019 assert_eq
!(v4
.port(), 443);
1021 let mut addr
= SocketAddr
::V4(v4
);
1022 assert_eq
!(addr
.port(), 443);
1023 addr
.set_port(8080);
1024 assert_eq
!(addr
.port(), 8080);
1026 let mut v6
= SocketAddrV6
::new(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1027 assert_eq
!(v6
.port(), 80);
1029 assert_eq
!(v6
.port(), 443);
1031 let mut addr
= SocketAddr
::V6(v6
);
1032 assert_eq
!(addr
.port(), 443);
1033 addr
.set_port(8080);
1034 assert_eq
!(addr
.port(), 8080);
1039 let mut v6
= SocketAddrV6
::new(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1040 assert_eq
!(v6
.flowinfo(), 10);
1041 v6
.set_flowinfo(20);
1042 assert_eq
!(v6
.flowinfo(), 20);
1047 let mut v6
= SocketAddrV6
::new(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1048 assert_eq
!(v6
.scope_id(), 10);
1049 v6
.set_scope_id(20);
1050 assert_eq
!(v6
.scope_id(), 20);
1055 let v4
= SocketAddr
::V4(SocketAddrV4
::new(Ipv4Addr
::new(77, 88, 21, 11), 80));
1056 assert
!(v4
.is_ipv4());
1057 assert
!(!v4
.is_ipv6());
1062 let v6
= SocketAddr
::V6(SocketAddrV6
::new(
1063 Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
1064 assert
!(!v6
.is_ipv4());
1065 assert
!(v6
.is_ipv6());