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