]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/addr.rs
Implement ToSocketAddrs for &[SocketAddr]
[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 prelude::v1::*;
12
13 use fmt;
14 use hash;
15 use io;
16 use mem;
17 use net::{lookup_host, ntoh, hton, Ipv4Addr, Ipv6Addr};
18 #[allow(deprecated)]
19 use net::IpAddr;
20 use option;
21 use sys::net::netc as c;
22 use sys_common::{FromInner, AsInner, IntoInner};
23 use vec;
24 use iter;
25 use slice;
26
27 /// Representation of a socket address for networking applications.
28 ///
29 /// A socket address can either represent the IPv4 or IPv6 protocol and is
30 /// paired with at least a port number as well. Each protocol may have more
31 /// specific information about the address available to it as well.
32 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
33 #[stable(feature = "rust1", since = "1.0.0")]
34 pub enum SocketAddr {
35     /// An IPv4 socket address which is a (ip, port) combination.
36     #[stable(feature = "rust1", since = "1.0.0")]
37     V4(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] SocketAddrV4),
38     /// An IPv6 socket address
39     #[stable(feature = "rust1", since = "1.0.0")]
40     V6(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] SocketAddrV6),
41 }
42
43 /// An IPv4 socket address which is a (ip, port) combination.
44 #[derive(Copy)]
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct SocketAddrV4 { inner: c::sockaddr_in }
47
48 /// An IPv6 socket address.
49 #[derive(Copy)]
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
52
53 impl SocketAddr {
54     /// Creates a new socket address from the (ip, port) pair.
55     #[unstable(feature = "ip_addr", reason = "recent addition", issue = "27801")]
56     #[rustc_deprecated(reason = "ip type too small a type to pull its weight",
57                        since = "1.6.0")]
58     #[allow(deprecated)]
59     pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
60         match ip {
61             IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
62             IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
63         }
64     }
65
66     /// Returns the IP address associated with this socket address.
67     #[unstable(feature = "ip_addr", reason = "recent addition", issue = "27801")]
68     #[rustc_deprecated(reason = "too small a type to pull its weight",
69                        since = "1.6.0")]
70     #[allow(deprecated)]
71     pub fn ip(&self) -> IpAddr {
72         match *self {
73             SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
74             SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
75         }
76     }
77
78     /// Returns the port number associated with this socket address.
79     #[stable(feature = "rust1", since = "1.0.0")]
80     pub fn port(&self) -> u16 {
81         match *self {
82             SocketAddr::V4(ref a) => a.port(),
83             SocketAddr::V6(ref a) => a.port(),
84         }
85     }
86 }
87
88 impl SocketAddrV4 {
89     /// Creates a new socket address from the (ip, port) pair.
90     #[stable(feature = "rust1", since = "1.0.0")]
91     pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
92         SocketAddrV4 {
93             inner: c::sockaddr_in {
94                 sin_family: c::AF_INET as c::sa_family_t,
95                 sin_port: hton(port),
96                 sin_addr: *ip.as_inner(),
97                 .. unsafe { mem::zeroed() }
98             },
99         }
100     }
101
102     /// Returns the IP address associated with this socket address.
103     #[stable(feature = "rust1", since = "1.0.0")]
104     pub fn ip(&self) -> &Ipv4Addr {
105         unsafe {
106             &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
107         }
108     }
109
110     /// Returns the port number associated with this socket address.
111     #[stable(feature = "rust1", since = "1.0.0")]
112     pub fn port(&self) -> u16 { ntoh(self.inner.sin_port) }
113 }
114
115 impl SocketAddrV6 {
116     /// Creates a new socket address from the ip/port/flowinfo/scope_id
117     /// components.
118     #[stable(feature = "rust1", since = "1.0.0")]
119     pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
120                -> SocketAddrV6 {
121         SocketAddrV6 {
122             inner: c::sockaddr_in6 {
123                 sin6_family: c::AF_INET6 as c::sa_family_t,
124                 sin6_port: hton(port),
125                 sin6_addr: *ip.as_inner(),
126                 sin6_flowinfo: hton(flowinfo),
127                 sin6_scope_id: hton(scope_id),
128                 .. unsafe { mem::zeroed() }
129             },
130         }
131     }
132
133     /// Returns the IP address associated with this socket address.
134     #[stable(feature = "rust1", since = "1.0.0")]
135     pub fn ip(&self) -> &Ipv6Addr {
136         unsafe {
137             &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
138         }
139     }
140
141     /// Returns the port number associated with this socket address.
142     #[stable(feature = "rust1", since = "1.0.0")]
143     pub fn port(&self) -> u16 { ntoh(self.inner.sin6_port) }
144
145     /// Returns the flow information associated with this address,
146     /// corresponding to the `sin6_flowinfo` field in C.
147     #[stable(feature = "rust1", since = "1.0.0")]
148     pub fn flowinfo(&self) -> u32 { ntoh(self.inner.sin6_flowinfo) }
149
150     /// Returns the scope ID associated with this address,
151     /// corresponding to the `sin6_scope_id` field in C.
152     #[stable(feature = "rust1", since = "1.0.0")]
153     pub fn scope_id(&self) -> u32 { ntoh(self.inner.sin6_scope_id) }
154 }
155
156 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
157     fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
158         SocketAddrV4 { inner: addr }
159     }
160 }
161
162 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
163     fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
164         SocketAddrV6 { inner: addr }
165     }
166 }
167
168 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
169     fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
170         match *self {
171             SocketAddr::V4(ref a) => {
172                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
173             }
174             SocketAddr::V6(ref a) => {
175                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
176             }
177         }
178     }
179 }
180
181 #[stable(feature = "rust1", since = "1.0.0")]
182 impl fmt::Display for SocketAddr {
183     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
184         match *self {
185             SocketAddr::V4(ref a) => a.fmt(f),
186             SocketAddr::V6(ref a) => a.fmt(f),
187         }
188     }
189 }
190
191 #[stable(feature = "rust1", since = "1.0.0")]
192 impl fmt::Display for SocketAddrV4 {
193     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
194         write!(f, "{}:{}", self.ip(), self.port())
195     }
196 }
197
198 #[stable(feature = "rust1", since = "1.0.0")]
199 impl fmt::Debug for SocketAddrV4 {
200     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
201         fmt::Display::fmt(self, fmt)
202     }
203 }
204
205 #[stable(feature = "rust1", since = "1.0.0")]
206 impl fmt::Display for SocketAddrV6 {
207     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208         write!(f, "[{}]:{}", self.ip(), self.port())
209     }
210 }
211
212 #[stable(feature = "rust1", since = "1.0.0")]
213 impl fmt::Debug for SocketAddrV6 {
214     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
215         fmt::Display::fmt(self, fmt)
216     }
217 }
218
219 #[stable(feature = "rust1", since = "1.0.0")]
220 impl Clone for SocketAddrV4 {
221     fn clone(&self) -> SocketAddrV4 { *self }
222 }
223 #[stable(feature = "rust1", since = "1.0.0")]
224 impl Clone for SocketAddrV6 {
225     fn clone(&self) -> SocketAddrV6 { *self }
226 }
227
228 #[stable(feature = "rust1", since = "1.0.0")]
229 impl PartialEq for SocketAddrV4 {
230     fn eq(&self, other: &SocketAddrV4) -> bool {
231         self.inner.sin_port == other.inner.sin_port &&
232             self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
233     }
234 }
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl PartialEq for SocketAddrV6 {
237     fn eq(&self, other: &SocketAddrV6) -> bool {
238         self.inner.sin6_port == other.inner.sin6_port &&
239             self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
240             self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
241             self.inner.sin6_scope_id == other.inner.sin6_scope_id
242     }
243 }
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl Eq for SocketAddrV4 {}
246 #[stable(feature = "rust1", since = "1.0.0")]
247 impl Eq for SocketAddrV6 {}
248
249 #[stable(feature = "rust1", since = "1.0.0")]
250 impl hash::Hash for SocketAddrV4 {
251     fn hash<H: hash::Hasher>(&self, s: &mut H) {
252         (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
253     }
254 }
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl hash::Hash for SocketAddrV6 {
257     fn hash<H: hash::Hasher>(&self, s: &mut H) {
258         (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
259          self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
260     }
261 }
262
263 /// A trait for objects which can be converted or resolved to one or more
264 /// `SocketAddr` values.
265 ///
266 /// This trait is used for generic address resolution when constructing network
267 /// objects.  By default it is implemented for the following types:
268 ///
269 ///  * `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` - `to_socket_addrs` is
270 ///    identity function.
271 ///
272 ///  * `(IpvNAddr, u16)` - `to_socket_addrs` constructs `SocketAddr` trivially.
273 ///
274 ///  * `(&str, u16)` - the string should be either a string representation of an
275 ///    IP address expected by `FromStr` implementation for `IpvNAddr` or a host
276 ///    name.
277 ///
278 ///  * `&str` - the string should be either a string representation of a
279 ///    `SocketAddr` as expected by its `FromStr` implementation or a string like
280 ///    `<host_name>:<port>` pair where `<port>` is a `u16` value.
281 ///
282 /// This trait allows constructing network objects like `TcpStream` or
283 /// `UdpSocket` easily with values of various types for the bind/connection
284 /// address. It is needed because sometimes one type is more appropriate than
285 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
286 /// than manual construction of the corresponding `SocketAddr`, but sometimes
287 /// `SocketAddr` value is *the* main source of the address, and converting it to
288 /// some other type (e.g. a string) just for it to be converted back to
289 /// `SocketAddr` in constructor methods is pointless.
290 ///
291 /// Some examples:
292 ///
293 /// ```no_run
294 /// use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
295 ///
296 /// fn main() {
297 ///     let ip = Ipv4Addr::new(127, 0, 0, 1);
298 ///     let port = 12345;
299 ///
300 ///     // The following lines are equivalent modulo possible "localhost" name
301 ///     // resolution differences
302 ///     let tcp_s = TcpStream::connect(SocketAddrV4::new(ip, port));
303 ///     let tcp_s = TcpStream::connect((ip, port));
304 ///     let tcp_s = TcpStream::connect(("127.0.0.1", port));
305 ///     let tcp_s = TcpStream::connect(("localhost", port));
306 ///     let tcp_s = TcpStream::connect("127.0.0.1:12345");
307 ///     let tcp_s = TcpStream::connect("localhost:12345");
308 ///
309 ///     // TcpListener::bind(), UdpSocket::bind() and UdpSocket::send_to()
310 ///     // behave similarly
311 ///     let tcp_l = TcpListener::bind("localhost:12345");
312 ///
313 ///     let mut udp_s = UdpSocket::bind(("127.0.0.1", port)).unwrap();
314 ///     udp_s.send_to(&[7], (ip, 23451)).unwrap();
315 /// }
316 /// ```
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub trait ToSocketAddrs {
319     /// Returned iterator over socket addresses which this type may correspond
320     /// to.
321     #[stable(feature = "rust1", since = "1.0.0")]
322     type Iter: Iterator<Item=SocketAddr>;
323
324     /// Converts this object to an iterator of resolved `SocketAddr`s.
325     ///
326     /// The returned iterator may not actually yield any values depending on the
327     /// outcome of any resolution performed.
328     ///
329     /// Note that this function may block the current thread while resolution is
330     /// performed.
331     ///
332     /// # Errors
333     ///
334     /// Any errors encountered during resolution will be returned as an `Err`.
335     #[stable(feature = "rust1", since = "1.0.0")]
336     fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
337 }
338
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl ToSocketAddrs for SocketAddr {
341     type Iter = option::IntoIter<SocketAddr>;
342     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
343         Ok(Some(*self).into_iter())
344     }
345 }
346
347 #[stable(feature = "rust1", since = "1.0.0")]
348 impl ToSocketAddrs for SocketAddrV4 {
349     type Iter = option::IntoIter<SocketAddr>;
350     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
351         SocketAddr::V4(*self).to_socket_addrs()
352     }
353 }
354
355 #[stable(feature = "rust1", since = "1.0.0")]
356 impl ToSocketAddrs for SocketAddrV6 {
357     type Iter = option::IntoIter<SocketAddr>;
358     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
359         SocketAddr::V6(*self).to_socket_addrs()
360     }
361 }
362
363 #[stable(feature = "rust1", since = "1.0.0")]
364 #[allow(deprecated)]
365 impl ToSocketAddrs for (IpAddr, u16) {
366     type Iter = option::IntoIter<SocketAddr>;
367     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
368         let (ip, port) = *self;
369         match ip {
370             IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
371             IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
372         }
373     }
374 }
375
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl ToSocketAddrs for (Ipv4Addr, u16) {
378     type Iter = option::IntoIter<SocketAddr>;
379     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
380         let (ip, port) = *self;
381         SocketAddrV4::new(ip, port).to_socket_addrs()
382     }
383 }
384
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl ToSocketAddrs for (Ipv6Addr, u16) {
387     type Iter = option::IntoIter<SocketAddr>;
388     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
389         let (ip, port) = *self;
390         SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
391     }
392 }
393
394 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
395     let ips = try!(lookup_host(s));
396     let v: Vec<_> = try!(ips.map(|a| {
397         a.map(|a| {
398             match a {
399                 SocketAddr::V4(ref a) => {
400                     SocketAddr::V4(SocketAddrV4::new(*a.ip(), p))
401                 }
402                 SocketAddr::V6(ref a) => {
403                     SocketAddr::V6(SocketAddrV6::new(*a.ip(), p, a.flowinfo(),
404                                                      a.scope_id()))
405                 }
406             }
407         })
408     }).collect());
409     Ok(v.into_iter())
410 }
411
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl<'a> ToSocketAddrs for (&'a str, u16) {
414     type Iter = vec::IntoIter<SocketAddr>;
415     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
416         let (host, port) = *self;
417
418         // try to parse the host as a regular IP address first
419         if let Ok(addr) = host.parse::<Ipv4Addr>() {
420             let addr = SocketAddrV4::new(addr, port);
421             return Ok(vec![SocketAddr::V4(addr)].into_iter())
422         }
423         if let Ok(addr) = host.parse::<Ipv6Addr>() {
424             let addr = SocketAddrV6::new(addr, port, 0, 0);
425             return Ok(vec![SocketAddr::V6(addr)].into_iter())
426         }
427
428         resolve_socket_addr(host, port)
429     }
430 }
431
432 // accepts strings like 'localhost:12345'
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl ToSocketAddrs for str {
435     type Iter = vec::IntoIter<SocketAddr>;
436     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
437         // try to parse as a regular SocketAddr first
438         match self.parse().ok() {
439             Some(addr) => return Ok(vec![addr].into_iter()),
440             None => {}
441         }
442
443         macro_rules! try_opt {
444             ($e:expr, $msg:expr) => (
445                 match $e {
446                     Some(r) => r,
447                     None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
448                                                       $msg)),
449                 }
450             )
451         }
452
453         // split the string by ':' and convert the second part to u16
454         let mut parts_iter = self.rsplitn(2, ':');
455         let port_str = try_opt!(parts_iter.next(), "invalid socket address");
456         let host = try_opt!(parts_iter.next(), "invalid socket address");
457         let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
458         resolve_socket_addr(host, port)
459     }
460 }
461
462 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
463 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
464     type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
465
466     fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
467         Ok(self.iter().cloned())
468     }
469 }
470
471 #[stable(feature = "rust1", since = "1.0.0")]
472 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
473     type Iter = T::Iter;
474     fn to_socket_addrs(&self) -> io::Result<T::Iter> {
475         (**self).to_socket_addrs()
476     }
477 }
478
479 #[cfg(test)]
480 mod tests {
481     use prelude::v1::*;
482     use net::*;
483     use net::test::{tsa, sa6, sa4};
484
485     #[test]
486     fn to_socket_addr_ipaddr_u16() {
487         let a = Ipv4Addr::new(77, 88, 21, 11);
488         let p = 12345;
489         let e = SocketAddr::V4(SocketAddrV4::new(a, p));
490         assert_eq!(Ok(vec![e]), tsa((a, p)));
491     }
492
493     #[test]
494     fn to_socket_addr_str_u16() {
495         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
496         assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
497
498         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
499         assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
500
501         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
502         assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
503     }
504
505     #[test]
506     fn to_socket_addr_str() {
507         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
508         assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
509
510         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
511         assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
512
513         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
514         assert!(tsa("localhost:23924").unwrap().contains(&a));
515     }
516
517     // FIXME: figure out why this fails on openbsd and bitrig and fix it
518     #[test]
519     #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
520     fn to_socket_addr_str_bad() {
521         assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
522     }
523 }