]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/addr.rs
Rollup merge of #36762 - achanda:sockaddr_type, 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     #[stable(feature = "ip_addr", since = "1.7.0")]
52     pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
53         match ip {
54             IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
55             IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
56         }
57     }
58
59     /// Returns the IP address associated with this socket address.
60     #[stable(feature = "ip_addr", since = "1.7.0")]
61     pub fn ip(&self) -> IpAddr {
62         match *self {
63             SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
64             SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
65         }
66     }
67
68     /// Change the IP address associated with this socket address.
69     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
70     pub fn set_ip(&mut self, new_ip: IpAddr) {
71         // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
72         match (self, new_ip) {
73             (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
74             (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
75             (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
76         }
77     }
78
79     /// Returns the port number associated with this socket address.
80     #[stable(feature = "rust1", since = "1.0.0")]
81     pub fn port(&self) -> u16 {
82         match *self {
83             SocketAddr::V4(ref a) => a.port(),
84             SocketAddr::V6(ref a) => a.port(),
85         }
86     }
87
88     /// Change the port number associated with this socket address.
89     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
90     pub fn set_port(&mut self, new_port: u16) {
91         match *self {
92             SocketAddr::V4(ref mut a) => a.set_port(new_port),
93             SocketAddr::V6(ref mut a) => a.set_port(new_port),
94         }
95     }
96
97     /// Returns true if the IP in this `SocketAddr` is a valid IPv4 address,
98     /// false if it's a valid IPv6 address.
99     #[unstable(feature = "sockaddr_checker", issue = "36949")]
100     pub fn is_ipv4(&self) -> bool {
101         match *self {
102             SocketAddr::V4(_) => true,
103             SocketAddr::V6(_) => false,
104         }
105     }
106
107     /// Returns true if the IP in this `SocketAddr` is a valid IPv6 address,
108     /// false if it's a valid IPv4 address.
109     #[unstable(feature = "sockaddr_checker", issue = "36949")]
110     pub fn is_ipv6(&self) -> bool {
111         match *self {
112             SocketAddr::V4(_) => false,
113             SocketAddr::V6(_) => true,
114         }
115     }
116 }
117
118 impl SocketAddrV4 {
119     /// Creates a new socket address from the (ip, port) pair.
120     #[stable(feature = "rust1", since = "1.0.0")]
121     pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
122         SocketAddrV4 {
123             inner: c::sockaddr_in {
124                 sin_family: c::AF_INET as c::sa_family_t,
125                 sin_port: hton(port),
126                 sin_addr: *ip.as_inner(),
127                 .. unsafe { mem::zeroed() }
128             },
129         }
130     }
131
132     /// Returns the IP address associated with this socket address.
133     #[stable(feature = "rust1", since = "1.0.0")]
134     pub fn ip(&self) -> &Ipv4Addr {
135         unsafe {
136             &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
137         }
138     }
139
140     /// Change the IP address associated with this socket address.
141     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
142     pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
143         self.inner.sin_addr = *new_ip.as_inner()
144     }
145
146     /// Returns the port number associated with this socket address.
147     #[stable(feature = "rust1", since = "1.0.0")]
148     pub fn port(&self) -> u16 {
149         ntoh(self.inner.sin_port)
150     }
151
152     /// Change the port number associated with this socket address.
153     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
154     pub fn set_port(&mut self, new_port: u16) {
155         self.inner.sin_port = hton(new_port);
156     }
157 }
158
159 impl SocketAddrV6 {
160     /// Creates a new socket address from the ip/port/flowinfo/scope_id
161     /// components.
162     #[stable(feature = "rust1", since = "1.0.0")]
163     pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
164                -> SocketAddrV6 {
165         SocketAddrV6 {
166             inner: c::sockaddr_in6 {
167                 sin6_family: c::AF_INET6 as c::sa_family_t,
168                 sin6_port: hton(port),
169                 sin6_addr: *ip.as_inner(),
170                 sin6_flowinfo: flowinfo,
171                 sin6_scope_id: scope_id,
172                 .. unsafe { mem::zeroed() }
173             },
174         }
175     }
176
177     /// Returns the IP address associated with this socket address.
178     #[stable(feature = "rust1", since = "1.0.0")]
179     pub fn ip(&self) -> &Ipv6Addr {
180         unsafe {
181             &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
182         }
183     }
184
185     /// Change the IP address associated with this socket address.
186     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
187     pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
188         self.inner.sin6_addr = *new_ip.as_inner()
189     }
190
191     /// Returns the port number associated with this socket address.
192     #[stable(feature = "rust1", since = "1.0.0")]
193     pub fn port(&self) -> u16 {
194         ntoh(self.inner.sin6_port)
195     }
196
197     /// Change the port number associated with this socket address.
198     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
199     pub fn set_port(&mut self, new_port: u16) {
200         self.inner.sin6_port = hton(new_port);
201     }
202
203     /// Returns the flow information associated with this address,
204     /// corresponding to the `sin6_flowinfo` field in C.
205     #[stable(feature = "rust1", since = "1.0.0")]
206     pub fn flowinfo(&self) -> u32 {
207         self.inner.sin6_flowinfo
208     }
209
210     /// Change the flow information associated with this socket address.
211     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
212     pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
213         self.inner.sin6_flowinfo = new_flowinfo;
214     }
215
216     /// Returns the scope ID associated with this address,
217     /// corresponding to the `sin6_scope_id` field in C.
218     #[stable(feature = "rust1", since = "1.0.0")]
219     pub fn scope_id(&self) -> u32 {
220         self.inner.sin6_scope_id
221     }
222
223     /// Change the scope ID associated with this socket address.
224     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
225     pub fn set_scope_id(&mut self, new_scope_id: u32) {
226         self.inner.sin6_scope_id = new_scope_id;
227     }
228 }
229
230 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
231     fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
232         SocketAddrV4 { inner: addr }
233     }
234 }
235
236 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
237     fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
238         SocketAddrV6 { inner: addr }
239     }
240 }
241
242 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
243     fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
244         match *self {
245             SocketAddr::V4(ref a) => {
246                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
247             }
248             SocketAddr::V6(ref a) => {
249                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
250             }
251         }
252     }
253 }
254
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl fmt::Display for SocketAddr {
257     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
258         match *self {
259             SocketAddr::V4(ref a) => a.fmt(f),
260             SocketAddr::V6(ref a) => a.fmt(f),
261         }
262     }
263 }
264
265 #[stable(feature = "rust1", since = "1.0.0")]
266 impl fmt::Display for SocketAddrV4 {
267     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
268         write!(f, "{}:{}", self.ip(), self.port())
269     }
270 }
271
272 #[stable(feature = "rust1", since = "1.0.0")]
273 impl fmt::Debug for SocketAddrV4 {
274     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
275         fmt::Display::fmt(self, fmt)
276     }
277 }
278
279 #[stable(feature = "rust1", since = "1.0.0")]
280 impl fmt::Display for SocketAddrV6 {
281     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
282         write!(f, "[{}]:{}", self.ip(), self.port())
283     }
284 }
285
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl fmt::Debug for SocketAddrV6 {
288     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
289         fmt::Display::fmt(self, fmt)
290     }
291 }
292
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl Clone for SocketAddrV4 {
295     fn clone(&self) -> SocketAddrV4 { *self }
296 }
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl Clone for SocketAddrV6 {
299     fn clone(&self) -> SocketAddrV6 { *self }
300 }
301
302 #[stable(feature = "rust1", since = "1.0.0")]
303 impl PartialEq for SocketAddrV4 {
304     fn eq(&self, other: &SocketAddrV4) -> bool {
305         self.inner.sin_port == other.inner.sin_port &&
306             self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
307     }
308 }
309 #[stable(feature = "rust1", since = "1.0.0")]
310 impl PartialEq for SocketAddrV6 {
311     fn eq(&self, other: &SocketAddrV6) -> bool {
312         self.inner.sin6_port == other.inner.sin6_port &&
313             self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
314             self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
315             self.inner.sin6_scope_id == other.inner.sin6_scope_id
316     }
317 }
318 #[stable(feature = "rust1", since = "1.0.0")]
319 impl Eq for SocketAddrV4 {}
320 #[stable(feature = "rust1", since = "1.0.0")]
321 impl Eq for SocketAddrV6 {}
322
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl hash::Hash for SocketAddrV4 {
325     fn hash<H: hash::Hasher>(&self, s: &mut H) {
326         (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
327     }
328 }
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl hash::Hash for SocketAddrV6 {
331     fn hash<H: hash::Hasher>(&self, s: &mut H) {
332         (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
333          self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
334     }
335 }
336
337 /// A trait for objects which can be converted or resolved to one or more
338 /// `SocketAddr` values.
339 ///
340 /// This trait is used for generic address resolution when constructing network
341 /// objects.  By default it is implemented for the following types:
342 ///
343 ///  * `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` - `to_socket_addrs` is
344 ///    identity function.
345 ///
346 ///  * `(IpvNAddr, u16)` - `to_socket_addrs` constructs `SocketAddr` trivially.
347 ///
348 ///  * `(&str, u16)` - the string should be either a string representation of an
349 ///    IP address expected by `FromStr` implementation for `IpvNAddr` or a host
350 ///    name.
351 ///
352 ///  * `&str` - the string should be either a string representation of a
353 ///    `SocketAddr` as expected by its `FromStr` implementation or a string like
354 ///    `<host_name>:<port>` pair where `<port>` is a `u16` value.
355 ///
356 /// This trait allows constructing network objects like `TcpStream` or
357 /// `UdpSocket` easily with values of various types for the bind/connection
358 /// address. It is needed because sometimes one type is more appropriate than
359 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
360 /// than manual construction of the corresponding `SocketAddr`, but sometimes
361 /// `SocketAddr` value is *the* main source of the address, and converting it to
362 /// some other type (e.g. a string) just for it to be converted back to
363 /// `SocketAddr` in constructor methods is pointless.
364 ///
365 /// Addresses returned by the operating system that are not IP addresses are
366 /// silently ignored.
367 ///
368 /// Some examples:
369 ///
370 /// ```no_run
371 /// use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
372 ///
373 /// fn main() {
374 ///     let ip = Ipv4Addr::new(127, 0, 0, 1);
375 ///     let port = 12345;
376 ///
377 ///     // The following lines are equivalent modulo possible "localhost" name
378 ///     // resolution differences
379 ///     let tcp_s = TcpStream::connect(SocketAddrV4::new(ip, port));
380 ///     let tcp_s = TcpStream::connect((ip, port));
381 ///     let tcp_s = TcpStream::connect(("127.0.0.1", port));
382 ///     let tcp_s = TcpStream::connect(("localhost", port));
383 ///     let tcp_s = TcpStream::connect("127.0.0.1:12345");
384 ///     let tcp_s = TcpStream::connect("localhost:12345");
385 ///
386 ///     // TcpListener::bind(), UdpSocket::bind() and UdpSocket::send_to()
387 ///     // behave similarly
388 ///     let tcp_l = TcpListener::bind("localhost:12345");
389 ///
390 ///     let mut udp_s = UdpSocket::bind(("127.0.0.1", port)).unwrap();
391 ///     udp_s.send_to(&[7], (ip, 23451)).unwrap();
392 /// }
393 /// ```
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub trait ToSocketAddrs {
396     /// Returned iterator over socket addresses which this type may correspond
397     /// to.
398     #[stable(feature = "rust1", since = "1.0.0")]
399     type Iter: Iterator<Item=SocketAddr>;
400
401     /// Converts this object to an iterator of resolved `SocketAddr`s.
402     ///
403     /// The returned iterator may not actually yield any values depending on the
404     /// outcome of any resolution performed.
405     ///
406     /// Note that this function may block the current thread while resolution is
407     /// performed.
408     ///
409     /// # Errors
410     ///
411     /// Any errors encountered during resolution will be returned as an `Err`.
412     #[stable(feature = "rust1", since = "1.0.0")]
413     fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
414 }
415
416 #[stable(feature = "rust1", since = "1.0.0")]
417 impl ToSocketAddrs for SocketAddr {
418     type Iter = option::IntoIter<SocketAddr>;
419     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
420         Ok(Some(*self).into_iter())
421     }
422 }
423
424 #[stable(feature = "rust1", since = "1.0.0")]
425 impl ToSocketAddrs for SocketAddrV4 {
426     type Iter = option::IntoIter<SocketAddr>;
427     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
428         SocketAddr::V4(*self).to_socket_addrs()
429     }
430 }
431
432 #[stable(feature = "rust1", since = "1.0.0")]
433 impl ToSocketAddrs for SocketAddrV6 {
434     type Iter = option::IntoIter<SocketAddr>;
435     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
436         SocketAddr::V6(*self).to_socket_addrs()
437     }
438 }
439
440 #[stable(feature = "rust1", since = "1.0.0")]
441 impl ToSocketAddrs for (IpAddr, u16) {
442     type Iter = option::IntoIter<SocketAddr>;
443     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
444         let (ip, port) = *self;
445         match ip {
446             IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
447             IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
448         }
449     }
450 }
451
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl ToSocketAddrs for (Ipv4Addr, u16) {
454     type Iter = option::IntoIter<SocketAddr>;
455     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
456         let (ip, port) = *self;
457         SocketAddrV4::new(ip, port).to_socket_addrs()
458     }
459 }
460
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl ToSocketAddrs for (Ipv6Addr, u16) {
463     type Iter = option::IntoIter<SocketAddr>;
464     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
465         let (ip, port) = *self;
466         SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
467     }
468 }
469
470 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
471     let ips = lookup_host(s)?;
472     let v: Vec<_> = ips.map(|mut a| { a.set_port(p); a }).collect();
473     Ok(v.into_iter())
474 }
475
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl<'a> ToSocketAddrs for (&'a str, u16) {
478     type Iter = vec::IntoIter<SocketAddr>;
479     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
480         let (host, port) = *self;
481
482         // try to parse the host as a regular IP address first
483         if let Ok(addr) = host.parse::<Ipv4Addr>() {
484             let addr = SocketAddrV4::new(addr, port);
485             return Ok(vec![SocketAddr::V4(addr)].into_iter())
486         }
487         if let Ok(addr) = host.parse::<Ipv6Addr>() {
488             let addr = SocketAddrV6::new(addr, port, 0, 0);
489             return Ok(vec![SocketAddr::V6(addr)].into_iter())
490         }
491
492         resolve_socket_addr(host, port)
493     }
494 }
495
496 // accepts strings like 'localhost:12345'
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl ToSocketAddrs for str {
499     type Iter = vec::IntoIter<SocketAddr>;
500     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
501         // try to parse as a regular SocketAddr first
502         if let Some(addr) = self.parse().ok() {
503             return Ok(vec![addr].into_iter());
504         }
505
506         macro_rules! try_opt {
507             ($e:expr, $msg:expr) => (
508                 match $e {
509                     Some(r) => r,
510                     None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
511                                                       $msg)),
512                 }
513             )
514         }
515
516         // split the string by ':' and convert the second part to u16
517         let mut parts_iter = self.rsplitn(2, ':');
518         let port_str = try_opt!(parts_iter.next(), "invalid socket address");
519         let host = try_opt!(parts_iter.next(), "invalid socket address");
520         let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
521         resolve_socket_addr(host, port)
522     }
523 }
524
525 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
526 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
527     type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
528
529     fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
530         Ok(self.iter().cloned())
531     }
532 }
533
534 #[stable(feature = "rust1", since = "1.0.0")]
535 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
536     type Iter = T::Iter;
537     fn to_socket_addrs(&self) -> io::Result<T::Iter> {
538         (**self).to_socket_addrs()
539     }
540 }
541
542 #[cfg(all(test, not(target_os = "emscripten")))]
543 mod tests {
544     use net::*;
545     use net::test::{tsa, sa6, sa4};
546
547     #[test]
548     fn to_socket_addr_ipaddr_u16() {
549         let a = Ipv4Addr::new(77, 88, 21, 11);
550         let p = 12345;
551         let e = SocketAddr::V4(SocketAddrV4::new(a, p));
552         assert_eq!(Ok(vec![e]), tsa((a, p)));
553     }
554
555     #[test]
556     fn to_socket_addr_str_u16() {
557         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
558         assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
559
560         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
561         assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
562
563         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
564         assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
565     }
566
567     #[test]
568     fn to_socket_addr_str() {
569         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
570         assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
571
572         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
573         assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
574
575         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
576         assert!(tsa("localhost:23924").unwrap().contains(&a));
577     }
578
579     // FIXME: figure out why this fails on openbsd and bitrig and fix it
580     #[test]
581     #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
582     fn to_socket_addr_str_bad() {
583         assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
584     }
585
586     #[test]
587     fn set_ip() {
588         fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
589         fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
590
591         let mut v4 = SocketAddrV4::new(ip4(11), 80);
592         assert_eq!(v4.ip(), &ip4(11));
593         v4.set_ip(ip4(12));
594         assert_eq!(v4.ip(), &ip4(12));
595
596         let mut addr = SocketAddr::V4(v4);
597         assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
598         addr.set_ip(IpAddr::V4(ip4(13)));
599         assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
600         addr.set_ip(IpAddr::V6(ip6(14)));
601         assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
602
603         let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
604         assert_eq!(v6.ip(), &ip6(1));
605         v6.set_ip(ip6(2));
606         assert_eq!(v6.ip(), &ip6(2));
607
608         let mut addr = SocketAddr::V6(v6);
609         assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
610         addr.set_ip(IpAddr::V6(ip6(3)));
611         assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
612         addr.set_ip(IpAddr::V4(ip4(4)));
613         assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
614     }
615
616     #[test]
617     fn set_port() {
618         let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
619         assert_eq!(v4.port(), 80);
620         v4.set_port(443);
621         assert_eq!(v4.port(), 443);
622
623         let mut addr = SocketAddr::V4(v4);
624         assert_eq!(addr.port(), 443);
625         addr.set_port(8080);
626         assert_eq!(addr.port(), 8080);
627
628         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
629         assert_eq!(v6.port(), 80);
630         v6.set_port(443);
631         assert_eq!(v6.port(), 443);
632
633         let mut addr = SocketAddr::V6(v6);
634         assert_eq!(addr.port(), 443);
635         addr.set_port(8080);
636         assert_eq!(addr.port(), 8080);
637     }
638
639     #[test]
640     fn set_flowinfo() {
641         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
642         assert_eq!(v6.flowinfo(), 10);
643         v6.set_flowinfo(20);
644         assert_eq!(v6.flowinfo(), 20);
645     }
646
647     #[test]
648     fn set_scope_id() {
649         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
650         assert_eq!(v6.scope_id(), 10);
651         v6.set_scope_id(20);
652         assert_eq!(v6.scope_id(), 20);
653     }
654
655     #[test]
656     fn is_v4() {
657         let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
658         assert!(v4.is_ipv4());
659         assert!(!v4.is_ipv6());
660     }
661
662     #[test]
663     fn is_v6() {
664         let v6 = SocketAddr::V6(SocketAddrV6::new(
665                 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
666         assert!(!v6.is_ipv4());
667         assert!(v6.is_ipv6());
668     }
669 }