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