]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/addr.rs
SGX target: fix std unit tests
[rust.git] / src / libstd / net / addr.rs
1 use crate::fmt;
2 use crate::hash;
3 use crate::io;
4 use crate::mem;
5 use crate::net::{ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
6 use crate::option;
7 use crate::sys::net::netc as c;
8 use crate::sys_common::{FromInner, AsInner, IntoInner};
9 use crate::sys_common::net::LookupHost;
10 use crate::vec;
11 use crate::iter;
12 use crate::slice;
13 use crate::convert::TryInto;
14
15 /// An internet socket address, either IPv4 or IPv6.
16 ///
17 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
18 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
19 /// [`SocketAddrV6`]'s respective documentation for more details.
20 ///
21 /// The size of a `SocketAddr` instance may vary depending on the target operating
22 /// system.
23 ///
24 /// [IP address]: ../../std/net/enum.IpAddr.html
25 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
26 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
27 ///
28 /// # Examples
29 ///
30 /// ```
31 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
32 ///
33 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
34 ///
35 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
36 /// assert_eq!(socket.port(), 8080);
37 /// assert_eq!(socket.is_ipv4(), true);
38 /// ```
39 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
40 #[stable(feature = "rust1", since = "1.0.0")]
41 pub enum SocketAddr {
42     /// An IPv4 socket address.
43     #[stable(feature = "rust1", since = "1.0.0")]
44     V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
45     /// An IPv6 socket address.
46     #[stable(feature = "rust1", since = "1.0.0")]
47     V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
48 }
49
50 /// An IPv4 socket address.
51 ///
52 /// IPv4 socket addresses consist of an [IPv4 address] and a 16-bit port number, as
53 /// stated in [IETF RFC 793].
54 ///
55 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
56 ///
57 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
58 /// system.
59 ///
60 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
61 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
62 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
63 ///
64 /// # Examples
65 ///
66 /// ```
67 /// use std::net::{Ipv4Addr, SocketAddrV4};
68 ///
69 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
70 ///
71 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
72 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
73 /// assert_eq!(socket.port(), 8080);
74 /// ```
75 #[derive(Copy)]
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub struct SocketAddrV4 { inner: c::sockaddr_in }
78
79 /// An IPv6 socket address.
80 ///
81 /// IPv6 socket addresses consist of an [Ipv6 address], a 16-bit port number, as well
82 /// as fields containing the traffic class, the flow label, and a scope identifier
83 /// (see [IETF RFC 2553, Section 3.3] for more details).
84 ///
85 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
86 ///
87 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
88 /// system.
89 ///
90 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
91 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
92 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
93 ///
94 /// # Examples
95 ///
96 /// ```
97 /// use std::net::{Ipv6Addr, SocketAddrV6};
98 ///
99 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
100 ///
101 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
102 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
103 /// assert_eq!(socket.port(), 8080);
104 /// ```
105 #[derive(Copy)]
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
108
109 impl SocketAddr {
110     /// Creates a new socket address from an [IP address] and a port number.
111     ///
112     /// [IP address]: ../../std/net/enum.IpAddr.html
113     ///
114     /// # Examples
115     ///
116     /// ```
117     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
118     ///
119     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
120     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
121     /// assert_eq!(socket.port(), 8080);
122     /// ```
123     #[stable(feature = "ip_addr", since = "1.7.0")]
124     pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
125         match ip {
126             IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
127             IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
128         }
129     }
130
131     /// Returns the IP address associated with this socket address.
132     ///
133     /// # Examples
134     ///
135     /// ```
136     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
137     ///
138     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
139     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
140     /// ```
141     #[stable(feature = "ip_addr", since = "1.7.0")]
142     pub fn ip(&self) -> IpAddr {
143         match *self {
144             SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
145             SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
146         }
147     }
148
149     /// Changes the IP address associated with this socket address.
150     ///
151     /// # Examples
152     ///
153     /// ```
154     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
155     ///
156     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
157     /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
158     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
159     /// ```
160     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
161     pub fn set_ip(&mut self, new_ip: IpAddr) {
162         // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
163         match (self, new_ip) {
164             (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
165             (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
166             (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
167         }
168     }
169
170     /// Returns the port number associated with this socket address.
171     ///
172     /// # Examples
173     ///
174     /// ```
175     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
176     ///
177     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
178     /// assert_eq!(socket.port(), 8080);
179     /// ```
180     #[stable(feature = "rust1", since = "1.0.0")]
181     pub fn port(&self) -> u16 {
182         match *self {
183             SocketAddr::V4(ref a) => a.port(),
184             SocketAddr::V6(ref a) => a.port(),
185         }
186     }
187
188     /// Changes the port number associated with this socket address.
189     ///
190     /// # Examples
191     ///
192     /// ```
193     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
194     ///
195     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
196     /// socket.set_port(1025);
197     /// assert_eq!(socket.port(), 1025);
198     /// ```
199     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
200     pub fn set_port(&mut self, new_port: u16) {
201         match *self {
202             SocketAddr::V4(ref mut a) => a.set_port(new_port),
203             SocketAddr::V6(ref mut a) => a.set_port(new_port),
204         }
205     }
206
207     /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
208     /// [IPv4 address], and [`false`] otherwise.
209     ///
210     /// [`true`]: ../../std/primitive.bool.html
211     /// [`false`]: ../../std/primitive.bool.html
212     /// [IP address]: ../../std/net/enum.IpAddr.html
213     /// [IPv4 address]: ../../std/net/enum.IpAddr.html#variant.V4
214     ///
215     /// # Examples
216     ///
217     /// ```
218     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
219     ///
220     /// fn main() {
221     ///     let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
222     ///     assert_eq!(socket.is_ipv4(), true);
223     ///     assert_eq!(socket.is_ipv6(), false);
224     /// }
225     /// ```
226     #[stable(feature = "sockaddr_checker", since = "1.16.0")]
227     pub fn is_ipv4(&self) -> bool {
228         match *self {
229             SocketAddr::V4(_) => true,
230             SocketAddr::V6(_) => false,
231         }
232     }
233
234     /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
235     /// [IPv6 address], and [`false`] otherwise.
236     ///
237     /// [`true`]: ../../std/primitive.bool.html
238     /// [`false`]: ../../std/primitive.bool.html
239     /// [IP address]: ../../std/net/enum.IpAddr.html
240     /// [IPv6 address]: ../../std/net/enum.IpAddr.html#variant.V6
241     ///
242     /// # Examples
243     ///
244     /// ```
245     /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
246     ///
247     /// fn main() {
248     ///     let socket = SocketAddr::new(
249     ///                      IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
250     ///     assert_eq!(socket.is_ipv4(), false);
251     ///     assert_eq!(socket.is_ipv6(), true);
252     /// }
253     /// ```
254     #[stable(feature = "sockaddr_checker", since = "1.16.0")]
255     pub fn is_ipv6(&self) -> bool {
256         match *self {
257             SocketAddr::V4(_) => false,
258             SocketAddr::V6(_) => true,
259         }
260     }
261 }
262
263 impl SocketAddrV4 {
264     /// Creates a new socket address from an [IPv4 address] and a port number.
265     ///
266     /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
267     ///
268     /// # Examples
269     ///
270     /// ```
271     /// use std::net::{SocketAddrV4, Ipv4Addr};
272     ///
273     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
274     /// ```
275     #[stable(feature = "rust1", since = "1.0.0")]
276     pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
277         SocketAddrV4 {
278             inner: c::sockaddr_in {
279                 sin_family: c::AF_INET as c::sa_family_t,
280                 sin_port: hton(port),
281                 sin_addr: *ip.as_inner(),
282                 .. unsafe { mem::zeroed() }
283             },
284         }
285     }
286
287     /// Returns the IP address associated with this socket address.
288     ///
289     /// # Examples
290     ///
291     /// ```
292     /// use std::net::{SocketAddrV4, Ipv4Addr};
293     ///
294     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
295     /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
296     /// ```
297     #[stable(feature = "rust1", since = "1.0.0")]
298     pub fn ip(&self) -> &Ipv4Addr {
299         unsafe {
300             &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
301         }
302     }
303
304     /// Changes the IP address associated with this socket address.
305     ///
306     /// # Examples
307     ///
308     /// ```
309     /// use std::net::{SocketAddrV4, Ipv4Addr};
310     ///
311     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
312     /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
313     /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
314     /// ```
315     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
316     pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
317         self.inner.sin_addr = *new_ip.as_inner()
318     }
319
320     /// Returns the port number associated with this socket address.
321     ///
322     /// # Examples
323     ///
324     /// ```
325     /// use std::net::{SocketAddrV4, Ipv4Addr};
326     ///
327     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
328     /// assert_eq!(socket.port(), 8080);
329     /// ```
330     #[stable(feature = "rust1", since = "1.0.0")]
331     pub fn port(&self) -> u16 {
332         ntoh(self.inner.sin_port)
333     }
334
335     /// Changes the port number associated with this socket address.
336     ///
337     /// # Examples
338     ///
339     /// ```
340     /// use std::net::{SocketAddrV4, Ipv4Addr};
341     ///
342     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
343     /// socket.set_port(4242);
344     /// assert_eq!(socket.port(), 4242);
345     /// ```
346     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
347     pub fn set_port(&mut self, new_port: u16) {
348         self.inner.sin_port = hton(new_port);
349     }
350 }
351
352 impl SocketAddrV6 {
353     /// Creates a new socket address from an [IPv6 address], a 16-bit port number,
354     /// and the `flowinfo` and `scope_id` fields.
355     ///
356     /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
357     /// parameters, see [IETF RFC 2553, Section 3.3].
358     ///
359     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
360     /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
361     ///
362     /// # Examples
363     ///
364     /// ```
365     /// use std::net::{SocketAddrV6, Ipv6Addr};
366     ///
367     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
368     /// ```
369     #[stable(feature = "rust1", since = "1.0.0")]
370     pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
371                -> SocketAddrV6 {
372         SocketAddrV6 {
373             inner: c::sockaddr_in6 {
374                 sin6_family: c::AF_INET6 as c::sa_family_t,
375                 sin6_port: hton(port),
376                 sin6_addr: *ip.as_inner(),
377                 sin6_flowinfo: flowinfo,
378                 sin6_scope_id: scope_id,
379                 .. unsafe { mem::zeroed() }
380             },
381         }
382     }
383
384     /// Returns the IP address associated with this socket address.
385     ///
386     /// # Examples
387     ///
388     /// ```
389     /// use std::net::{SocketAddrV6, Ipv6Addr};
390     ///
391     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
392     /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
393     /// ```
394     #[stable(feature = "rust1", since = "1.0.0")]
395     pub fn ip(&self) -> &Ipv6Addr {
396         unsafe {
397             &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
398         }
399     }
400
401     /// Changes the IP address associated with this socket address.
402     ///
403     /// # Examples
404     ///
405     /// ```
406     /// use std::net::{SocketAddrV6, Ipv6Addr};
407     ///
408     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
409     /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
410     /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
411     /// ```
412     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
413     pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
414         self.inner.sin6_addr = *new_ip.as_inner()
415     }
416
417     /// Returns the port number associated with this socket address.
418     ///
419     /// # Examples
420     ///
421     /// ```
422     /// use std::net::{SocketAddrV6, Ipv6Addr};
423     ///
424     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
425     /// assert_eq!(socket.port(), 8080);
426     /// ```
427     #[stable(feature = "rust1", since = "1.0.0")]
428     pub fn port(&self) -> u16 {
429         ntoh(self.inner.sin6_port)
430     }
431
432     /// Changes the port number associated with this socket address.
433     ///
434     /// # Examples
435     ///
436     /// ```
437     /// use std::net::{SocketAddrV6, Ipv6Addr};
438     ///
439     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
440     /// socket.set_port(4242);
441     /// assert_eq!(socket.port(), 4242);
442     /// ```
443     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
444     pub fn set_port(&mut self, new_port: u16) {
445         self.inner.sin6_port = hton(new_port);
446     }
447
448     /// Returns the flow information associated with this address.
449     ///
450     /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
451     /// as specified in [IETF RFC 2553, Section 3.3].
452     /// It combines information about the flow label and the traffic class as specified
453     /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
454     ///
455     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
456     /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
457     /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
458     /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
459     ///
460     /// # Examples
461     ///
462     /// ```
463     /// use std::net::{SocketAddrV6, Ipv6Addr};
464     ///
465     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
466     /// assert_eq!(socket.flowinfo(), 10);
467     /// ```
468     #[stable(feature = "rust1", since = "1.0.0")]
469     pub fn flowinfo(&self) -> u32 {
470         self.inner.sin6_flowinfo
471     }
472
473     /// Changes the flow information associated with this socket address.
474     ///
475     /// See the [`flowinfo`] method's documentation for more details.
476     ///
477     /// [`flowinfo`]: #method.flowinfo
478     ///
479     /// # Examples
480     ///
481     /// ```
482     /// use std::net::{SocketAddrV6, Ipv6Addr};
483     ///
484     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
485     /// socket.set_flowinfo(56);
486     /// assert_eq!(socket.flowinfo(), 56);
487     /// ```
488     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
489     pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
490         self.inner.sin6_flowinfo = new_flowinfo;
491     }
492
493     /// Returns the scope ID associated with this address.
494     ///
495     /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
496     /// as specified in [IETF RFC 2553, Section 3.3].
497     ///
498     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
499     ///
500     /// # Examples
501     ///
502     /// ```
503     /// use std::net::{SocketAddrV6, Ipv6Addr};
504     ///
505     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
506     /// assert_eq!(socket.scope_id(), 78);
507     /// ```
508     #[stable(feature = "rust1", since = "1.0.0")]
509     pub fn scope_id(&self) -> u32 {
510         self.inner.sin6_scope_id
511     }
512
513     /// Changes the scope ID associated with this socket address.
514     ///
515     /// See the [`scope_id`] method's documentation for more details.
516     ///
517     /// [`scope_id`]: #method.scope_id
518     ///
519     /// # Examples
520     ///
521     /// ```
522     /// use std::net::{SocketAddrV6, Ipv6Addr};
523     ///
524     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
525     /// socket.set_scope_id(42);
526     /// assert_eq!(socket.scope_id(), 42);
527     /// ```
528     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
529     pub fn set_scope_id(&mut self, new_scope_id: u32) {
530         self.inner.sin6_scope_id = new_scope_id;
531     }
532 }
533
534 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
535     fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
536         SocketAddrV4 { inner: addr }
537     }
538 }
539
540 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
541     fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
542         SocketAddrV6 { inner: addr }
543     }
544 }
545
546 #[stable(feature = "ip_from_ip", since = "1.16.0")]
547 impl From<SocketAddrV4> for SocketAddr {
548     /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
549     fn from(sock4: SocketAddrV4) -> SocketAddr {
550         SocketAddr::V4(sock4)
551     }
552 }
553
554 #[stable(feature = "ip_from_ip", since = "1.16.0")]
555 impl From<SocketAddrV6> for SocketAddr {
556     /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
557     fn from(sock6: SocketAddrV6) -> SocketAddr {
558         SocketAddr::V6(sock6)
559     }
560 }
561
562 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
563 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
564     /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
565     ///
566     /// This conversion creates a [`SocketAddr::V4`] for a [`IpAddr::V4`]
567     /// and creates a [`SocketAddr::V6`] for a [`IpAddr::V6`].
568     ///
569     /// `u16` is treated as port of the newly created [`SocketAddr`].
570     fn from(pieces: (I, u16)) -> SocketAddr {
571         SocketAddr::new(pieces.0.into(), pieces.1)
572     }
573 }
574
575 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
576     fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
577         match *self {
578             SocketAddr::V4(ref a) => {
579                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
580             }
581             SocketAddr::V6(ref a) => {
582                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
583             }
584         }
585     }
586 }
587
588 #[stable(feature = "rust1", since = "1.0.0")]
589 impl fmt::Display for SocketAddr {
590     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
591         match *self {
592             SocketAddr::V4(ref a) => a.fmt(f),
593             SocketAddr::V6(ref a) => a.fmt(f),
594         }
595     }
596 }
597
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl fmt::Display for SocketAddrV4 {
600     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
601         write!(f, "{}:{}", self.ip(), self.port())
602     }
603 }
604
605 #[stable(feature = "rust1", since = "1.0.0")]
606 impl fmt::Debug for SocketAddrV4 {
607     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
608         fmt::Display::fmt(self, fmt)
609     }
610 }
611
612 #[stable(feature = "rust1", since = "1.0.0")]
613 impl fmt::Display for SocketAddrV6 {
614     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
615         write!(f, "[{}]:{}", self.ip(), self.port())
616     }
617 }
618
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl fmt::Debug for SocketAddrV6 {
621     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
622         fmt::Display::fmt(self, fmt)
623     }
624 }
625
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl Clone for SocketAddrV4 {
628     fn clone(&self) -> SocketAddrV4 { *self }
629 }
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl Clone for SocketAddrV6 {
632     fn clone(&self) -> SocketAddrV6 { *self }
633 }
634
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl PartialEq for SocketAddrV4 {
637     fn eq(&self, other: &SocketAddrV4) -> bool {
638         self.inner.sin_port == other.inner.sin_port &&
639             self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
640     }
641 }
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl PartialEq for SocketAddrV6 {
644     fn eq(&self, other: &SocketAddrV6) -> bool {
645         self.inner.sin6_port == other.inner.sin6_port &&
646             self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
647             self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
648             self.inner.sin6_scope_id == other.inner.sin6_scope_id
649     }
650 }
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl Eq for SocketAddrV4 {}
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl Eq for SocketAddrV6 {}
655
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl hash::Hash for SocketAddrV4 {
658     fn hash<H: hash::Hasher>(&self, s: &mut H) {
659         (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
660     }
661 }
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl hash::Hash for SocketAddrV6 {
664     fn hash<H: hash::Hasher>(&self, s: &mut H) {
665         (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
666          self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
667     }
668 }
669
670 /// A trait for objects which can be converted or resolved to one or more
671 /// [`SocketAddr`] values.
672 ///
673 /// This trait is used for generic address resolution when constructing network
674 /// objects. By default it is implemented for the following types:
675 ///
676 ///  * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
677 ///
678 ///  * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
679 ///    `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
680 ///    [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
681 ///
682 ///  * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
683 ///    of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
684 ///    name.
685 ///
686 ///  * [`&str`]: the string should be either a string representation of a
687 ///    [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
688 ///    `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
689 ///
690 /// This trait allows constructing network objects like [`TcpStream`] or
691 /// [`UdpSocket`] easily with values of various types for the bind/connection
692 /// address. It is needed because sometimes one type is more appropriate than
693 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
694 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
695 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
696 /// some other type (e.g., a string) just for it to be converted back to
697 /// [`SocketAddr`] in constructor methods is pointless.
698 ///
699 /// Addresses returned by the operating system that are not IP addresses are
700 /// silently ignored.
701 ///
702 /// [`FromStr`]: ../../std/str/trait.FromStr.html
703 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
704 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
705 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
706 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
707 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
708 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
709 /// [`&str`]: ../../std/primitive.str.html
710 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
711 /// [`to_socket_addrs`]: #tymethod.to_socket_addrs
712 /// [`UdpSocket`]: ../../std/net/struct.UdpSocket.html
713 /// [`u16`]: ../../std/primitive.u16.html
714 ///
715 /// # Examples
716 ///
717 /// Creating a [`SocketAddr`] iterator that yields one item:
718 ///
719 /// ```
720 /// use std::net::{ToSocketAddrs, SocketAddr};
721 ///
722 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
723 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
724 ///
725 /// assert_eq!(Some(addr), addrs_iter.next());
726 /// assert!(addrs_iter.next().is_none());
727 /// ```
728 ///
729 /// Creating a [`SocketAddr`] iterator from a hostname:
730 ///
731 /// ```no_run
732 /// use std::net::{SocketAddr, ToSocketAddrs};
733 ///
734 /// // assuming 'localhost' resolves to 127.0.0.1
735 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
736 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
737 /// assert!(addrs_iter.next().is_none());
738 ///
739 /// // assuming 'foo' does not resolve
740 /// assert!("foo:443".to_socket_addrs().is_err());
741 /// ```
742 ///
743 /// Creating a [`SocketAddr`] iterator that yields multiple items:
744 ///
745 /// ```
746 /// use std::net::{SocketAddr, ToSocketAddrs};
747 ///
748 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
749 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
750 /// let addrs = vec![addr1, addr2];
751 ///
752 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
753 ///
754 /// assert_eq!(Some(addr1), addrs_iter.next());
755 /// assert_eq!(Some(addr2), addrs_iter.next());
756 /// assert!(addrs_iter.next().is_none());
757 /// ```
758 ///
759 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
760 /// socket address `&str` (missing the port):
761 ///
762 /// ```
763 /// use std::io;
764 /// use std::net::ToSocketAddrs;
765 ///
766 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
767 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
768 /// ```
769 ///
770 /// [`TcpStream::connect`] is an example of an function that utilizes
771 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
772 /// different types:
773 ///
774 /// ```no_run
775 /// use std::net::{TcpStream, Ipv4Addr};
776 ///
777 /// let stream = TcpStream::connect(("127.0.0.1", 443));
778 /// // or
779 /// let stream = TcpStream::connect("127.0.0.1:443");
780 /// // or
781 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
782 /// ```
783 ///
784 /// [`TcpStream::connect`]: ../../std/net/struct.TcpStream.html#method.connect
785 #[stable(feature = "rust1", since = "1.0.0")]
786 pub trait ToSocketAddrs {
787     /// Returned iterator over socket addresses which this type may correspond
788     /// to.
789     #[stable(feature = "rust1", since = "1.0.0")]
790     type Iter: Iterator<Item=SocketAddr>;
791
792     /// Converts this object to an iterator of resolved `SocketAddr`s.
793     ///
794     /// The returned iterator may not actually yield any values depending on the
795     /// outcome of any resolution performed.
796     ///
797     /// Note that this function may block the current thread while resolution is
798     /// performed.
799     #[stable(feature = "rust1", since = "1.0.0")]
800     fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
801 }
802
803 #[stable(feature = "rust1", since = "1.0.0")]
804 impl ToSocketAddrs for SocketAddr {
805     type Iter = option::IntoIter<SocketAddr>;
806     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
807         Ok(Some(*self).into_iter())
808     }
809 }
810
811 #[stable(feature = "rust1", since = "1.0.0")]
812 impl ToSocketAddrs for SocketAddrV4 {
813     type Iter = option::IntoIter<SocketAddr>;
814     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
815         SocketAddr::V4(*self).to_socket_addrs()
816     }
817 }
818
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl ToSocketAddrs for SocketAddrV6 {
821     type Iter = option::IntoIter<SocketAddr>;
822     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
823         SocketAddr::V6(*self).to_socket_addrs()
824     }
825 }
826
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl ToSocketAddrs for (IpAddr, u16) {
829     type Iter = option::IntoIter<SocketAddr>;
830     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
831         let (ip, port) = *self;
832         match ip {
833             IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
834             IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
835         }
836     }
837 }
838
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl ToSocketAddrs for (Ipv4Addr, u16) {
841     type Iter = option::IntoIter<SocketAddr>;
842     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
843         let (ip, port) = *self;
844         SocketAddrV4::new(ip, port).to_socket_addrs()
845     }
846 }
847
848 #[stable(feature = "rust1", since = "1.0.0")]
849 impl ToSocketAddrs for (Ipv6Addr, u16) {
850     type Iter = option::IntoIter<SocketAddr>;
851     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
852         let (ip, port) = *self;
853         SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
854     }
855 }
856
857 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
858     let p = lh.port();
859     let v: Vec<_> = lh.map(|mut a| { a.set_port(p); a }).collect();
860     Ok(v.into_iter())
861 }
862
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl ToSocketAddrs for (&str, u16) {
865     type Iter = vec::IntoIter<SocketAddr>;
866     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
867         let (host, port) = *self;
868
869         // try to parse the host as a regular IP address first
870         if let Ok(addr) = host.parse::<Ipv4Addr>() {
871             let addr = SocketAddrV4::new(addr, port);
872             return Ok(vec![SocketAddr::V4(addr)].into_iter())
873         }
874         if let Ok(addr) = host.parse::<Ipv6Addr>() {
875             let addr = SocketAddrV6::new(addr, port, 0, 0);
876             return Ok(vec![SocketAddr::V6(addr)].into_iter())
877         }
878
879         resolve_socket_addr((host, port).try_into()?)
880     }
881 }
882
883 // accepts strings like 'localhost:12345'
884 #[stable(feature = "rust1", since = "1.0.0")]
885 impl ToSocketAddrs for str {
886     type Iter = vec::IntoIter<SocketAddr>;
887     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
888         // try to parse as a regular SocketAddr first
889         if let Some(addr) = self.parse().ok() {
890             return Ok(vec![addr].into_iter());
891         }
892
893         resolve_socket_addr(self.try_into()?)
894     }
895 }
896
897 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
898 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
899     type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
900
901     fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
902         Ok(self.iter().cloned())
903     }
904 }
905
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
908     type Iter = T::Iter;
909     fn to_socket_addrs(&self) -> io::Result<T::Iter> {
910         (**self).to_socket_addrs()
911     }
912 }
913
914 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
915 impl ToSocketAddrs for String {
916     type Iter = vec::IntoIter<SocketAddr>;
917     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
918         (&**self).to_socket_addrs()
919     }
920 }
921
922 #[cfg(all(test, not(target_os = "emscripten")))]
923 mod tests {
924     use crate::net::*;
925     use crate::net::test::{tsa, sa6, sa4};
926
927     #[test]
928     fn to_socket_addr_ipaddr_u16() {
929         let a = Ipv4Addr::new(77, 88, 21, 11);
930         let p = 12345;
931         let e = SocketAddr::V4(SocketAddrV4::new(a, p));
932         assert_eq!(Ok(vec![e]), tsa((a, p)));
933     }
934
935     #[test]
936     fn to_socket_addr_str_u16() {
937         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
938         assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
939
940         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
941         assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
942
943         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
944         #[cfg(not(target_env = "sgx"))]
945         assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
946         #[cfg(target_env = "sgx")]
947         let _ = a;
948     }
949
950     #[test]
951     fn to_socket_addr_str() {
952         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
953         assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
954
955         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
956         assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
957
958         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
959         #[cfg(not(target_env = "sgx"))]
960         assert!(tsa("localhost:23924").unwrap().contains(&a));
961         #[cfg(target_env = "sgx")]
962         let _ = a;
963     }
964
965     #[test]
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")));
971
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
975     }
976
977     // FIXME: figure out why this fails on openbsd and bitrig and fix it
978     #[test]
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());
982     }
983
984     #[test]
985     fn set_ip() {
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) }
988
989         let mut v4 = SocketAddrV4::new(ip4(11), 80);
990         assert_eq!(v4.ip(), &ip4(11));
991         v4.set_ip(ip4(12));
992         assert_eq!(v4.ip(), &ip4(12));
993
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)));
1000
1001         let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1002         assert_eq!(v6.ip(), &ip6(1));
1003         v6.set_ip(ip6(2));
1004         assert_eq!(v6.ip(), &ip6(2));
1005
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)));
1012     }
1013
1014     #[test]
1015     fn set_port() {
1016         let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1017         assert_eq!(v4.port(), 80);
1018         v4.set_port(443);
1019         assert_eq!(v4.port(), 443);
1020
1021         let mut addr = SocketAddr::V4(v4);
1022         assert_eq!(addr.port(), 443);
1023         addr.set_port(8080);
1024         assert_eq!(addr.port(), 8080);
1025
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);
1028         v6.set_port(443);
1029         assert_eq!(v6.port(), 443);
1030
1031         let mut addr = SocketAddr::V6(v6);
1032         assert_eq!(addr.port(), 443);
1033         addr.set_port(8080);
1034         assert_eq!(addr.port(), 8080);
1035     }
1036
1037     #[test]
1038     fn set_flowinfo() {
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);
1043     }
1044
1045     #[test]
1046     fn set_scope_id() {
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);
1051     }
1052
1053     #[test]
1054     fn is_v4() {
1055         let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1056         assert!(v4.is_ipv4());
1057         assert!(!v4.is_ipv6());
1058     }
1059
1060     #[test]
1061     fn is_v6() {
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());
1066     }
1067 }