]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/addr.rs
Rollup merge of #37962 - GuillaumeGomez:socket-v6, r=frewsxcv
[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::{lookup_host, ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
16 use option;
17 use sys::net::netc as c;
18 use sys_common::{FromInner, AsInner, IntoInner};
19 use vec;
20 use iter;
21 use slice;
22
23 /// Representation of a socket address for networking applications.
24 ///
25 /// A socket address can either represent the IPv4 or IPv6 protocol and is
26 /// paired with at least a port number as well. Each protocol may have more
27 /// specific information about the address available to it as well.
28 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
29 #[stable(feature = "rust1", since = "1.0.0")]
30 pub enum SocketAddr {
31     /// An IPv4 socket address which is a (ip, port) combination.
32     #[stable(feature = "rust1", since = "1.0.0")]
33     V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
34     /// An IPv6 socket address.
35     #[stable(feature = "rust1", since = "1.0.0")]
36     V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
37 }
38
39 /// An IPv4 socket address which is a (ip, port) combination.
40 #[derive(Copy)]
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub struct SocketAddrV4 { inner: c::sockaddr_in }
43
44 /// An IPv6 socket address.
45 #[derive(Copy)]
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
48
49 impl SocketAddr {
50     /// Creates a new socket address from the (ip, port) pair.
51     ///
52     /// # Examples
53     ///
54     /// ```
55     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
56     ///
57     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
58     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
59     /// assert_eq!(socket.port(), 8080);
60     /// ```
61     #[stable(feature = "ip_addr", since = "1.7.0")]
62     pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
63         match ip {
64             IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
65             IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
66         }
67     }
68
69     /// Returns the IP address associated with this socket address.
70     ///
71     /// # Examples
72     ///
73     /// ```
74     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
75     ///
76     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
77     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
78     /// ```
79     #[stable(feature = "ip_addr", since = "1.7.0")]
80     pub fn ip(&self) -> IpAddr {
81         match *self {
82             SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
83             SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
84         }
85     }
86
87     /// Change the IP address associated with this socket address.
88     ///
89     /// # Examples
90     ///
91     /// ```
92     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
93     ///
94     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
95     /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
96     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
97     /// ```
98     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
99     pub fn set_ip(&mut self, new_ip: IpAddr) {
100         // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
101         match (self, new_ip) {
102             (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
103             (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
104             (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
105         }
106     }
107
108     /// Returns the port number associated with this socket address.
109     ///
110     /// # Examples
111     ///
112     /// ```
113     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
114     ///
115     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
116     /// assert_eq!(socket.port(), 8080);
117     /// ```
118     #[stable(feature = "rust1", since = "1.0.0")]
119     pub fn port(&self) -> u16 {
120         match *self {
121             SocketAddr::V4(ref a) => a.port(),
122             SocketAddr::V6(ref a) => a.port(),
123         }
124     }
125
126     /// Change the port number associated with this socket address.
127     ///
128     /// # Examples
129     ///
130     /// ```
131     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
132     ///
133     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
134     /// socket.set_port(1025);
135     /// assert_eq!(socket.port(), 1025);
136     /// ```
137     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
138     pub fn set_port(&mut self, new_port: u16) {
139         match *self {
140             SocketAddr::V4(ref mut a) => a.set_port(new_port),
141             SocketAddr::V6(ref mut a) => a.set_port(new_port),
142         }
143     }
144
145     /// Returns true if the IP in this `SocketAddr` is a valid IPv4 address,
146     /// false if it's a valid IPv6 address.
147     ///
148     /// # Examples
149     ///
150     /// ```
151     /// #![feature(sockaddr_checker)]
152     ///
153     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
154     ///
155     /// fn main() {
156     ///     let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
157     ///     assert_eq!(socket.is_ipv4(), true);
158     ///     assert_eq!(socket.is_ipv6(), false);
159     /// }
160     /// ```
161     #[unstable(feature = "sockaddr_checker", issue = "36949")]
162     pub fn is_ipv4(&self) -> bool {
163         match *self {
164             SocketAddr::V4(_) => true,
165             SocketAddr::V6(_) => false,
166         }
167     }
168
169     /// Returns true if the IP in this `SocketAddr` is a valid IPv6 address,
170     /// false if it's a valid IPv4 address.
171     ///
172     /// # Examples
173     ///
174     /// ```
175     /// #![feature(sockaddr_checker)]
176     ///
177     /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
178     ///
179     /// fn main() {
180     ///     let socket = SocketAddr::new(
181     ///                      IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
182     ///     assert_eq!(socket.is_ipv4(), false);
183     ///     assert_eq!(socket.is_ipv6(), true);
184     /// }
185     /// ```
186     #[unstable(feature = "sockaddr_checker", issue = "36949")]
187     pub fn is_ipv6(&self) -> bool {
188         match *self {
189             SocketAddr::V4(_) => false,
190             SocketAddr::V6(_) => true,
191         }
192     }
193 }
194
195 impl SocketAddrV4 {
196     /// Creates a new socket address from the (ip, port) pair.
197     ///
198     /// # Examples
199     ///
200     /// ```
201     /// use std::net::{SocketAddrV4, Ipv4Addr};
202     ///
203     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
204     /// ```
205     #[stable(feature = "rust1", since = "1.0.0")]
206     pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
207         SocketAddrV4 {
208             inner: c::sockaddr_in {
209                 sin_family: c::AF_INET as c::sa_family_t,
210                 sin_port: hton(port),
211                 sin_addr: *ip.as_inner(),
212                 .. unsafe { mem::zeroed() }
213             },
214         }
215     }
216
217     /// Returns the IP address associated with this socket address.
218     ///
219     /// # Examples
220     ///
221     /// ```
222     /// use std::net::{SocketAddrV4, Ipv4Addr};
223     ///
224     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
225     /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
226     /// ```
227     #[stable(feature = "rust1", since = "1.0.0")]
228     pub fn ip(&self) -> &Ipv4Addr {
229         unsafe {
230             &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
231         }
232     }
233
234     /// Change the IP address associated with this socket address.
235     ///
236     /// # Examples
237     ///
238     /// ```
239     /// use std::net::{SocketAddrV4, Ipv4Addr};
240     ///
241     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
242     /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
243     /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
244     /// ```
245     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
246     pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
247         self.inner.sin_addr = *new_ip.as_inner()
248     }
249
250     /// Returns the port number associated with this socket address.
251     ///
252     /// # Examples
253     ///
254     /// ```
255     /// use std::net::{SocketAddrV4, Ipv4Addr};
256     ///
257     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
258     /// assert_eq!(socket.port(), 8080);
259     /// ```
260     #[stable(feature = "rust1", since = "1.0.0")]
261     pub fn port(&self) -> u16 {
262         ntoh(self.inner.sin_port)
263     }
264
265     /// Change the port number associated with this socket address.
266     ///
267     /// # Examples
268     ///
269     /// ```
270     /// use std::net::{SocketAddrV4, Ipv4Addr};
271     ///
272     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
273     /// socket.set_port(4242);
274     /// assert_eq!(socket.port(), 4242);
275     /// ```
276     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
277     pub fn set_port(&mut self, new_port: u16) {
278         self.inner.sin_port = hton(new_port);
279     }
280 }
281
282 impl SocketAddrV6 {
283     /// Creates a new socket address from the ip/port/flowinfo/scope_id
284     /// components.
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// use std::net::{SocketAddrV6, Ipv6Addr};
290     ///
291     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
292     /// ```
293     #[stable(feature = "rust1", since = "1.0.0")]
294     pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
295                -> SocketAddrV6 {
296         SocketAddrV6 {
297             inner: c::sockaddr_in6 {
298                 sin6_family: c::AF_INET6 as c::sa_family_t,
299                 sin6_port: hton(port),
300                 sin6_addr: *ip.as_inner(),
301                 sin6_flowinfo: flowinfo,
302                 sin6_scope_id: scope_id,
303                 .. unsafe { mem::zeroed() }
304             },
305         }
306     }
307
308     /// Returns the IP address associated with this socket address.
309     ///
310     /// # Examples
311     ///
312     /// ```
313     /// use std::net::{SocketAddrV6, Ipv6Addr};
314     ///
315     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
316     /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
317     /// ```
318     #[stable(feature = "rust1", since = "1.0.0")]
319     pub fn ip(&self) -> &Ipv6Addr {
320         unsafe {
321             &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
322         }
323     }
324
325     /// Change the IP address associated with this socket address.
326     ///
327     /// # Examples
328     ///
329     /// ```
330     /// use std::net::{SocketAddrV6, Ipv6Addr};
331     ///
332     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
333     /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
334     /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
335     /// ```
336     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
337     pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
338         self.inner.sin6_addr = *new_ip.as_inner()
339     }
340
341     /// Returns the port number associated with this socket address.
342     ///
343     /// # Examples
344     ///
345     /// ```
346     /// use std::net::{SocketAddrV6, Ipv6Addr};
347     ///
348     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
349     /// assert_eq!(socket.port(), 8080);
350     /// ```
351     #[stable(feature = "rust1", since = "1.0.0")]
352     pub fn port(&self) -> u16 {
353         ntoh(self.inner.sin6_port)
354     }
355
356     /// Change the port number associated with this socket address.
357     ///
358     /// # Examples
359     ///
360     /// ```
361     /// use std::net::{SocketAddrV6, Ipv6Addr};
362     ///
363     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
364     /// socket.set_port(4242);
365     /// assert_eq!(socket.port(), 4242);
366     /// ```
367     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
368     pub fn set_port(&mut self, new_port: u16) {
369         self.inner.sin6_port = hton(new_port);
370     }
371
372     /// Returns the flow information associated with this address,
373     /// corresponding to the `sin6_flowinfo` field in C.
374     ///
375     /// # Examples
376     ///
377     /// ```
378     /// use std::net::{SocketAddrV6, Ipv6Addr};
379     ///
380     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
381     /// assert_eq!(socket.flowinfo(), 10);
382     /// ```
383     #[stable(feature = "rust1", since = "1.0.0")]
384     pub fn flowinfo(&self) -> u32 {
385         self.inner.sin6_flowinfo
386     }
387
388     /// Change the flow information associated with this socket address.
389     ///
390     /// # Examples
391     ///
392     /// ```
393     /// use std::net::{SocketAddrV6, Ipv6Addr};
394     ///
395     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
396     /// socket.set_flowinfo(56);
397     /// assert_eq!(socket.flowinfo(), 56);
398     /// ```
399     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
400     pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
401         self.inner.sin6_flowinfo = new_flowinfo;
402     }
403
404     /// Returns the scope ID associated with this address,
405     /// corresponding to the `sin6_scope_id` field in C.
406     ///
407     /// # Examples
408     ///
409     /// ```
410     /// use std::net::{SocketAddrV6, Ipv6Addr};
411     ///
412     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
413     /// assert_eq!(socket.scope_id(), 78);
414     /// ```
415     #[stable(feature = "rust1", since = "1.0.0")]
416     pub fn scope_id(&self) -> u32 {
417         self.inner.sin6_scope_id
418     }
419
420     /// Change the scope ID associated with this socket address.
421     ///
422     /// # Examples
423     ///
424     /// ```
425     /// use std::net::{SocketAddrV6, Ipv6Addr};
426     ///
427     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
428     /// socket.set_scope_id(42);
429     /// assert_eq!(socket.scope_id(), 42);
430     /// ```
431     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
432     pub fn set_scope_id(&mut self, new_scope_id: u32) {
433         self.inner.sin6_scope_id = new_scope_id;
434     }
435 }
436
437 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
438     fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
439         SocketAddrV4 { inner: addr }
440     }
441 }
442
443 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
444     fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
445         SocketAddrV6 { inner: addr }
446     }
447 }
448
449 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
450     fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
451         match *self {
452             SocketAddr::V4(ref a) => {
453                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
454             }
455             SocketAddr::V6(ref a) => {
456                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
457             }
458         }
459     }
460 }
461
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl fmt::Display for SocketAddr {
464     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
465         match *self {
466             SocketAddr::V4(ref a) => a.fmt(f),
467             SocketAddr::V6(ref a) => a.fmt(f),
468         }
469     }
470 }
471
472 #[stable(feature = "rust1", since = "1.0.0")]
473 impl fmt::Display for SocketAddrV4 {
474     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
475         write!(f, "{}:{}", self.ip(), self.port())
476     }
477 }
478
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl fmt::Debug for SocketAddrV4 {
481     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
482         fmt::Display::fmt(self, fmt)
483     }
484 }
485
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl fmt::Display for SocketAddrV6 {
488     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489         write!(f, "[{}]:{}", self.ip(), self.port())
490     }
491 }
492
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl fmt::Debug for SocketAddrV6 {
495     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
496         fmt::Display::fmt(self, fmt)
497     }
498 }
499
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl Clone for SocketAddrV4 {
502     fn clone(&self) -> SocketAddrV4 { *self }
503 }
504 #[stable(feature = "rust1", since = "1.0.0")]
505 impl Clone for SocketAddrV6 {
506     fn clone(&self) -> SocketAddrV6 { *self }
507 }
508
509 #[stable(feature = "rust1", since = "1.0.0")]
510 impl PartialEq for SocketAddrV4 {
511     fn eq(&self, other: &SocketAddrV4) -> bool {
512         self.inner.sin_port == other.inner.sin_port &&
513             self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
514     }
515 }
516 #[stable(feature = "rust1", since = "1.0.0")]
517 impl PartialEq for SocketAddrV6 {
518     fn eq(&self, other: &SocketAddrV6) -> bool {
519         self.inner.sin6_port == other.inner.sin6_port &&
520             self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
521             self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
522             self.inner.sin6_scope_id == other.inner.sin6_scope_id
523     }
524 }
525 #[stable(feature = "rust1", since = "1.0.0")]
526 impl Eq for SocketAddrV4 {}
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl Eq for SocketAddrV6 {}
529
530 #[stable(feature = "rust1", since = "1.0.0")]
531 impl hash::Hash for SocketAddrV4 {
532     fn hash<H: hash::Hasher>(&self, s: &mut H) {
533         (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
534     }
535 }
536 #[stable(feature = "rust1", since = "1.0.0")]
537 impl hash::Hash for SocketAddrV6 {
538     fn hash<H: hash::Hasher>(&self, s: &mut H) {
539         (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
540          self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
541     }
542 }
543
544 /// A trait for objects which can be converted or resolved to one or more
545 /// `SocketAddr` values.
546 ///
547 /// This trait is used for generic address resolution when constructing network
548 /// objects.  By default it is implemented for the following types:
549 ///
550 ///  * `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` - `to_socket_addrs` is
551 ///    identity function.
552 ///
553 ///  * `(IpvNAddr, u16)` - `to_socket_addrs` constructs `SocketAddr` trivially.
554 ///
555 ///  * `(&str, u16)` - the string should be either a string representation of an
556 ///    IP address expected by `FromStr` implementation for `IpvNAddr` or a host
557 ///    name.
558 ///
559 ///  * `&str` - the string should be either a string representation of a
560 ///    `SocketAddr` as expected by its `FromStr` implementation or a string like
561 ///    `<host_name>:<port>` pair where `<port>` is a `u16` value.
562 ///
563 /// This trait allows constructing network objects like `TcpStream` or
564 /// `UdpSocket` easily with values of various types for the bind/connection
565 /// address. It is needed because sometimes one type is more appropriate than
566 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
567 /// than manual construction of the corresponding `SocketAddr`, but sometimes
568 /// `SocketAddr` value is *the* main source of the address, and converting it to
569 /// some other type (e.g. a string) just for it to be converted back to
570 /// `SocketAddr` in constructor methods is pointless.
571 ///
572 /// Addresses returned by the operating system that are not IP addresses are
573 /// silently ignored.
574 ///
575 /// Some examples:
576 ///
577 /// ```no_run
578 /// use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
579 ///
580 /// fn main() {
581 ///     let ip = Ipv4Addr::new(127, 0, 0, 1);
582 ///     let port = 12345;
583 ///
584 ///     // The following lines are equivalent modulo possible "localhost" name
585 ///     // resolution differences
586 ///     let tcp_s = TcpStream::connect(SocketAddrV4::new(ip, port));
587 ///     let tcp_s = TcpStream::connect((ip, port));
588 ///     let tcp_s = TcpStream::connect(("127.0.0.1", port));
589 ///     let tcp_s = TcpStream::connect(("localhost", port));
590 ///     let tcp_s = TcpStream::connect("127.0.0.1:12345");
591 ///     let tcp_s = TcpStream::connect("localhost:12345");
592 ///
593 ///     // TcpListener::bind(), UdpSocket::bind() and UdpSocket::send_to()
594 ///     // behave similarly
595 ///     let tcp_l = TcpListener::bind("localhost:12345");
596 ///
597 ///     let mut udp_s = UdpSocket::bind(("127.0.0.1", port)).unwrap();
598 ///     udp_s.send_to(&[7], (ip, 23451)).unwrap();
599 /// }
600 /// ```
601 #[stable(feature = "rust1", since = "1.0.0")]
602 pub trait ToSocketAddrs {
603     /// Returned iterator over socket addresses which this type may correspond
604     /// to.
605     #[stable(feature = "rust1", since = "1.0.0")]
606     type Iter: Iterator<Item=SocketAddr>;
607
608     /// Converts this object to an iterator of resolved `SocketAddr`s.
609     ///
610     /// The returned iterator may not actually yield any values depending on the
611     /// outcome of any resolution performed.
612     ///
613     /// Note that this function may block the current thread while resolution is
614     /// performed.
615     ///
616     /// # Errors
617     ///
618     /// Any errors encountered during resolution will be returned as an `Err`.
619     #[stable(feature = "rust1", since = "1.0.0")]
620     fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
621 }
622
623 #[stable(feature = "rust1", since = "1.0.0")]
624 impl ToSocketAddrs for SocketAddr {
625     type Iter = option::IntoIter<SocketAddr>;
626     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
627         Ok(Some(*self).into_iter())
628     }
629 }
630
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl ToSocketAddrs for SocketAddrV4 {
633     type Iter = option::IntoIter<SocketAddr>;
634     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
635         SocketAddr::V4(*self).to_socket_addrs()
636     }
637 }
638
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl ToSocketAddrs for SocketAddrV6 {
641     type Iter = option::IntoIter<SocketAddr>;
642     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
643         SocketAddr::V6(*self).to_socket_addrs()
644     }
645 }
646
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl ToSocketAddrs for (IpAddr, u16) {
649     type Iter = option::IntoIter<SocketAddr>;
650     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
651         let (ip, port) = *self;
652         match ip {
653             IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
654             IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
655         }
656     }
657 }
658
659 #[stable(feature = "rust1", since = "1.0.0")]
660 impl ToSocketAddrs for (Ipv4Addr, u16) {
661     type Iter = option::IntoIter<SocketAddr>;
662     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
663         let (ip, port) = *self;
664         SocketAddrV4::new(ip, port).to_socket_addrs()
665     }
666 }
667
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl ToSocketAddrs for (Ipv6Addr, u16) {
670     type Iter = option::IntoIter<SocketAddr>;
671     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
672         let (ip, port) = *self;
673         SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
674     }
675 }
676
677 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
678     let ips = lookup_host(s)?;
679     let v: Vec<_> = ips.map(|mut a| { a.set_port(p); a }).collect();
680     Ok(v.into_iter())
681 }
682
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl<'a> ToSocketAddrs for (&'a str, u16) {
685     type Iter = vec::IntoIter<SocketAddr>;
686     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
687         let (host, port) = *self;
688
689         // try to parse the host as a regular IP address first
690         if let Ok(addr) = host.parse::<Ipv4Addr>() {
691             let addr = SocketAddrV4::new(addr, port);
692             return Ok(vec![SocketAddr::V4(addr)].into_iter())
693         }
694         if let Ok(addr) = host.parse::<Ipv6Addr>() {
695             let addr = SocketAddrV6::new(addr, port, 0, 0);
696             return Ok(vec![SocketAddr::V6(addr)].into_iter())
697         }
698
699         resolve_socket_addr(host, port)
700     }
701 }
702
703 // accepts strings like 'localhost:12345'
704 #[stable(feature = "rust1", since = "1.0.0")]
705 impl ToSocketAddrs for str {
706     type Iter = vec::IntoIter<SocketAddr>;
707     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
708         // try to parse as a regular SocketAddr first
709         if let Some(addr) = self.parse().ok() {
710             return Ok(vec![addr].into_iter());
711         }
712
713         macro_rules! try_opt {
714             ($e:expr, $msg:expr) => (
715                 match $e {
716                     Some(r) => r,
717                     None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
718                                                       $msg)),
719                 }
720             )
721         }
722
723         // split the string by ':' and convert the second part to u16
724         let mut parts_iter = self.rsplitn(2, ':');
725         let port_str = try_opt!(parts_iter.next(), "invalid socket address");
726         let host = try_opt!(parts_iter.next(), "invalid socket address");
727         let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
728         resolve_socket_addr(host, port)
729     }
730 }
731
732 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
733 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
734     type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
735
736     fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
737         Ok(self.iter().cloned())
738     }
739 }
740
741 #[stable(feature = "rust1", since = "1.0.0")]
742 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
743     type Iter = T::Iter;
744     fn to_socket_addrs(&self) -> io::Result<T::Iter> {
745         (**self).to_socket_addrs()
746     }
747 }
748
749 #[cfg(all(test, not(target_os = "emscripten")))]
750 mod tests {
751     use net::*;
752     use net::test::{tsa, sa6, sa4};
753
754     #[test]
755     fn to_socket_addr_ipaddr_u16() {
756         let a = Ipv4Addr::new(77, 88, 21, 11);
757         let p = 12345;
758         let e = SocketAddr::V4(SocketAddrV4::new(a, p));
759         assert_eq!(Ok(vec![e]), tsa((a, p)));
760     }
761
762     #[test]
763     fn to_socket_addr_str_u16() {
764         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
765         assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
766
767         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
768         assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
769
770         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
771         assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
772     }
773
774     #[test]
775     fn to_socket_addr_str() {
776         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
777         assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
778
779         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
780         assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
781
782         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
783         assert!(tsa("localhost:23924").unwrap().contains(&a));
784     }
785
786     // FIXME: figure out why this fails on openbsd and bitrig and fix it
787     #[test]
788     #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
789     fn to_socket_addr_str_bad() {
790         assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
791     }
792
793     #[test]
794     fn set_ip() {
795         fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
796         fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
797
798         let mut v4 = SocketAddrV4::new(ip4(11), 80);
799         assert_eq!(v4.ip(), &ip4(11));
800         v4.set_ip(ip4(12));
801         assert_eq!(v4.ip(), &ip4(12));
802
803         let mut addr = SocketAddr::V4(v4);
804         assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
805         addr.set_ip(IpAddr::V4(ip4(13)));
806         assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
807         addr.set_ip(IpAddr::V6(ip6(14)));
808         assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
809
810         let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
811         assert_eq!(v6.ip(), &ip6(1));
812         v6.set_ip(ip6(2));
813         assert_eq!(v6.ip(), &ip6(2));
814
815         let mut addr = SocketAddr::V6(v6);
816         assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
817         addr.set_ip(IpAddr::V6(ip6(3)));
818         assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
819         addr.set_ip(IpAddr::V4(ip4(4)));
820         assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
821     }
822
823     #[test]
824     fn set_port() {
825         let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
826         assert_eq!(v4.port(), 80);
827         v4.set_port(443);
828         assert_eq!(v4.port(), 443);
829
830         let mut addr = SocketAddr::V4(v4);
831         assert_eq!(addr.port(), 443);
832         addr.set_port(8080);
833         assert_eq!(addr.port(), 8080);
834
835         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
836         assert_eq!(v6.port(), 80);
837         v6.set_port(443);
838         assert_eq!(v6.port(), 443);
839
840         let mut addr = SocketAddr::V6(v6);
841         assert_eq!(addr.port(), 443);
842         addr.set_port(8080);
843         assert_eq!(addr.port(), 8080);
844     }
845
846     #[test]
847     fn set_flowinfo() {
848         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
849         assert_eq!(v6.flowinfo(), 10);
850         v6.set_flowinfo(20);
851         assert_eq!(v6.flowinfo(), 20);
852     }
853
854     #[test]
855     fn set_scope_id() {
856         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
857         assert_eq!(v6.scope_id(), 10);
858         v6.set_scope_id(20);
859         assert_eq!(v6.scope_id(), 20);
860     }
861
862     #[test]
863     fn is_v4() {
864         let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
865         assert!(v4.is_ipv4());
866         assert!(!v4.is_ipv6());
867     }
868
869     #[test]
870     fn is_v6() {
871         let v6 = SocketAddr::V6(SocketAddrV6::new(
872                 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
873         assert!(!v6.is_ipv4());
874         assert!(v6.is_ipv6());
875     }
876 }