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