]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/addr.rs
Rollup merge of #37836 - steveklabnik:remove-incorrect-reference-comment, r=Guillaume...
[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     #[stable(feature = "rust1", since = "1.0.0")]
198     pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
199         SocketAddrV4 {
200             inner: c::sockaddr_in {
201                 sin_family: c::AF_INET as c::sa_family_t,
202                 sin_port: hton(port),
203                 sin_addr: *ip.as_inner(),
204                 .. unsafe { mem::zeroed() }
205             },
206         }
207     }
208
209     /// Returns the IP address associated with this socket address.
210     #[stable(feature = "rust1", since = "1.0.0")]
211     pub fn ip(&self) -> &Ipv4Addr {
212         unsafe {
213             &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
214         }
215     }
216
217     /// Change the IP address associated with this socket address.
218     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
219     pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
220         self.inner.sin_addr = *new_ip.as_inner()
221     }
222
223     /// Returns the port number associated with this socket address.
224     #[stable(feature = "rust1", since = "1.0.0")]
225     pub fn port(&self) -> u16 {
226         ntoh(self.inner.sin_port)
227     }
228
229     /// Change the port number associated with this socket address.
230     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
231     pub fn set_port(&mut self, new_port: u16) {
232         self.inner.sin_port = hton(new_port);
233     }
234 }
235
236 impl SocketAddrV6 {
237     /// Creates a new socket address from the ip/port/flowinfo/scope_id
238     /// components.
239     #[stable(feature = "rust1", since = "1.0.0")]
240     pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
241                -> SocketAddrV6 {
242         SocketAddrV6 {
243             inner: c::sockaddr_in6 {
244                 sin6_family: c::AF_INET6 as c::sa_family_t,
245                 sin6_port: hton(port),
246                 sin6_addr: *ip.as_inner(),
247                 sin6_flowinfo: flowinfo,
248                 sin6_scope_id: scope_id,
249                 .. unsafe { mem::zeroed() }
250             },
251         }
252     }
253
254     /// Returns the IP address associated with this socket address.
255     #[stable(feature = "rust1", since = "1.0.0")]
256     pub fn ip(&self) -> &Ipv6Addr {
257         unsafe {
258             &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
259         }
260     }
261
262     /// Change the IP address associated with this socket address.
263     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
264     pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
265         self.inner.sin6_addr = *new_ip.as_inner()
266     }
267
268     /// Returns the port number associated with this socket address.
269     #[stable(feature = "rust1", since = "1.0.0")]
270     pub fn port(&self) -> u16 {
271         ntoh(self.inner.sin6_port)
272     }
273
274     /// Change the port number associated with this socket address.
275     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
276     pub fn set_port(&mut self, new_port: u16) {
277         self.inner.sin6_port = hton(new_port);
278     }
279
280     /// Returns the flow information associated with this address,
281     /// corresponding to the `sin6_flowinfo` field in C.
282     #[stable(feature = "rust1", since = "1.0.0")]
283     pub fn flowinfo(&self) -> u32 {
284         self.inner.sin6_flowinfo
285     }
286
287     /// Change the flow information associated with this socket address.
288     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
289     pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
290         self.inner.sin6_flowinfo = new_flowinfo;
291     }
292
293     /// Returns the scope ID associated with this address,
294     /// corresponding to the `sin6_scope_id` field in C.
295     #[stable(feature = "rust1", since = "1.0.0")]
296     pub fn scope_id(&self) -> u32 {
297         self.inner.sin6_scope_id
298     }
299
300     /// Change the scope ID associated with this socket address.
301     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
302     pub fn set_scope_id(&mut self, new_scope_id: u32) {
303         self.inner.sin6_scope_id = new_scope_id;
304     }
305 }
306
307 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
308     fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
309         SocketAddrV4 { inner: addr }
310     }
311 }
312
313 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
314     fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
315         SocketAddrV6 { inner: addr }
316     }
317 }
318
319 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
320     fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
321         match *self {
322             SocketAddr::V4(ref a) => {
323                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
324             }
325             SocketAddr::V6(ref a) => {
326                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
327             }
328         }
329     }
330 }
331
332 #[stable(feature = "rust1", since = "1.0.0")]
333 impl fmt::Display for SocketAddr {
334     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
335         match *self {
336             SocketAddr::V4(ref a) => a.fmt(f),
337             SocketAddr::V6(ref a) => a.fmt(f),
338         }
339     }
340 }
341
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl fmt::Display for SocketAddrV4 {
344     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
345         write!(f, "{}:{}", self.ip(), self.port())
346     }
347 }
348
349 #[stable(feature = "rust1", since = "1.0.0")]
350 impl fmt::Debug for SocketAddrV4 {
351     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
352         fmt::Display::fmt(self, fmt)
353     }
354 }
355
356 #[stable(feature = "rust1", since = "1.0.0")]
357 impl fmt::Display for SocketAddrV6 {
358     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
359         write!(f, "[{}]:{}", self.ip(), self.port())
360     }
361 }
362
363 #[stable(feature = "rust1", since = "1.0.0")]
364 impl fmt::Debug for SocketAddrV6 {
365     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
366         fmt::Display::fmt(self, fmt)
367     }
368 }
369
370 #[stable(feature = "rust1", since = "1.0.0")]
371 impl Clone for SocketAddrV4 {
372     fn clone(&self) -> SocketAddrV4 { *self }
373 }
374 #[stable(feature = "rust1", since = "1.0.0")]
375 impl Clone for SocketAddrV6 {
376     fn clone(&self) -> SocketAddrV6 { *self }
377 }
378
379 #[stable(feature = "rust1", since = "1.0.0")]
380 impl PartialEq for SocketAddrV4 {
381     fn eq(&self, other: &SocketAddrV4) -> bool {
382         self.inner.sin_port == other.inner.sin_port &&
383             self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
384     }
385 }
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl PartialEq for SocketAddrV6 {
388     fn eq(&self, other: &SocketAddrV6) -> bool {
389         self.inner.sin6_port == other.inner.sin6_port &&
390             self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
391             self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
392             self.inner.sin6_scope_id == other.inner.sin6_scope_id
393     }
394 }
395 #[stable(feature = "rust1", since = "1.0.0")]
396 impl Eq for SocketAddrV4 {}
397 #[stable(feature = "rust1", since = "1.0.0")]
398 impl Eq for SocketAddrV6 {}
399
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl hash::Hash for SocketAddrV4 {
402     fn hash<H: hash::Hasher>(&self, s: &mut H) {
403         (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
404     }
405 }
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl hash::Hash for SocketAddrV6 {
408     fn hash<H: hash::Hasher>(&self, s: &mut H) {
409         (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
410          self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
411     }
412 }
413
414 /// A trait for objects which can be converted or resolved to one or more
415 /// `SocketAddr` values.
416 ///
417 /// This trait is used for generic address resolution when constructing network
418 /// objects.  By default it is implemented for the following types:
419 ///
420 ///  * `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` - `to_socket_addrs` is
421 ///    identity function.
422 ///
423 ///  * `(IpvNAddr, u16)` - `to_socket_addrs` constructs `SocketAddr` trivially.
424 ///
425 ///  * `(&str, u16)` - the string should be either a string representation of an
426 ///    IP address expected by `FromStr` implementation for `IpvNAddr` or a host
427 ///    name.
428 ///
429 ///  * `&str` - the string should be either a string representation of a
430 ///    `SocketAddr` as expected by its `FromStr` implementation or a string like
431 ///    `<host_name>:<port>` pair where `<port>` is a `u16` value.
432 ///
433 /// This trait allows constructing network objects like `TcpStream` or
434 /// `UdpSocket` easily with values of various types for the bind/connection
435 /// address. It is needed because sometimes one type is more appropriate than
436 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
437 /// than manual construction of the corresponding `SocketAddr`, but sometimes
438 /// `SocketAddr` value is *the* main source of the address, and converting it to
439 /// some other type (e.g. a string) just for it to be converted back to
440 /// `SocketAddr` in constructor methods is pointless.
441 ///
442 /// Addresses returned by the operating system that are not IP addresses are
443 /// silently ignored.
444 ///
445 /// Some examples:
446 ///
447 /// ```no_run
448 /// use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
449 ///
450 /// fn main() {
451 ///     let ip = Ipv4Addr::new(127, 0, 0, 1);
452 ///     let port = 12345;
453 ///
454 ///     // The following lines are equivalent modulo possible "localhost" name
455 ///     // resolution differences
456 ///     let tcp_s = TcpStream::connect(SocketAddrV4::new(ip, port));
457 ///     let tcp_s = TcpStream::connect((ip, port));
458 ///     let tcp_s = TcpStream::connect(("127.0.0.1", port));
459 ///     let tcp_s = TcpStream::connect(("localhost", port));
460 ///     let tcp_s = TcpStream::connect("127.0.0.1:12345");
461 ///     let tcp_s = TcpStream::connect("localhost:12345");
462 ///
463 ///     // TcpListener::bind(), UdpSocket::bind() and UdpSocket::send_to()
464 ///     // behave similarly
465 ///     let tcp_l = TcpListener::bind("localhost:12345");
466 ///
467 ///     let mut udp_s = UdpSocket::bind(("127.0.0.1", port)).unwrap();
468 ///     udp_s.send_to(&[7], (ip, 23451)).unwrap();
469 /// }
470 /// ```
471 #[stable(feature = "rust1", since = "1.0.0")]
472 pub trait ToSocketAddrs {
473     /// Returned iterator over socket addresses which this type may correspond
474     /// to.
475     #[stable(feature = "rust1", since = "1.0.0")]
476     type Iter: Iterator<Item=SocketAddr>;
477
478     /// Converts this object to an iterator of resolved `SocketAddr`s.
479     ///
480     /// The returned iterator may not actually yield any values depending on the
481     /// outcome of any resolution performed.
482     ///
483     /// Note that this function may block the current thread while resolution is
484     /// performed.
485     ///
486     /// # Errors
487     ///
488     /// Any errors encountered during resolution will be returned as an `Err`.
489     #[stable(feature = "rust1", since = "1.0.0")]
490     fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
491 }
492
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl ToSocketAddrs for SocketAddr {
495     type Iter = option::IntoIter<SocketAddr>;
496     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
497         Ok(Some(*self).into_iter())
498     }
499 }
500
501 #[stable(feature = "rust1", since = "1.0.0")]
502 impl ToSocketAddrs for SocketAddrV4 {
503     type Iter = option::IntoIter<SocketAddr>;
504     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
505         SocketAddr::V4(*self).to_socket_addrs()
506     }
507 }
508
509 #[stable(feature = "rust1", since = "1.0.0")]
510 impl ToSocketAddrs for SocketAddrV6 {
511     type Iter = option::IntoIter<SocketAddr>;
512     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
513         SocketAddr::V6(*self).to_socket_addrs()
514     }
515 }
516
517 #[stable(feature = "rust1", since = "1.0.0")]
518 impl ToSocketAddrs for (IpAddr, u16) {
519     type Iter = option::IntoIter<SocketAddr>;
520     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
521         let (ip, port) = *self;
522         match ip {
523             IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
524             IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
525         }
526     }
527 }
528
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl ToSocketAddrs for (Ipv4Addr, u16) {
531     type Iter = option::IntoIter<SocketAddr>;
532     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
533         let (ip, port) = *self;
534         SocketAddrV4::new(ip, port).to_socket_addrs()
535     }
536 }
537
538 #[stable(feature = "rust1", since = "1.0.0")]
539 impl ToSocketAddrs for (Ipv6Addr, u16) {
540     type Iter = option::IntoIter<SocketAddr>;
541     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
542         let (ip, port) = *self;
543         SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
544     }
545 }
546
547 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
548     let ips = lookup_host(s)?;
549     let v: Vec<_> = ips.map(|mut a| { a.set_port(p); a }).collect();
550     Ok(v.into_iter())
551 }
552
553 #[stable(feature = "rust1", since = "1.0.0")]
554 impl<'a> ToSocketAddrs for (&'a str, u16) {
555     type Iter = vec::IntoIter<SocketAddr>;
556     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
557         let (host, port) = *self;
558
559         // try to parse the host as a regular IP address first
560         if let Ok(addr) = host.parse::<Ipv4Addr>() {
561             let addr = SocketAddrV4::new(addr, port);
562             return Ok(vec![SocketAddr::V4(addr)].into_iter())
563         }
564         if let Ok(addr) = host.parse::<Ipv6Addr>() {
565             let addr = SocketAddrV6::new(addr, port, 0, 0);
566             return Ok(vec![SocketAddr::V6(addr)].into_iter())
567         }
568
569         resolve_socket_addr(host, port)
570     }
571 }
572
573 // accepts strings like 'localhost:12345'
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl ToSocketAddrs for str {
576     type Iter = vec::IntoIter<SocketAddr>;
577     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
578         // try to parse as a regular SocketAddr first
579         if let Some(addr) = self.parse().ok() {
580             return Ok(vec![addr].into_iter());
581         }
582
583         macro_rules! try_opt {
584             ($e:expr, $msg:expr) => (
585                 match $e {
586                     Some(r) => r,
587                     None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
588                                                       $msg)),
589                 }
590             )
591         }
592
593         // split the string by ':' and convert the second part to u16
594         let mut parts_iter = self.rsplitn(2, ':');
595         let port_str = try_opt!(parts_iter.next(), "invalid socket address");
596         let host = try_opt!(parts_iter.next(), "invalid socket address");
597         let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
598         resolve_socket_addr(host, port)
599     }
600 }
601
602 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
603 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
604     type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
605
606     fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
607         Ok(self.iter().cloned())
608     }
609 }
610
611 #[stable(feature = "rust1", since = "1.0.0")]
612 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
613     type Iter = T::Iter;
614     fn to_socket_addrs(&self) -> io::Result<T::Iter> {
615         (**self).to_socket_addrs()
616     }
617 }
618
619 #[cfg(all(test, not(target_os = "emscripten")))]
620 mod tests {
621     use net::*;
622     use net::test::{tsa, sa6, sa4};
623
624     #[test]
625     fn to_socket_addr_ipaddr_u16() {
626         let a = Ipv4Addr::new(77, 88, 21, 11);
627         let p = 12345;
628         let e = SocketAddr::V4(SocketAddrV4::new(a, p));
629         assert_eq!(Ok(vec![e]), tsa((a, p)));
630     }
631
632     #[test]
633     fn to_socket_addr_str_u16() {
634         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
635         assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
636
637         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
638         assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
639
640         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
641         assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
642     }
643
644     #[test]
645     fn to_socket_addr_str() {
646         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
647         assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
648
649         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
650         assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
651
652         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
653         assert!(tsa("localhost:23924").unwrap().contains(&a));
654     }
655
656     // FIXME: figure out why this fails on openbsd and bitrig and fix it
657     #[test]
658     #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
659     fn to_socket_addr_str_bad() {
660         assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
661     }
662
663     #[test]
664     fn set_ip() {
665         fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
666         fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
667
668         let mut v4 = SocketAddrV4::new(ip4(11), 80);
669         assert_eq!(v4.ip(), &ip4(11));
670         v4.set_ip(ip4(12));
671         assert_eq!(v4.ip(), &ip4(12));
672
673         let mut addr = SocketAddr::V4(v4);
674         assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
675         addr.set_ip(IpAddr::V4(ip4(13)));
676         assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
677         addr.set_ip(IpAddr::V6(ip6(14)));
678         assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
679
680         let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
681         assert_eq!(v6.ip(), &ip6(1));
682         v6.set_ip(ip6(2));
683         assert_eq!(v6.ip(), &ip6(2));
684
685         let mut addr = SocketAddr::V6(v6);
686         assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
687         addr.set_ip(IpAddr::V6(ip6(3)));
688         assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
689         addr.set_ip(IpAddr::V4(ip4(4)));
690         assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
691     }
692
693     #[test]
694     fn set_port() {
695         let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
696         assert_eq!(v4.port(), 80);
697         v4.set_port(443);
698         assert_eq!(v4.port(), 443);
699
700         let mut addr = SocketAddr::V4(v4);
701         assert_eq!(addr.port(), 443);
702         addr.set_port(8080);
703         assert_eq!(addr.port(), 8080);
704
705         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
706         assert_eq!(v6.port(), 80);
707         v6.set_port(443);
708         assert_eq!(v6.port(), 443);
709
710         let mut addr = SocketAddr::V6(v6);
711         assert_eq!(addr.port(), 443);
712         addr.set_port(8080);
713         assert_eq!(addr.port(), 8080);
714     }
715
716     #[test]
717     fn set_flowinfo() {
718         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
719         assert_eq!(v6.flowinfo(), 10);
720         v6.set_flowinfo(20);
721         assert_eq!(v6.flowinfo(), 20);
722     }
723
724     #[test]
725     fn set_scope_id() {
726         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
727         assert_eq!(v6.scope_id(), 10);
728         v6.set_scope_id(20);
729         assert_eq!(v6.scope_id(), 20);
730     }
731
732     #[test]
733     fn is_v4() {
734         let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
735         assert!(v4.is_ipv4());
736         assert!(!v4.is_ipv6());
737     }
738
739     #[test]
740     fn is_v6() {
741         let v6 = SocketAddr::V6(SocketAddrV6::new(
742                 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
743         assert!(!v6.is_ipv4());
744         assert!(v6.is_ipv6());
745     }
746 }