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