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
::{ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr}
;
17 use sys
::net
::netc
as c
;
18 use sys_common
::{FromInner, AsInner, IntoInner}
;
19 use sys_common
::net
::lookup_host
;
24 /// An internet socket address, either IPv4 or IPv6.
26 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
27 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
28 /// [`SocketAddrV6`]'s respective documentation for more details.
30 /// The size of a `SocketAddr` instance may vary depending on the target operating
33 /// [IP address]: ../../std/net/enum.IpAddr.html
34 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
35 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
40 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
42 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
44 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
45 /// assert_eq!(socket.port(), 8080);
46 /// assert_eq!(socket.is_ipv4(), true);
48 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
49 #[stable(feature = "rust1", since = "1.0.0")]
51 /// An IPv4 socket address.
52 #[stable(feature = "rust1", since = "1.0.0")]
53 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
54 /// An IPv6 socket address.
55 #[stable(feature = "rust1", since = "1.0.0")]
56 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
59 /// An IPv4 socket address.
61 /// IPv4 socket addresses consist of an [IPv4 address] and a 16-bit port number, as
62 /// stated in [IETF RFC 793].
64 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
66 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
69 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
70 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
71 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
76 /// use std::net::{Ipv4Addr, SocketAddrV4};
78 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
80 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
81 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
82 /// assert_eq!(socket.port(), 8080);
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct SocketAddrV4 { inner: c::sockaddr_in }
88 /// An IPv6 socket address.
90 /// IPv6 socket addresses consist of an [Ipv6 address], a 16-bit port number, as well
91 /// as fields containing the traffic class, the flow label, and a scope identifier
92 /// (see [IETF RFC 2553, Section 3.3] for more details).
94 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
96 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
99 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
100 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
101 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
106 /// use std::net::{Ipv6Addr, SocketAddrV6};
108 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
110 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
111 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
112 /// assert_eq!(socket.port(), 8080);
115 #[stable(feature = "rust1", since = "1.0.0")]
116 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
119 /// Creates a new socket address from an [IP address] and a port number.
121 /// [IP address]: ../../std/net/enum.IpAddr.html
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")]
133 pub fn new(ip
: IpAddr
, port
: u16) -> SocketAddr
{
135 IpAddr
::V4(a
) => SocketAddr
::V4(SocketAddrV4
::new(a
, port
)),
136 IpAddr
::V6(a
) => SocketAddr
::V6(SocketAddrV6
::new(a
, port
, 0, 0)),
140 /// Returns the IP address associated with this socket address.
145 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
147 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
148 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
150 #[stable(feature = "ip_addr", since = "1.7.0")]
151 pub fn ip(&self) -> IpAddr
{
153 SocketAddr
::V4(ref a
) => IpAddr
::V4(*a
.ip()),
154 SocketAddr
::V6(ref a
) => IpAddr
::V6(*a
.ip()),
158 /// Changes the IP address associated with this socket address.
163 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
165 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
166 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
167 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
169 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
170 pub fn set_ip(&mut self, new_ip
: IpAddr
) {
171 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
172 match (self, new_ip
) {
173 (&mut SocketAddr
::V4(ref mut a
), IpAddr
::V4(new_ip
)) => a
.set_ip(new_ip
),
174 (&mut SocketAddr
::V6(ref mut a
), IpAddr
::V6(new_ip
)) => a
.set_ip(new_ip
),
175 (self_
, new_ip
) => *self_
= Self::new(new_ip
, self_
.port()),
179 /// Returns the port number associated with this socket address.
184 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
186 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
187 /// assert_eq!(socket.port(), 8080);
189 #[stable(feature = "rust1", since = "1.0.0")]
190 pub fn port(&self) -> u16 {
192 SocketAddr
::V4(ref a
) => a
.port(),
193 SocketAddr
::V6(ref a
) => a
.port(),
197 /// Changes the port number associated with this socket address.
202 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
204 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
205 /// socket.set_port(1025);
206 /// assert_eq!(socket.port(), 1025);
208 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
209 pub fn set_port(&mut self, new_port
: u16) {
211 SocketAddr
::V4(ref mut a
) => a
.set_port(new_port
),
212 SocketAddr
::V6(ref mut a
) => a
.set_port(new_port
),
216 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
217 /// [IPv4 address], and [`false`] otherwise.
219 /// [`true`]: ../../std/primitive.bool.html
220 /// [`false`]: ../../std/primitive.bool.html
221 /// [IP address]: ../../std/net/enum.IpAddr.html
222 /// [IPv4 address]: ../../std/net/enum.IpAddr.html#variant.V4
227 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
230 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
231 /// assert_eq!(socket.is_ipv4(), true);
232 /// assert_eq!(socket.is_ipv6(), false);
235 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
236 pub fn is_ipv4(&self) -> bool
{
238 SocketAddr
::V4(_
) => true,
239 SocketAddr
::V6(_
) => false,
243 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
244 /// [IPv6 address], and [`false`] otherwise.
246 /// [`true`]: ../../std/primitive.bool.html
247 /// [`false`]: ../../std/primitive.bool.html
248 /// [IP address]: ../../std/net/enum.IpAddr.html
249 /// [IPv6 address]: ../../std/net/enum.IpAddr.html#variant.V6
254 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
257 /// let socket = SocketAddr::new(
258 /// IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
259 /// assert_eq!(socket.is_ipv4(), false);
260 /// assert_eq!(socket.is_ipv6(), true);
263 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
264 pub fn is_ipv6(&self) -> bool
{
266 SocketAddr
::V4(_
) => false,
267 SocketAddr
::V6(_
) => true,
273 /// Creates a new socket address from an [IPv4 address] and a port number.
275 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
280 /// use std::net::{SocketAddrV4, Ipv4Addr};
282 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn new(ip
: Ipv4Addr
, port
: u16) -> SocketAddrV4
{
287 inner
: c
::sockaddr_in
{
288 sin_family
: c
::AF_INET
as c
::sa_family_t
,
289 sin_port
: hton(port
),
290 sin_addr
: *ip
.as_inner(),
291 .. unsafe { mem::zeroed() }
296 /// Returns the IP address associated with this socket address.
301 /// use std::net::{SocketAddrV4, Ipv4Addr};
303 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
304 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub fn ip(&self) -> &Ipv4Addr
{
309 &*(&self.inner
.sin_addr
as *const c
::in_addr
as *const Ipv4Addr
)
313 /// Changes the IP address associated with this socket address.
318 /// use std::net::{SocketAddrV4, Ipv4Addr};
320 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
321 /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
322 /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
324 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
325 pub fn set_ip(&mut self, new_ip
: Ipv4Addr
) {
326 self.inner
.sin_addr
= *new_ip
.as_inner()
329 /// Returns the port number associated with this socket address.
334 /// use std::net::{SocketAddrV4, Ipv4Addr};
336 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
337 /// assert_eq!(socket.port(), 8080);
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub fn port(&self) -> u16 {
341 ntoh(self.inner
.sin_port
)
344 /// Changes the port number associated with this socket address.
349 /// use std::net::{SocketAddrV4, Ipv4Addr};
351 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
352 /// socket.set_port(4242);
353 /// assert_eq!(socket.port(), 4242);
355 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
356 pub fn set_port(&mut self, new_port
: u16) {
357 self.inner
.sin_port
= hton(new_port
);
362 /// Creates a new socket address from an [IPv6 address], a 16-bit port number,
363 /// and the `flowinfo` and `scope_id` fields.
365 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
366 /// parameters, see [IETF RFC 2553, Section 3.3].
368 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
369 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
374 /// use std::net::{SocketAddrV6, Ipv6Addr};
376 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub fn new(ip
: Ipv6Addr
, port
: u16, flowinfo
: u32, scope_id
: u32)
382 inner
: c
::sockaddr_in6
{
383 sin6_family
: c
::AF_INET6
as c
::sa_family_t
,
384 sin6_port
: hton(port
),
385 sin6_addr
: *ip
.as_inner(),
386 sin6_flowinfo
: flowinfo
,
387 sin6_scope_id
: scope_id
,
388 .. unsafe { mem::zeroed() }
393 /// Returns the IP address associated with this socket address.
398 /// use std::net::{SocketAddrV6, Ipv6Addr};
400 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
401 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
403 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn ip(&self) -> &Ipv6Addr
{
406 &*(&self.inner
.sin6_addr
as *const c
::in6_addr
as *const Ipv6Addr
)
410 /// Changes the IP address associated with this socket address.
415 /// use std::net::{SocketAddrV6, Ipv6Addr};
417 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
418 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
419 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
421 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
422 pub fn set_ip(&mut self, new_ip
: Ipv6Addr
) {
423 self.inner
.sin6_addr
= *new_ip
.as_inner()
426 /// Returns the port number associated with this socket address.
431 /// use std::net::{SocketAddrV6, Ipv6Addr};
433 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
434 /// assert_eq!(socket.port(), 8080);
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub fn port(&self) -> u16 {
438 ntoh(self.inner
.sin6_port
)
441 /// Changes the port number associated with this socket address.
446 /// use std::net::{SocketAddrV6, Ipv6Addr};
448 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
449 /// socket.set_port(4242);
450 /// assert_eq!(socket.port(), 4242);
452 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
453 pub fn set_port(&mut self, new_port
: u16) {
454 self.inner
.sin6_port
= hton(new_port
);
457 /// Returns the flow information associated with this address.
459 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
460 /// as specified in [IETF RFC 2553, Section 3.3].
461 /// It combines information about the flow label and the traffic class as specified
462 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
464 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
465 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
466 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
467 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
472 /// use std::net::{SocketAddrV6, Ipv6Addr};
474 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
475 /// assert_eq!(socket.flowinfo(), 10);
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn flowinfo(&self) -> u32 {
479 self.inner
.sin6_flowinfo
482 /// Changes the flow information associated with this socket address.
484 /// See the [`flowinfo`] method's documentation for more details.
486 /// [`flowinfo`]: #method.flowinfo
491 /// use std::net::{SocketAddrV6, Ipv6Addr};
493 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
494 /// socket.set_flowinfo(56);
495 /// assert_eq!(socket.flowinfo(), 56);
497 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
498 pub fn set_flowinfo(&mut self, new_flowinfo
: u32) {
499 self.inner
.sin6_flowinfo
= new_flowinfo
;
502 /// Returns the scope ID associated with this address.
504 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
505 /// as specified in [IETF RFC 2553, Section 3.3].
507 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
512 /// use std::net::{SocketAddrV6, Ipv6Addr};
514 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
515 /// assert_eq!(socket.scope_id(), 78);
517 #[stable(feature = "rust1", since = "1.0.0")]
518 pub fn scope_id(&self) -> u32 {
519 self.inner
.sin6_scope_id
522 /// Change the scope ID associated with this socket address.
524 /// See the [`scope_id`] method's documentation for more details.
526 /// [`scope_id`]: #method.scope_id
531 /// use std::net::{SocketAddrV6, Ipv6Addr};
533 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
534 /// socket.set_scope_id(42);
535 /// assert_eq!(socket.scope_id(), 42);
537 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
538 pub fn set_scope_id(&mut self, new_scope_id
: u32) {
539 self.inner
.sin6_scope_id
= new_scope_id
;
543 impl FromInner
<c
::sockaddr_in
> for SocketAddrV4
{
544 fn from_inner(addr
: c
::sockaddr_in
) -> SocketAddrV4
{
545 SocketAddrV4 { inner: addr }
549 impl FromInner
<c
::sockaddr_in6
> for SocketAddrV6
{
550 fn from_inner(addr
: c
::sockaddr_in6
) -> SocketAddrV6
{
551 SocketAddrV6 { inner: addr }
555 #[stable(feature = "ip_from_ip", since = "1.16.0")]
556 impl From
<SocketAddrV4
> for SocketAddr
{
557 /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
558 fn from(sock4
: SocketAddrV4
) -> SocketAddr
{
559 SocketAddr
::V4(sock4
)
563 #[stable(feature = "ip_from_ip", since = "1.16.0")]
564 impl From
<SocketAddrV6
> for SocketAddr
{
565 /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
566 fn from(sock6
: SocketAddrV6
) -> SocketAddr
{
567 SocketAddr
::V6(sock6
)
571 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
572 impl<I
: Into
<IpAddr
>> From
<(I
, u16)> for SocketAddr
{
573 /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
575 /// This conversion creates a [`SocketAddr::V4`] for a [`IpAddr::V4`]
576 /// and creates a [`SocketAddr::V6`] for a [`IpAddr::V6`].
578 /// `u16` is treated as port of the newly created [`SocketAddr`].
579 fn from(pieces
: (I
, u16)) -> SocketAddr
{
580 SocketAddr
::new(pieces
.0.into
(), pieces
.1)
584 impl<'a
> IntoInner
<(*const c
::sockaddr
, c
::socklen_t
)> for &'a SocketAddr
{
585 fn into_inner(self) -> (*const c
::sockaddr
, c
::socklen_t
) {
587 SocketAddr
::V4(ref a
) => {
588 (a
as *const _
as *const _
, mem
::size_of_val(a
) as c
::socklen_t
)
590 SocketAddr
::V6(ref a
) => {
591 (a
as *const _
as *const _
, mem
::size_of_val(a
) as c
::socklen_t
)
597 #[stable(feature = "rust1", since = "1.0.0")]
598 impl fmt
::Display
for SocketAddr
{
599 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
601 SocketAddr
::V4(ref a
) => a
.fmt(f
),
602 SocketAddr
::V6(ref a
) => a
.fmt(f
),
607 #[stable(feature = "rust1", since = "1.0.0")]
608 impl fmt
::Display
for SocketAddrV4
{
609 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
610 write
!(f
, "{}:{}", self.ip(), self.port())
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 write
!(f
, "[{}]:{}", self.ip(), self.port())
628 #[stable(feature = "rust1", since = "1.0.0")]
629 impl fmt
::Debug
for SocketAddrV6
{
630 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
631 fmt
::Display
::fmt(self, fmt
)
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl Clone
for SocketAddrV4
{
637 fn clone(&self) -> SocketAddrV4 { *self }
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl Clone
for SocketAddrV6
{
641 fn clone(&self) -> SocketAddrV6 { *self }
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl PartialEq
for SocketAddrV4
{
646 fn eq(&self, other
: &SocketAddrV4
) -> bool
{
647 self.inner
.sin_port
== other
.inner
.sin_port
&&
648 self.inner
.sin_addr
.s_addr
== other
.inner
.sin_addr
.s_addr
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl PartialEq
for SocketAddrV6
{
653 fn eq(&self, other
: &SocketAddrV6
) -> bool
{
654 self.inner
.sin6_port
== other
.inner
.sin6_port
&&
655 self.inner
.sin6_addr
.s6_addr
== other
.inner
.sin6_addr
.s6_addr
&&
656 self.inner
.sin6_flowinfo
== other
.inner
.sin6_flowinfo
&&
657 self.inner
.sin6_scope_id
== other
.inner
.sin6_scope_id
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl Eq
for SocketAddrV4 {}
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl Eq
for SocketAddrV6 {}
665 #[stable(feature = "rust1", since = "1.0.0")]
666 impl hash
::Hash
for SocketAddrV4
{
667 fn hash
<H
: hash
::Hasher
>(&self, s
: &mut H
) {
668 (self.inner
.sin_port
, self.inner
.sin_addr
.s_addr
).hash(s
)
671 #[stable(feature = "rust1", since = "1.0.0")]
672 impl hash
::Hash
for SocketAddrV6
{
673 fn hash
<H
: hash
::Hasher
>(&self, s
: &mut H
) {
674 (self.inner
.sin6_port
, &self.inner
.sin6_addr
.s6_addr
,
675 self.inner
.sin6_flowinfo
, self.inner
.sin6_scope_id
).hash(s
)
679 /// A trait for objects which can be converted or resolved to one or more
680 /// [`SocketAddr`] values.
682 /// This trait is used for generic address resolution when constructing network
683 /// objects. By default it is implemented for the following types:
685 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
687 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
688 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
689 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
691 /// * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
692 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
695 /// * [`&str`]: the string should be either a string representation of a
696 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
697 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
699 /// This trait allows constructing network objects like [`TcpStream`] or
700 /// [`UdpSocket`] easily with values of various types for the bind/connection
701 /// address. It is needed because sometimes one type is more appropriate than
702 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
703 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
704 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
705 /// some other type (e.g. a string) just for it to be converted back to
706 /// [`SocketAddr`] in constructor methods is pointless.
708 /// Addresses returned by the operating system that are not IP addresses are
709 /// silently ignored.
711 /// [`FromStr`]: ../../std/str/trait.FromStr.html
712 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
713 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
714 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
715 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
716 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
717 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
718 /// [`&str`]: ../../std/primitive.str.html
719 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
720 /// [`to_socket_addrs`]: #tymethod.to_socket_addrs
721 /// [`UdpSocket`]: ../../std/net/struct.UdpSocket.html
722 /// [`u16`]: ../../std/primitive.u16.html
726 /// Creating a [`SocketAddr`] iterator that yields one item:
729 /// use std::net::{ToSocketAddrs, SocketAddr};
731 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
732 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
734 /// assert_eq!(Some(addr), addrs_iter.next());
735 /// assert!(addrs_iter.next().is_none());
738 /// Creating a [`SocketAddr`] iterator from a hostname:
741 /// use std::net::{SocketAddr, ToSocketAddrs};
743 /// // assuming 'localhost' resolves to 127.0.0.1
744 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
745 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
746 /// assert!(addrs_iter.next().is_none());
748 /// // assuming 'foo' does not resolve
749 /// assert!("foo:443".to_socket_addrs().is_err());
752 /// Creating a [`SocketAddr`] iterator that yields multiple items:
755 /// use std::net::{SocketAddr, ToSocketAddrs};
757 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
758 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
759 /// let addrs = vec![addr1, addr2];
761 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
763 /// assert_eq!(Some(addr1), addrs_iter.next());
764 /// assert_eq!(Some(addr2), addrs_iter.next());
765 /// assert!(addrs_iter.next().is_none());
768 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
769 /// socket address `&str` (missing the port):
773 /// use std::net::ToSocketAddrs;
775 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
776 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
779 /// [`TcpStream::connect`] is an example of an function that utilizes
780 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
784 /// use std::net::{TcpStream, Ipv4Addr};
786 /// let stream = TcpStream::connect(("127.0.0.1", 443));
788 /// let stream = TcpStream::connect("127.0.0.1:443");
790 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
793 /// [`TcpStream::connect`]: ../../std/net/struct.TcpStream.html#method.connect
794 #[stable(feature = "rust1", since = "1.0.0")]
795 pub trait ToSocketAddrs
{
796 /// Returned iterator over socket addresses which this type may correspond
798 #[stable(feature = "rust1", since = "1.0.0")]
799 type Iter
: Iterator
<Item
=SocketAddr
>;
801 /// Converts this object to an iterator of resolved `SocketAddr`s.
803 /// The returned iterator may not actually yield any values depending on the
804 /// outcome of any resolution performed.
806 /// Note that this function may block the current thread while resolution is
808 #[stable(feature = "rust1", since = "1.0.0")]
809 fn to_socket_addrs(&self) -> io
::Result
<Self::Iter
>;
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl ToSocketAddrs
for SocketAddr
{
814 type Iter
= option
::IntoIter
<SocketAddr
>;
815 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
816 Ok(Some(*self).into_iter())
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl ToSocketAddrs
for SocketAddrV4
{
822 type Iter
= option
::IntoIter
<SocketAddr
>;
823 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
824 SocketAddr
::V4(*self).to_socket_addrs()
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl ToSocketAddrs
for SocketAddrV6
{
830 type Iter
= option
::IntoIter
<SocketAddr
>;
831 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
832 SocketAddr
::V6(*self).to_socket_addrs()
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl ToSocketAddrs
for (IpAddr
, u16) {
838 type Iter
= option
::IntoIter
<SocketAddr
>;
839 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
840 let (ip
, port
) = *self;
842 IpAddr
::V4(ref a
) => (*a
, port
).to_socket_addrs(),
843 IpAddr
::V6(ref a
) => (*a
, port
).to_socket_addrs(),
848 #[stable(feature = "rust1", since = "1.0.0")]
849 impl ToSocketAddrs
for (Ipv4Addr
, u16) {
850 type Iter
= option
::IntoIter
<SocketAddr
>;
851 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
852 let (ip
, port
) = *self;
853 SocketAddrV4
::new(ip
, port
).to_socket_addrs()
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl ToSocketAddrs
for (Ipv6Addr
, u16) {
859 type Iter
= option
::IntoIter
<SocketAddr
>;
860 fn to_socket_addrs(&self) -> io
::Result
<option
::IntoIter
<SocketAddr
>> {
861 let (ip
, port
) = *self;
862 SocketAddrV6
::new(ip
, port
, 0, 0).to_socket_addrs()
866 fn resolve_socket_addr(s
: &str, p
: u16) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
867 let ips
= lookup_host(s
)?
;
868 let v
: Vec
<_
> = ips
.map(|mut a
| { a.set_port(p); a }
).collect();
872 #[stable(feature = "rust1", since = "1.0.0")]
873 impl<'a
> ToSocketAddrs
for (&'a
str, u16) {
874 type Iter
= vec
::IntoIter
<SocketAddr
>;
875 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
876 let (host
, port
) = *self;
878 // try to parse the host as a regular IP address first
879 if let Ok(addr
) = host
.parse
::<Ipv4Addr
>() {
880 let addr
= SocketAddrV4
::new(addr
, port
);
881 return Ok(vec
![SocketAddr
::V4(addr
)].into_iter())
883 if let Ok(addr
) = host
.parse
::<Ipv6Addr
>() {
884 let addr
= SocketAddrV6
::new(addr
, port
, 0, 0);
885 return Ok(vec
![SocketAddr
::V6(addr
)].into_iter())
888 resolve_socket_addr(host
, port
)
892 // accepts strings like 'localhost:12345'
893 #[stable(feature = "rust1", since = "1.0.0")]
894 impl ToSocketAddrs
for str {
895 type Iter
= vec
::IntoIter
<SocketAddr
>;
896 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
897 // try to parse as a regular SocketAddr first
898 if let Some(addr
) = self.parse().ok() {
899 return Ok(vec
![addr
].into_iter());
902 macro_rules
! try_opt
{
903 ($e
:expr
, $msg
:expr
) => (
906 None
=> return Err(io
::Error
::new(io
::ErrorKind
::InvalidInput
,
912 // split the string by ':' and convert the second part to u16
913 let mut parts_iter
= self.rsplitn(2, '
:'
);
914 let port_str
= try_opt
!(parts_iter
.next(), "invalid socket address");
915 let host
= try_opt
!(parts_iter
.next(), "invalid socket address");
916 let port
: u16 = try_opt
!(port_str
.parse().ok(), "invalid port value");
917 resolve_socket_addr(host
, port
)
921 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
922 impl<'a
> ToSocketAddrs
for &'a
[SocketAddr
] {
923 type Iter
= iter
::Cloned
<slice
::Iter
<'a
, SocketAddr
>>;
925 fn to_socket_addrs(&self) -> io
::Result
<Self::Iter
> {
926 Ok(self.iter().cloned())
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl<'a
, T
: ToSocketAddrs
+ ?Sized
> ToSocketAddrs
for &'a T
{
933 fn to_socket_addrs(&self) -> io
::Result
<T
::Iter
> {
934 (**self).to_socket_addrs()
938 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
939 impl ToSocketAddrs
for String
{
940 type Iter
= vec
::IntoIter
<SocketAddr
>;
941 fn to_socket_addrs(&self) -> io
::Result
<vec
::IntoIter
<SocketAddr
>> {
942 (&**self).to_socket_addrs()
946 #[cfg(all(test, not(target_os = "emscripten")))]
949 use net
::test
::{tsa, sa6, sa4}
;
952 fn to_socket_addr_ipaddr_u16() {
953 let a
= Ipv4Addr
::new(77, 88, 21, 11);
955 let e
= SocketAddr
::V4(SocketAddrV4
::new(a
, p
));
956 assert_eq
!(Ok(vec
![e
]), tsa((a
, p
)));
960 fn to_socket_addr_str_u16() {
961 let a
= sa4(Ipv4Addr
::new(77, 88, 21, 11), 24352);
962 assert_eq
!(Ok(vec
![a
]), tsa(("77.88.21.11", 24352)));
964 let a
= sa6(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
965 assert_eq
!(Ok(vec
![a
]), tsa(("2a02:6b8:0:1::1", 53)));
967 let a
= sa4(Ipv4Addr
::new(127, 0, 0, 1), 23924);
968 assert
!(tsa(("localhost", 23924)).unwrap().contains(&a
));
972 fn to_socket_addr_str() {
973 let a
= sa4(Ipv4Addr
::new(77, 88, 21, 11), 24352);
974 assert_eq
!(Ok(vec
![a
]), tsa("77.88.21.11:24352"));
976 let a
= sa6(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
977 assert_eq
!(Ok(vec
![a
]), tsa("[2a02:6b8:0:1::1]:53"));
979 let a
= sa4(Ipv4Addr
::new(127, 0, 0, 1), 23924);
980 assert
!(tsa("localhost:23924").unwrap().contains(&a
));
984 fn to_socket_addr_string() {
985 let a
= sa4(Ipv4Addr
::new(77, 88, 21, 11), 24352);
986 assert_eq
!(Ok(vec
![a
]), tsa(&*format
!("{}:{}", "77.88.21.11", "24352")));
987 assert_eq
!(Ok(vec
![a
]), tsa(&format
!("{}:{}", "77.88.21.11", "24352")));
988 assert_eq
!(Ok(vec
![a
]), tsa(format
!("{}:{}", "77.88.21.11", "24352")));
990 let s
= format
!("{}:{}", "77.88.21.11", "24352");
991 assert_eq
!(Ok(vec
![a
]), tsa(s
));
992 // s has been moved into the tsa call
995 // FIXME: figure out why this fails on openbsd and bitrig and fix it
997 #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
998 fn to_socket_addr_str_bad() {
999 assert
!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
1004 fn ip4(low
: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
1005 fn ip6(low
: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
1007 let mut v4
= SocketAddrV4
::new(ip4(11), 80);
1008 assert_eq
!(v4
.ip(), &ip4(11));
1010 assert_eq
!(v4
.ip(), &ip4(12));
1012 let mut addr
= SocketAddr
::V4(v4
);
1013 assert_eq
!(addr
.ip(), IpAddr
::V4(ip4(12)));
1014 addr
.set_ip(IpAddr
::V4(ip4(13)));
1015 assert_eq
!(addr
.ip(), IpAddr
::V4(ip4(13)));
1016 addr
.set_ip(IpAddr
::V6(ip6(14)));
1017 assert_eq
!(addr
.ip(), IpAddr
::V6(ip6(14)));
1019 let mut v6
= SocketAddrV6
::new(ip6(1), 80, 0, 0);
1020 assert_eq
!(v6
.ip(), &ip6(1));
1022 assert_eq
!(v6
.ip(), &ip6(2));
1024 let mut addr
= SocketAddr
::V6(v6
);
1025 assert_eq
!(addr
.ip(), IpAddr
::V6(ip6(2)));
1026 addr
.set_ip(IpAddr
::V6(ip6(3)));
1027 assert_eq
!(addr
.ip(), IpAddr
::V6(ip6(3)));
1028 addr
.set_ip(IpAddr
::V4(ip4(4)));
1029 assert_eq
!(addr
.ip(), IpAddr
::V4(ip4(4)));
1034 let mut v4
= SocketAddrV4
::new(Ipv4Addr
::new(77, 88, 21, 11), 80);
1035 assert_eq
!(v4
.port(), 80);
1037 assert_eq
!(v4
.port(), 443);
1039 let mut addr
= SocketAddr
::V4(v4
);
1040 assert_eq
!(addr
.port(), 443);
1041 addr
.set_port(8080);
1042 assert_eq
!(addr
.port(), 8080);
1044 let mut v6
= SocketAddrV6
::new(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1045 assert_eq
!(v6
.port(), 80);
1047 assert_eq
!(v6
.port(), 443);
1049 let mut addr
= SocketAddr
::V6(v6
);
1050 assert_eq
!(addr
.port(), 443);
1051 addr
.set_port(8080);
1052 assert_eq
!(addr
.port(), 8080);
1057 let mut v6
= SocketAddrV6
::new(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1058 assert_eq
!(v6
.flowinfo(), 10);
1059 v6
.set_flowinfo(20);
1060 assert_eq
!(v6
.flowinfo(), 20);
1065 let mut v6
= SocketAddrV6
::new(Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1066 assert_eq
!(v6
.scope_id(), 10);
1067 v6
.set_scope_id(20);
1068 assert_eq
!(v6
.scope_id(), 20);
1073 let v4
= SocketAddr
::V4(SocketAddrV4
::new(Ipv4Addr
::new(77, 88, 21, 11), 80));
1074 assert
!(v4
.is_ipv4());
1075 assert
!(!v4
.is_ipv6());
1080 let v6
= SocketAddr
::V6(SocketAddrV6
::new(
1081 Ipv6Addr
::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
1082 assert
!(!v6
.is_ipv4());
1083 assert
!(v6
.is_ipv6());