]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/addr.rs
Rollup merge of #49767 - ecstatic-morse:ptr-docs, r=steveklabnik
[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::{ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
16 use option;
17 use sys::net::netc as c;
18 use sys_common::{FromInner, AsInner, IntoInner};
19 use sys_common::net::lookup_host;
20 use vec;
21 use iter;
22 use slice;
23
24 /// An internet socket address, either IPv4 or IPv6.
25 ///
26 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
27 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
28 /// [`SocketAddrV6`]'s respective documentation for more details.
29 ///
30 /// The size of a `SocketAddr` instance may vary depending on the target operating
31 /// system.
32 ///
33 /// [IP address]: ../../std/net/enum.IpAddr.html
34 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
35 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
36 ///
37 /// # Examples
38 ///
39 /// ```
40 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
41 ///
42 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
43 ///
44 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
45 /// assert_eq!(socket.port(), 8080);
46 /// assert_eq!(socket.is_ipv4(), true);
47 /// ```
48 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub enum SocketAddr {
51     /// An IPv4 socket address.
52     #[stable(feature = "rust1", since = "1.0.0")]
53     V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
54     /// An IPv6 socket address.
55     #[stable(feature = "rust1", since = "1.0.0")]
56     V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
57 }
58
59 /// An IPv4 socket address.
60 ///
61 /// IPv4 socket addresses consist of an [IPv4 address] and a 16-bit port number, as
62 /// stated in [IETF RFC 793].
63 ///
64 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
65 ///
66 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
67 /// system.
68 ///
69 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
70 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
71 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
72 ///
73 /// # Examples
74 ///
75 /// ```
76 /// use std::net::{Ipv4Addr, SocketAddrV4};
77 ///
78 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
79 ///
80 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
81 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
82 /// assert_eq!(socket.port(), 8080);
83 /// ```
84 #[derive(Copy)]
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct SocketAddrV4 { inner: c::sockaddr_in }
87
88 /// An IPv6 socket address.
89 ///
90 /// IPv6 socket addresses consist of an [Ipv6 address], a 16-bit port number, as well
91 /// as fields containing the traffic class, the flow label, and a scope identifier
92 /// (see [IETF RFC 2553, Section 3.3] for more details).
93 ///
94 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
95 ///
96 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
97 /// system.
98 ///
99 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
100 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
101 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
102 ///
103 /// # Examples
104 ///
105 /// ```
106 /// use std::net::{Ipv6Addr, SocketAddrV6};
107 ///
108 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
109 ///
110 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
111 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
112 /// assert_eq!(socket.port(), 8080);
113 /// ```
114 #[derive(Copy)]
115 #[stable(feature = "rust1", since = "1.0.0")]
116 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
117
118 impl SocketAddr {
119     /// Creates a new socket address from an [IP address] and a port number.
120     ///
121     /// [IP address]: ../../std/net/enum.IpAddr.html
122     ///
123     /// # Examples
124     ///
125     /// ```
126     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
127     ///
128     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
129     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
130     /// assert_eq!(socket.port(), 8080);
131     /// ```
132     #[stable(feature = "ip_addr", since = "1.7.0")]
133     pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
134         match ip {
135             IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
136             IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
137         }
138     }
139
140     /// Returns the IP address associated with this socket address.
141     ///
142     /// # Examples
143     ///
144     /// ```
145     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
146     ///
147     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
148     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
149     /// ```
150     #[stable(feature = "ip_addr", since = "1.7.0")]
151     pub fn ip(&self) -> IpAddr {
152         match *self {
153             SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
154             SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
155         }
156     }
157
158     /// Changes the IP address associated with this socket address.
159     ///
160     /// # Examples
161     ///
162     /// ```
163     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
164     ///
165     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
166     /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
167     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
168     /// ```
169     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
170     pub fn set_ip(&mut self, new_ip: IpAddr) {
171         // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
172         match (self, new_ip) {
173             (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
174             (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
175             (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
176         }
177     }
178
179     /// Returns the port number associated with this socket address.
180     ///
181     /// # Examples
182     ///
183     /// ```
184     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
185     ///
186     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
187     /// assert_eq!(socket.port(), 8080);
188     /// ```
189     #[stable(feature = "rust1", since = "1.0.0")]
190     pub fn port(&self) -> u16 {
191         match *self {
192             SocketAddr::V4(ref a) => a.port(),
193             SocketAddr::V6(ref a) => a.port(),
194         }
195     }
196
197     /// Changes the port number associated with this socket address.
198     ///
199     /// # Examples
200     ///
201     /// ```
202     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
203     ///
204     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
205     /// socket.set_port(1025);
206     /// assert_eq!(socket.port(), 1025);
207     /// ```
208     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
209     pub fn set_port(&mut self, new_port: u16) {
210         match *self {
211             SocketAddr::V4(ref mut a) => a.set_port(new_port),
212             SocketAddr::V6(ref mut a) => a.set_port(new_port),
213         }
214     }
215
216     /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
217     /// [IPv4 address], and [`false`] otherwise.
218     ///
219     /// [`true`]: ../../std/primitive.bool.html
220     /// [`false`]: ../../std/primitive.bool.html
221     /// [IP address]: ../../std/net/enum.IpAddr.html
222     /// [IPv4 address]: ../../std/net/enum.IpAddr.html#variant.V4
223     ///
224     /// # Examples
225     ///
226     /// ```
227     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
228     ///
229     /// fn main() {
230     ///     let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
231     ///     assert_eq!(socket.is_ipv4(), true);
232     ///     assert_eq!(socket.is_ipv6(), false);
233     /// }
234     /// ```
235     #[stable(feature = "sockaddr_checker", since = "1.16.0")]
236     pub fn is_ipv4(&self) -> bool {
237         match *self {
238             SocketAddr::V4(_) => true,
239             SocketAddr::V6(_) => false,
240         }
241     }
242
243     /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
244     /// [IPv6 address], and [`false`] otherwise.
245     ///
246     /// [`true`]: ../../std/primitive.bool.html
247     /// [`false`]: ../../std/primitive.bool.html
248     /// [IP address]: ../../std/net/enum.IpAddr.html
249     /// [IPv6 address]: ../../std/net/enum.IpAddr.html#variant.V6
250     ///
251     /// # Examples
252     ///
253     /// ```
254     /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
255     ///
256     /// fn main() {
257     ///     let socket = SocketAddr::new(
258     ///                      IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
259     ///     assert_eq!(socket.is_ipv4(), false);
260     ///     assert_eq!(socket.is_ipv6(), true);
261     /// }
262     /// ```
263     #[stable(feature = "sockaddr_checker", since = "1.16.0")]
264     pub fn is_ipv6(&self) -> bool {
265         match *self {
266             SocketAddr::V4(_) => false,
267             SocketAddr::V6(_) => true,
268         }
269     }
270 }
271
272 impl SocketAddrV4 {
273     /// Creates a new socket address from an [IPv4 address] and a port number.
274     ///
275     /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
276     ///
277     /// # Examples
278     ///
279     /// ```
280     /// use std::net::{SocketAddrV4, Ipv4Addr};
281     ///
282     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
283     /// ```
284     #[stable(feature = "rust1", since = "1.0.0")]
285     pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
286         SocketAddrV4 {
287             inner: c::sockaddr_in {
288                 sin_family: c::AF_INET as c::sa_family_t,
289                 sin_port: hton(port),
290                 sin_addr: *ip.as_inner(),
291                 .. unsafe { mem::zeroed() }
292             },
293         }
294     }
295
296     /// Returns the IP address associated with this socket address.
297     ///
298     /// # Examples
299     ///
300     /// ```
301     /// use std::net::{SocketAddrV4, Ipv4Addr};
302     ///
303     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
304     /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
305     /// ```
306     #[stable(feature = "rust1", since = "1.0.0")]
307     pub fn ip(&self) -> &Ipv4Addr {
308         unsafe {
309             &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
310         }
311     }
312
313     /// Changes the IP address associated with this socket address.
314     ///
315     /// # Examples
316     ///
317     /// ```
318     /// use std::net::{SocketAddrV4, Ipv4Addr};
319     ///
320     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
321     /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
322     /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
323     /// ```
324     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
325     pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
326         self.inner.sin_addr = *new_ip.as_inner()
327     }
328
329     /// Returns the port number associated with this socket address.
330     ///
331     /// # Examples
332     ///
333     /// ```
334     /// use std::net::{SocketAddrV4, Ipv4Addr};
335     ///
336     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
337     /// assert_eq!(socket.port(), 8080);
338     /// ```
339     #[stable(feature = "rust1", since = "1.0.0")]
340     pub fn port(&self) -> u16 {
341         ntoh(self.inner.sin_port)
342     }
343
344     /// Changes the port number associated with this socket address.
345     ///
346     /// # Examples
347     ///
348     /// ```
349     /// use std::net::{SocketAddrV4, Ipv4Addr};
350     ///
351     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
352     /// socket.set_port(4242);
353     /// assert_eq!(socket.port(), 4242);
354     /// ```
355     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
356     pub fn set_port(&mut self, new_port: u16) {
357         self.inner.sin_port = hton(new_port);
358     }
359 }
360
361 impl SocketAddrV6 {
362     /// Creates a new socket address from an [IPv6 address], a 16-bit port number,
363     /// and the `flowinfo` and `scope_id` fields.
364     ///
365     /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
366     /// parameters, see [IETF RFC 2553, Section 3.3].
367     ///
368     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
369     /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
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, 0, 0);
377     /// ```
378     #[stable(feature = "rust1", since = "1.0.0")]
379     pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
380                -> SocketAddrV6 {
381         SocketAddrV6 {
382             inner: c::sockaddr_in6 {
383                 sin6_family: c::AF_INET6 as c::sa_family_t,
384                 sin6_port: hton(port),
385                 sin6_addr: *ip.as_inner(),
386                 sin6_flowinfo: flowinfo,
387                 sin6_scope_id: scope_id,
388                 .. unsafe { mem::zeroed() }
389             },
390         }
391     }
392
393     /// Returns the IP address associated with this socket address.
394     ///
395     /// # Examples
396     ///
397     /// ```
398     /// use std::net::{SocketAddrV6, Ipv6Addr};
399     ///
400     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
401     /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
402     /// ```
403     #[stable(feature = "rust1", since = "1.0.0")]
404     pub fn ip(&self) -> &Ipv6Addr {
405         unsafe {
406             &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
407         }
408     }
409
410     /// Changes the IP address associated with this socket address.
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// use std::net::{SocketAddrV6, Ipv6Addr};
416     ///
417     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
418     /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
419     /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
420     /// ```
421     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
422     pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
423         self.inner.sin6_addr = *new_ip.as_inner()
424     }
425
426     /// Returns the port number associated with this socket address.
427     ///
428     /// # Examples
429     ///
430     /// ```
431     /// use std::net::{SocketAddrV6, Ipv6Addr};
432     ///
433     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
434     /// assert_eq!(socket.port(), 8080);
435     /// ```
436     #[stable(feature = "rust1", since = "1.0.0")]
437     pub fn port(&self) -> u16 {
438         ntoh(self.inner.sin6_port)
439     }
440
441     /// Changes the port number associated with this socket address.
442     ///
443     /// # Examples
444     ///
445     /// ```
446     /// use std::net::{SocketAddrV6, Ipv6Addr};
447     ///
448     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
449     /// socket.set_port(4242);
450     /// assert_eq!(socket.port(), 4242);
451     /// ```
452     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
453     pub fn set_port(&mut self, new_port: u16) {
454         self.inner.sin6_port = hton(new_port);
455     }
456
457     /// Returns the flow information associated with this address.
458     ///
459     /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
460     /// as specified in [IETF RFC 2553, Section 3.3].
461     /// It combines information about the flow label and the traffic class as specified
462     /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
463     ///
464     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
465     /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
466     /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
467     /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
468     ///
469     /// # Examples
470     ///
471     /// ```
472     /// use std::net::{SocketAddrV6, Ipv6Addr};
473     ///
474     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
475     /// assert_eq!(socket.flowinfo(), 10);
476     /// ```
477     #[stable(feature = "rust1", since = "1.0.0")]
478     pub fn flowinfo(&self) -> u32 {
479         self.inner.sin6_flowinfo
480     }
481
482     /// Changes the flow information associated with this socket address.
483     ///
484     /// See the [`flowinfo`] method's documentation for more details.
485     ///
486     /// [`flowinfo`]: #method.flowinfo
487     ///
488     /// # Examples
489     ///
490     /// ```
491     /// use std::net::{SocketAddrV6, Ipv6Addr};
492     ///
493     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
494     /// socket.set_flowinfo(56);
495     /// assert_eq!(socket.flowinfo(), 56);
496     /// ```
497     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
498     pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
499         self.inner.sin6_flowinfo = new_flowinfo;
500     }
501
502     /// Returns the scope ID associated with this address.
503     ///
504     /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
505     /// as specified in [IETF RFC 2553, Section 3.3].
506     ///
507     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
508     ///
509     /// # Examples
510     ///
511     /// ```
512     /// use std::net::{SocketAddrV6, Ipv6Addr};
513     ///
514     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
515     /// assert_eq!(socket.scope_id(), 78);
516     /// ```
517     #[stable(feature = "rust1", since = "1.0.0")]
518     pub fn scope_id(&self) -> u32 {
519         self.inner.sin6_scope_id
520     }
521
522     /// Change the scope ID associated with this socket address.
523     ///
524     /// See the [`scope_id`] method's documentation for more details.
525     ///
526     /// [`scope_id`]: #method.scope_id
527     ///
528     /// # Examples
529     ///
530     /// ```
531     /// use std::net::{SocketAddrV6, Ipv6Addr};
532     ///
533     /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
534     /// socket.set_scope_id(42);
535     /// assert_eq!(socket.scope_id(), 42);
536     /// ```
537     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
538     pub fn set_scope_id(&mut self, new_scope_id: u32) {
539         self.inner.sin6_scope_id = new_scope_id;
540     }
541 }
542
543 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
544     fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
545         SocketAddrV4 { inner: addr }
546     }
547 }
548
549 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
550     fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
551         SocketAddrV6 { inner: addr }
552     }
553 }
554
555 #[stable(feature = "ip_from_ip", since = "1.16.0")]
556 impl From<SocketAddrV4> for SocketAddr {
557     fn from(sock4: SocketAddrV4) -> SocketAddr {
558         SocketAddr::V4(sock4)
559     }
560 }
561
562 #[stable(feature = "ip_from_ip", since = "1.16.0")]
563 impl From<SocketAddrV6> for SocketAddr {
564     fn from(sock6: SocketAddrV6) -> SocketAddr {
565         SocketAddr::V6(sock6)
566     }
567 }
568
569 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
570 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
571     fn from(pieces: (I, u16)) -> SocketAddr {
572         SocketAddr::new(pieces.0.into(), pieces.1)
573     }
574 }
575
576 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
577     fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
578         match *self {
579             SocketAddr::V4(ref a) => {
580                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
581             }
582             SocketAddr::V6(ref a) => {
583                 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
584             }
585         }
586     }
587 }
588
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl fmt::Display for SocketAddr {
591     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
592         match *self {
593             SocketAddr::V4(ref a) => a.fmt(f),
594             SocketAddr::V6(ref a) => a.fmt(f),
595         }
596     }
597 }
598
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl fmt::Display for SocketAddrV4 {
601     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
602         write!(f, "{}:{}", self.ip(), self.port())
603     }
604 }
605
606 #[stable(feature = "rust1", since = "1.0.0")]
607 impl fmt::Debug for SocketAddrV4 {
608     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
609         fmt::Display::fmt(self, fmt)
610     }
611 }
612
613 #[stable(feature = "rust1", since = "1.0.0")]
614 impl fmt::Display for SocketAddrV6 {
615     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
616         write!(f, "[{}]:{}", self.ip(), self.port())
617     }
618 }
619
620 #[stable(feature = "rust1", since = "1.0.0")]
621 impl fmt::Debug for SocketAddrV6 {
622     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
623         fmt::Display::fmt(self, fmt)
624     }
625 }
626
627 #[stable(feature = "rust1", since = "1.0.0")]
628 impl Clone for SocketAddrV4 {
629     fn clone(&self) -> SocketAddrV4 { *self }
630 }
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl Clone for SocketAddrV6 {
633     fn clone(&self) -> SocketAddrV6 { *self }
634 }
635
636 #[stable(feature = "rust1", since = "1.0.0")]
637 impl PartialEq for SocketAddrV4 {
638     fn eq(&self, other: &SocketAddrV4) -> bool {
639         self.inner.sin_port == other.inner.sin_port &&
640             self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
641     }
642 }
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl PartialEq for SocketAddrV6 {
645     fn eq(&self, other: &SocketAddrV6) -> bool {
646         self.inner.sin6_port == other.inner.sin6_port &&
647             self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
648             self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
649             self.inner.sin6_scope_id == other.inner.sin6_scope_id
650     }
651 }
652 #[stable(feature = "rust1", since = "1.0.0")]
653 impl Eq for SocketAddrV4 {}
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl Eq for SocketAddrV6 {}
656
657 #[stable(feature = "rust1", since = "1.0.0")]
658 impl hash::Hash for SocketAddrV4 {
659     fn hash<H: hash::Hasher>(&self, s: &mut H) {
660         (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
661     }
662 }
663 #[stable(feature = "rust1", since = "1.0.0")]
664 impl hash::Hash for SocketAddrV6 {
665     fn hash<H: hash::Hasher>(&self, s: &mut H) {
666         (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
667          self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
668     }
669 }
670
671 /// A trait for objects which can be converted or resolved to one or more
672 /// [`SocketAddr`] values.
673 ///
674 /// This trait is used for generic address resolution when constructing network
675 /// objects.  By default it is implemented for the following types:
676 ///
677 ///  * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
678 ///
679 ///  * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
680 ///    `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
681 ///    [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
682 ///
683 ///  * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
684 ///    of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
685 ///    name.
686 ///
687 ///  * [`&str`]: the string should be either a string representation of a
688 ///    [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
689 ///    `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
690 ///
691 /// This trait allows constructing network objects like [`TcpStream`] or
692 /// [`UdpSocket`] easily with values of various types for the bind/connection
693 /// address. It is needed because sometimes one type is more appropriate than
694 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
695 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
696 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
697 /// some other type (e.g. a string) just for it to be converted back to
698 /// [`SocketAddr`] in constructor methods is pointless.
699 ///
700 /// Addresses returned by the operating system that are not IP addresses are
701 /// silently ignored.
702 ///
703 /// [`FromStr`]: ../../std/str/trait.FromStr.html
704 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
705 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
706 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
707 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
708 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
709 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
710 /// [`&str`]: ../../std/primitive.str.html
711 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
712 /// [`to_socket_addrs`]: #tymethod.to_socket_addrs
713 /// [`UdpSocket`]: ../../std/net/struct.UdpSocket.html
714 /// [`u16`]: ../../std/primitive.u16.html
715 ///
716 /// # Examples
717 ///
718 /// Creating a [`SocketAddr`] iterator that yields one item:
719 ///
720 /// ```
721 /// use std::net::{ToSocketAddrs, SocketAddr};
722 ///
723 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
724 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
725 ///
726 /// assert_eq!(Some(addr), addrs_iter.next());
727 /// assert!(addrs_iter.next().is_none());
728 /// ```
729 ///
730 /// Creating a [`SocketAddr`] iterator from a hostname:
731 ///
732 /// ```no_run
733 /// use std::net::{SocketAddr, ToSocketAddrs};
734 ///
735 /// // assuming 'localhost' resolves to 127.0.0.1
736 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
737 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
738 /// assert!(addrs_iter.next().is_none());
739 ///
740 /// // assuming 'foo' does not resolve
741 /// assert!("foo:443".to_socket_addrs().is_err());
742 /// ```
743 ///
744 /// Creating a [`SocketAddr`] iterator that yields multiple items:
745 ///
746 /// ```
747 /// use std::net::{SocketAddr, ToSocketAddrs};
748 ///
749 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
750 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
751 /// let addrs = vec![addr1, addr2];
752 ///
753 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
754 ///
755 /// assert_eq!(Some(addr1), addrs_iter.next());
756 /// assert_eq!(Some(addr2), addrs_iter.next());
757 /// assert!(addrs_iter.next().is_none());
758 /// ```
759 ///
760 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
761 /// socket address `&str` (missing the port):
762 ///
763 /// ```
764 /// use std::io;
765 /// use std::net::ToSocketAddrs;
766 ///
767 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
768 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
769 /// ```
770 ///
771 /// [`TcpStream::connect`] is an example of an function that utilizes
772 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
773 /// different types:
774 ///
775 /// ```no_run
776 /// use std::net::{TcpStream, Ipv4Addr};
777 ///
778 /// let stream = TcpStream::connect(("127.0.0.1", 443));
779 /// // or
780 /// let stream = TcpStream::connect("127.0.0.1:443");
781 /// // or
782 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
783 /// ```
784 ///
785 /// [`TcpStream::connect`]: ../../std/net/struct.TcpStream.html#method.connect
786 #[stable(feature = "rust1", since = "1.0.0")]
787 pub trait ToSocketAddrs {
788     /// Returned iterator over socket addresses which this type may correspond
789     /// to.
790     #[stable(feature = "rust1", since = "1.0.0")]
791     type Iter: Iterator<Item=SocketAddr>;
792
793     /// Converts this object to an iterator of resolved `SocketAddr`s.
794     ///
795     /// The returned iterator may not actually yield any values depending on the
796     /// outcome of any resolution performed.
797     ///
798     /// Note that this function may block the current thread while resolution is
799     /// performed.
800     #[stable(feature = "rust1", since = "1.0.0")]
801     fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
802 }
803
804 #[stable(feature = "rust1", since = "1.0.0")]
805 impl ToSocketAddrs for SocketAddr {
806     type Iter = option::IntoIter<SocketAddr>;
807     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
808         Ok(Some(*self).into_iter())
809     }
810 }
811
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl ToSocketAddrs for SocketAddrV4 {
814     type Iter = option::IntoIter<SocketAddr>;
815     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
816         SocketAddr::V4(*self).to_socket_addrs()
817     }
818 }
819
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl ToSocketAddrs for SocketAddrV6 {
822     type Iter = option::IntoIter<SocketAddr>;
823     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
824         SocketAddr::V6(*self).to_socket_addrs()
825     }
826 }
827
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl ToSocketAddrs for (IpAddr, u16) {
830     type Iter = option::IntoIter<SocketAddr>;
831     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
832         let (ip, port) = *self;
833         match ip {
834             IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
835             IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
836         }
837     }
838 }
839
840 #[stable(feature = "rust1", since = "1.0.0")]
841 impl ToSocketAddrs for (Ipv4Addr, u16) {
842     type Iter = option::IntoIter<SocketAddr>;
843     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
844         let (ip, port) = *self;
845         SocketAddrV4::new(ip, port).to_socket_addrs()
846     }
847 }
848
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl ToSocketAddrs for (Ipv6Addr, u16) {
851     type Iter = option::IntoIter<SocketAddr>;
852     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
853         let (ip, port) = *self;
854         SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
855     }
856 }
857
858 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
859     let ips = lookup_host(s)?;
860     let v: Vec<_> = ips.map(|mut a| { a.set_port(p); a }).collect();
861     Ok(v.into_iter())
862 }
863
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl<'a> ToSocketAddrs for (&'a str, u16) {
866     type Iter = vec::IntoIter<SocketAddr>;
867     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
868         let (host, port) = *self;
869
870         // try to parse the host as a regular IP address first
871         if let Ok(addr) = host.parse::<Ipv4Addr>() {
872             let addr = SocketAddrV4::new(addr, port);
873             return Ok(vec![SocketAddr::V4(addr)].into_iter())
874         }
875         if let Ok(addr) = host.parse::<Ipv6Addr>() {
876             let addr = SocketAddrV6::new(addr, port, 0, 0);
877             return Ok(vec![SocketAddr::V6(addr)].into_iter())
878         }
879
880         resolve_socket_addr(host, port)
881     }
882 }
883
884 // accepts strings like 'localhost:12345'
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl ToSocketAddrs for str {
887     type Iter = vec::IntoIter<SocketAddr>;
888     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
889         // try to parse as a regular SocketAddr first
890         if let Some(addr) = self.parse().ok() {
891             return Ok(vec![addr].into_iter());
892         }
893
894         macro_rules! try_opt {
895             ($e:expr, $msg:expr) => (
896                 match $e {
897                     Some(r) => r,
898                     None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
899                                                       $msg)),
900                 }
901             )
902         }
903
904         // split the string by ':' and convert the second part to u16
905         let mut parts_iter = self.rsplitn(2, ':');
906         let port_str = try_opt!(parts_iter.next(), "invalid socket address");
907         let host = try_opt!(parts_iter.next(), "invalid socket address");
908         let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
909         resolve_socket_addr(host, port)
910     }
911 }
912
913 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
914 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
915     type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
916
917     fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
918         Ok(self.iter().cloned())
919     }
920 }
921
922 #[stable(feature = "rust1", since = "1.0.0")]
923 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
924     type Iter = T::Iter;
925     fn to_socket_addrs(&self) -> io::Result<T::Iter> {
926         (**self).to_socket_addrs()
927     }
928 }
929
930 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
931 impl ToSocketAddrs for String {
932     type Iter = vec::IntoIter<SocketAddr>;
933     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
934         (&**self).to_socket_addrs()
935     }
936 }
937
938 #[cfg(all(test, not(target_os = "emscripten")))]
939 mod tests {
940     use net::*;
941     use net::test::{tsa, sa6, sa4};
942
943     #[test]
944     fn to_socket_addr_ipaddr_u16() {
945         let a = Ipv4Addr::new(77, 88, 21, 11);
946         let p = 12345;
947         let e = SocketAddr::V4(SocketAddrV4::new(a, p));
948         assert_eq!(Ok(vec![e]), tsa((a, p)));
949     }
950
951     #[test]
952     fn to_socket_addr_str_u16() {
953         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
954         assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
955
956         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
957         assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
958
959         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
960         assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
961     }
962
963     #[test]
964     fn to_socket_addr_str() {
965         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
966         assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
967
968         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
969         assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
970
971         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
972         assert!(tsa("localhost:23924").unwrap().contains(&a));
973     }
974
975     #[test]
976     fn to_socket_addr_string() {
977         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
978         assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
979         assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
980         assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
981
982         let s = format!("{}:{}", "77.88.21.11", "24352");
983         assert_eq!(Ok(vec![a]), tsa(s));
984         // s has been moved into the tsa call
985     }
986
987     // FIXME: figure out why this fails on openbsd and bitrig and fix it
988     #[test]
989     #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
990     fn to_socket_addr_str_bad() {
991         assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
992     }
993
994     #[test]
995     fn set_ip() {
996         fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
997         fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
998
999         let mut v4 = SocketAddrV4::new(ip4(11), 80);
1000         assert_eq!(v4.ip(), &ip4(11));
1001         v4.set_ip(ip4(12));
1002         assert_eq!(v4.ip(), &ip4(12));
1003
1004         let mut addr = SocketAddr::V4(v4);
1005         assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
1006         addr.set_ip(IpAddr::V4(ip4(13)));
1007         assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
1008         addr.set_ip(IpAddr::V6(ip6(14)));
1009         assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
1010
1011         let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1012         assert_eq!(v6.ip(), &ip6(1));
1013         v6.set_ip(ip6(2));
1014         assert_eq!(v6.ip(), &ip6(2));
1015
1016         let mut addr = SocketAddr::V6(v6);
1017         assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
1018         addr.set_ip(IpAddr::V6(ip6(3)));
1019         assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
1020         addr.set_ip(IpAddr::V4(ip4(4)));
1021         assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
1022     }
1023
1024     #[test]
1025     fn set_port() {
1026         let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1027         assert_eq!(v4.port(), 80);
1028         v4.set_port(443);
1029         assert_eq!(v4.port(), 443);
1030
1031         let mut addr = SocketAddr::V4(v4);
1032         assert_eq!(addr.port(), 443);
1033         addr.set_port(8080);
1034         assert_eq!(addr.port(), 8080);
1035
1036         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1037         assert_eq!(v6.port(), 80);
1038         v6.set_port(443);
1039         assert_eq!(v6.port(), 443);
1040
1041         let mut addr = SocketAddr::V6(v6);
1042         assert_eq!(addr.port(), 443);
1043         addr.set_port(8080);
1044         assert_eq!(addr.port(), 8080);
1045     }
1046
1047     #[test]
1048     fn set_flowinfo() {
1049         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1050         assert_eq!(v6.flowinfo(), 10);
1051         v6.set_flowinfo(20);
1052         assert_eq!(v6.flowinfo(), 20);
1053     }
1054
1055     #[test]
1056     fn set_scope_id() {
1057         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1058         assert_eq!(v6.scope_id(), 10);
1059         v6.set_scope_id(20);
1060         assert_eq!(v6.scope_id(), 20);
1061     }
1062
1063     #[test]
1064     fn is_v4() {
1065         let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1066         assert!(v4.is_ipv4());
1067         assert!(!v4.is_ipv6());
1068     }
1069
1070     #[test]
1071     fn is_v6() {
1072         let v6 = SocketAddr::V6(SocketAddrV6::new(
1073                 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
1074         assert!(!v6.is_ipv4());
1075         assert!(v6.is_ipv6());
1076     }
1077 }