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