]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/addr.rs
Fix font color for help button in ayu and dark themes
[rust.git] / library / std / src / net / addr.rs
1 use crate::cmp::Ordering;
2 use crate::convert::TryInto;
3 use crate::fmt;
4 use crate::hash;
5 use crate::io::{self, Write};
6 use crate::iter;
7 use crate::mem;
8 use crate::net::{htons, ntohs, IpAddr, Ipv4Addr, Ipv6Addr};
9 use crate::option;
10 use crate::slice;
11 use crate::sys::net::netc as c;
12 use crate::sys_common::net::LookupHost;
13 use crate::sys_common::{AsInner, FromInner, IntoInner};
14 use crate::vec;
15
16 /// An internet socket address, either IPv4 or IPv6.
17 ///
18 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
19 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
20 /// [`SocketAddrV6`]'s respective documentation for more details.
21 ///
22 /// The size of a `SocketAddr` instance may vary depending on the target operating
23 /// system.
24 ///
25 /// [IP address]: IpAddr
26 ///
27 /// # Examples
28 ///
29 /// ```
30 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
31 ///
32 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
33 ///
34 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
35 /// assert_eq!(socket.port(), 8080);
36 /// assert_eq!(socket.is_ipv4(), true);
37 /// ```
38 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
39 #[stable(feature = "rust1", since = "1.0.0")]
40 pub enum SocketAddr {
41     /// An IPv4 socket address.
42     #[stable(feature = "rust1", since = "1.0.0")]
43     V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
44     /// An IPv6 socket address.
45     #[stable(feature = "rust1", since = "1.0.0")]
46     V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
47 }
48
49 /// An IPv4 socket address.
50 ///
51 /// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
52 /// stated in [IETF RFC 793].
53 ///
54 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
55 ///
56 /// The size of a `SocketAddrV4` struct may vary depending on the target operating
57 /// system.
58 ///
59 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
60 /// [`IPv4` address]: Ipv4Addr
61 ///
62 /// # Examples
63 ///
64 /// ```
65 /// use std::net::{Ipv4Addr, SocketAddrV4};
66 ///
67 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
68 ///
69 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
70 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
71 /// assert_eq!(socket.port(), 8080);
72 /// ```
73 #[derive(Copy)]
74 #[stable(feature = "rust1", since = "1.0.0")]
75 pub struct SocketAddrV4 {
76     inner: c::sockaddr_in,
77 }
78
79 /// An IPv6 socket address.
80 ///
81 /// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
82 /// as fields containing the traffic class, the flow label, and a scope identifier
83 /// (see [IETF RFC 2553, Section 3.3] for more details).
84 ///
85 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
86 ///
87 /// The size of a `SocketAddrV6` struct may vary depending on the target operating
88 /// system.
89 ///
90 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
91 /// [`IPv6` address]: Ipv6Addr
92 ///
93 /// # Examples
94 ///
95 /// ```
96 /// use std::net::{Ipv6Addr, SocketAddrV6};
97 ///
98 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
99 ///
100 /// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
101 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
102 /// assert_eq!(socket.port(), 8080);
103 /// ```
104 #[derive(Copy)]
105 #[stable(feature = "rust1", since = "1.0.0")]
106 pub struct SocketAddrV6 {
107     inner: c::sockaddr_in6,
108 }
109
110 impl SocketAddr {
111     /// Creates a new socket address from an [IP address] and a port number.
112     ///
113     /// [IP address]: IpAddr
114     ///
115     /// # Examples
116     ///
117     /// ```
118     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
119     ///
120     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
121     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
122     /// assert_eq!(socket.port(), 8080);
123     /// ```
124     #[stable(feature = "ip_addr", since = "1.7.0")]
125     pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
126         match ip {
127             IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
128             IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
129         }
130     }
131
132     /// Returns the IP address associated with this socket address.
133     ///
134     /// # Examples
135     ///
136     /// ```
137     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
138     ///
139     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
140     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
141     /// ```
142     #[stable(feature = "ip_addr", since = "1.7.0")]
143     pub fn ip(&self) -> IpAddr {
144         match *self {
145             SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
146             SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
147         }
148     }
149
150     /// Changes the IP address associated with this socket address.
151     ///
152     /// # Examples
153     ///
154     /// ```
155     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
156     ///
157     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
158     /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
159     /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
160     /// ```
161     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
162     pub fn set_ip(&mut self, new_ip: IpAddr) {
163         // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
164         match (self, new_ip) {
165             (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
166             (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
167             (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
168         }
169     }
170
171     /// Returns the port number associated with this socket address.
172     ///
173     /// # Examples
174     ///
175     /// ```
176     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
177     ///
178     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
179     /// assert_eq!(socket.port(), 8080);
180     /// ```
181     #[stable(feature = "rust1", since = "1.0.0")]
182     pub fn port(&self) -> u16 {
183         match *self {
184             SocketAddr::V4(ref a) => a.port(),
185             SocketAddr::V6(ref a) => a.port(),
186         }
187     }
188
189     /// Changes the port number associated with this socket address.
190     ///
191     /// # Examples
192     ///
193     /// ```
194     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
195     ///
196     /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
197     /// socket.set_port(1025);
198     /// assert_eq!(socket.port(), 1025);
199     /// ```
200     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
201     pub fn set_port(&mut self, new_port: u16) {
202         match *self {
203             SocketAddr::V4(ref mut a) => a.set_port(new_port),
204             SocketAddr::V6(ref mut a) => a.set_port(new_port),
205         }
206     }
207
208     /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
209     /// [`IPv4` address], and [`false`] otherwise.
210     ///
211     /// [IP address]: IpAddr
212     /// [`IPv4` address]: IpAddr::V4
213     /// [`false`]: ../../std/primitive.bool.html
214     /// [`true`]: ../../std/primitive.bool.html
215     ///
216     /// # Examples
217     ///
218     /// ```
219     /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
220     ///
221     /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
222     /// assert_eq!(socket.is_ipv4(), true);
223     /// assert_eq!(socket.is_ipv6(), false);
224     /// ```
225     #[stable(feature = "sockaddr_checker", since = "1.16.0")]
226     pub fn is_ipv4(&self) -> bool {
227         matches!(*self, SocketAddr::V4(_))
228     }
229
230     /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
231     /// [`IPv6` address], and [`false`] otherwise.
232     ///
233     /// [IP address]: IpAddr
234     /// [`IPv6` address]: IpAddr::V6
235     /// [`false`]: ../../std/primitive.bool.html
236     /// [`true`]: ../../std/primitive.bool.html
237     ///
238     /// # Examples
239     ///
240     /// ```
241     /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
242     ///
243     /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
244     /// assert_eq!(socket.is_ipv4(), false);
245     /// assert_eq!(socket.is_ipv6(), true);
246     /// ```
247     #[stable(feature = "sockaddr_checker", since = "1.16.0")]
248     pub fn is_ipv6(&self) -> bool {
249         matches!(*self, SocketAddr::V6(_))
250     }
251 }
252
253 impl SocketAddrV4 {
254     /// Creates a new socket address from an [`IPv4` address] and a port number.
255     ///
256     /// [`IPv4` address]: Ipv4Addr
257     ///
258     /// # Examples
259     ///
260     /// ```
261     /// use std::net::{SocketAddrV4, Ipv4Addr};
262     ///
263     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
264     /// ```
265     #[stable(feature = "rust1", since = "1.0.0")]
266     pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
267         SocketAddrV4 {
268             inner: c::sockaddr_in {
269                 sin_family: c::AF_INET as c::sa_family_t,
270                 sin_port: htons(port),
271                 sin_addr: *ip.as_inner(),
272                 ..unsafe { mem::zeroed() }
273             },
274         }
275     }
276
277     /// Returns the IP address associated with this socket address.
278     ///
279     /// # Examples
280     ///
281     /// ```
282     /// use std::net::{SocketAddrV4, Ipv4Addr};
283     ///
284     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
285     /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
286     /// ```
287     #[stable(feature = "rust1", since = "1.0.0")]
288     pub fn ip(&self) -> &Ipv4Addr {
289         unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) }
290     }
291
292     /// Changes the IP address associated with this socket address.
293     ///
294     /// # Examples
295     ///
296     /// ```
297     /// use std::net::{SocketAddrV4, Ipv4Addr};
298     ///
299     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
300     /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
301     /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
302     /// ```
303     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
304     pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
305         self.inner.sin_addr = *new_ip.as_inner()
306     }
307
308     /// Returns the port number associated with this socket address.
309     ///
310     /// # Examples
311     ///
312     /// ```
313     /// use std::net::{SocketAddrV4, Ipv4Addr};
314     ///
315     /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
316     /// assert_eq!(socket.port(), 8080);
317     /// ```
318     #[stable(feature = "rust1", since = "1.0.0")]
319     pub fn port(&self) -> u16 {
320         ntohs(self.inner.sin_port)
321     }
322
323     /// Changes the port number associated with this socket address.
324     ///
325     /// # Examples
326     ///
327     /// ```
328     /// use std::net::{SocketAddrV4, Ipv4Addr};
329     ///
330     /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
331     /// socket.set_port(4242);
332     /// assert_eq!(socket.port(), 4242);
333     /// ```
334     #[stable(feature = "sockaddr_setters", since = "1.9.0")]
335     pub fn set_port(&mut self, new_port: u16) {
336         self.inner.sin_port = htons(new_port);
337     }
338 }
339
340 impl SocketAddrV6 {
341     /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
342     /// and the `flowinfo` and `scope_id` fields.
343     ///
344     /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
345     /// parameters, see [IETF RFC 2553, Section 3.3].
346     ///
347     /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
348     /// [`IPv6` address]: Ipv6Addr
349     ///
350     /// # Examples
351     ///
352     /// ```
353     /// use std::net::{SocketAddrV6, Ipv6Addr};
354     ///
355     /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
356     /// ```
357     #[stable(feature = "rust1", since = "1.0.0")]
358     pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
359         SocketAddrV6 {
360             inner: c::sockaddr_in6 {
361                 sin6_family: c::AF_INET6 as c::sa_family_t,
362                 sin6_port: htons(port),
363                 sin6_addr: *ip.as_inner(),
364                 sin6_flowinfo: flowinfo,
365                 sin6_scope_id: scope_id,
366                 ..unsafe { mem::zeroed() }
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             write!(f, "[{}]:{}", self.ip(), self.port())
626         } else {
627             const IPV6_SOCKET_BUF_LEN: usize = (4 * 8)  // The address
628             + 7  // The colon separators
629             + 2  // The brackets
630             + 1 + 5; // The port
631
632             let mut buf = [0; IPV6_SOCKET_BUF_LEN];
633             let mut buf_slice = &mut buf[..];
634
635             // Unwrap is fine because writing to a sufficiently-sized
636             // buffer is infallible
637             write!(buf_slice, "[{}]:{}", self.ip(), self.port()).unwrap();
638             let len = IPV6_SOCKET_BUF_LEN - buf_slice.len();
639
640             // This unsafe is OK because we know what is being written to the buffer
641             let buf = unsafe { crate::str::from_utf8_unchecked(&buf[..len]) };
642             f.pad(buf)
643         }
644     }
645 }
646
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl fmt::Debug for SocketAddrV6 {
649     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
650         fmt::Display::fmt(self, fmt)
651     }
652 }
653
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl Clone for SocketAddrV4 {
656     fn clone(&self) -> SocketAddrV4 {
657         *self
658     }
659 }
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl Clone for SocketAddrV6 {
662     fn clone(&self) -> SocketAddrV6 {
663         *self
664     }
665 }
666
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl PartialEq for SocketAddrV4 {
669     fn eq(&self, other: &SocketAddrV4) -> bool {
670         self.inner.sin_port == other.inner.sin_port
671             && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
672     }
673 }
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl PartialEq for SocketAddrV6 {
676     fn eq(&self, other: &SocketAddrV6) -> bool {
677         self.inner.sin6_port == other.inner.sin6_port
678             && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr
679             && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo
680             && self.inner.sin6_scope_id == other.inner.sin6_scope_id
681     }
682 }
683 #[stable(feature = "rust1", since = "1.0.0")]
684 impl Eq for SocketAddrV4 {}
685 #[stable(feature = "rust1", since = "1.0.0")]
686 impl Eq for SocketAddrV6 {}
687
688 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
689 impl PartialOrd for SocketAddrV4 {
690     fn partial_cmp(&self, other: &SocketAddrV4) -> Option<Ordering> {
691         Some(self.cmp(other))
692     }
693 }
694
695 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
696 impl PartialOrd for SocketAddrV6 {
697     fn partial_cmp(&self, other: &SocketAddrV6) -> Option<Ordering> {
698         Some(self.cmp(other))
699     }
700 }
701
702 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
703 impl Ord for SocketAddrV4 {
704     fn cmp(&self, other: &SocketAddrV4) -> Ordering {
705         self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
706     }
707 }
708
709 #[stable(feature = "socketaddr_ordering", since = "1.45.0")]
710 impl Ord for SocketAddrV6 {
711     fn cmp(&self, other: &SocketAddrV6) -> Ordering {
712         self.ip().cmp(other.ip()).then(self.port().cmp(&other.port()))
713     }
714 }
715
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl hash::Hash for SocketAddrV4 {
718     fn hash<H: hash::Hasher>(&self, s: &mut H) {
719         (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
720     }
721 }
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl hash::Hash for SocketAddrV6 {
724     fn hash<H: hash::Hasher>(&self, s: &mut H) {
725         (
726             self.inner.sin6_port,
727             &self.inner.sin6_addr.s6_addr,
728             self.inner.sin6_flowinfo,
729             self.inner.sin6_scope_id,
730         )
731             .hash(s)
732     }
733 }
734
735 /// A trait for objects which can be converted or resolved to one or more
736 /// [`SocketAddr`] values.
737 ///
738 /// This trait is used for generic address resolution when constructing network
739 /// objects. By default it is implemented for the following types:
740 ///
741 ///  * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
742 ///
743 ///  * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
744 ///    `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
745 ///    [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
746 ///
747 ///  * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
748 ///    of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
749 ///    name.
750 ///
751 ///  * [`&str`]: the string should be either a string representation of a
752 ///    [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
753 ///    `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
754 ///
755 /// This trait allows constructing network objects like [`TcpStream`] or
756 /// [`UdpSocket`] easily with values of various types for the bind/connection
757 /// address. It is needed because sometimes one type is more appropriate than
758 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
759 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
760 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
761 /// some other type (e.g., a string) just for it to be converted back to
762 /// [`SocketAddr`] in constructor methods is pointless.
763 ///
764 /// Addresses returned by the operating system that are not IP addresses are
765 /// silently ignored.
766 ///
767 /// [`FromStr`]: crate::str::FromStr
768 /// [`&str`]: str
769 /// [`TcpStream`]: crate::net::TcpStream
770 /// [`to_socket_addrs`]: ToSocketAddrs::to_socket_addrs
771 /// [`UdpSocket`]: crate::net::UdpSocket
772 ///
773 /// # Examples
774 ///
775 /// Creating a [`SocketAddr`] iterator that yields one item:
776 ///
777 /// ```
778 /// use std::net::{ToSocketAddrs, SocketAddr};
779 ///
780 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
781 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
782 ///
783 /// assert_eq!(Some(addr), addrs_iter.next());
784 /// assert!(addrs_iter.next().is_none());
785 /// ```
786 ///
787 /// Creating a [`SocketAddr`] iterator from a hostname:
788 ///
789 /// ```no_run
790 /// use std::net::{SocketAddr, ToSocketAddrs};
791 ///
792 /// // assuming 'localhost' resolves to 127.0.0.1
793 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
794 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
795 /// assert!(addrs_iter.next().is_none());
796 ///
797 /// // assuming 'foo' does not resolve
798 /// assert!("foo:443".to_socket_addrs().is_err());
799 /// ```
800 ///
801 /// Creating a [`SocketAddr`] iterator that yields multiple items:
802 ///
803 /// ```
804 /// use std::net::{SocketAddr, ToSocketAddrs};
805 ///
806 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
807 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
808 /// let addrs = vec![addr1, addr2];
809 ///
810 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
811 ///
812 /// assert_eq!(Some(addr1), addrs_iter.next());
813 /// assert_eq!(Some(addr2), addrs_iter.next());
814 /// assert!(addrs_iter.next().is_none());
815 /// ```
816 ///
817 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
818 /// socket address `&str` (missing the port):
819 ///
820 /// ```
821 /// use std::io;
822 /// use std::net::ToSocketAddrs;
823 ///
824 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
825 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
826 /// ```
827 ///
828 /// [`TcpStream::connect`] is an example of an function that utilizes
829 /// `ToSocketAddrs` as a trait bound on its parameter in order to accept
830 /// different types:
831 ///
832 /// ```no_run
833 /// use std::net::{TcpStream, Ipv4Addr};
834 ///
835 /// let stream = TcpStream::connect(("127.0.0.1", 443));
836 /// // or
837 /// let stream = TcpStream::connect("127.0.0.1:443");
838 /// // or
839 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
840 /// ```
841 ///
842 /// [`TcpStream::connect`]: crate::net::TcpStream::connect
843 #[stable(feature = "rust1", since = "1.0.0")]
844 pub trait ToSocketAddrs {
845     /// Returned iterator over socket addresses which this type may correspond
846     /// to.
847     #[stable(feature = "rust1", since = "1.0.0")]
848     type Iter: Iterator<Item = SocketAddr>;
849
850     /// Converts this object to an iterator of resolved `SocketAddr`s.
851     ///
852     /// The returned iterator may not actually yield any values depending on the
853     /// outcome of any resolution performed.
854     ///
855     /// Note that this function may block the current thread while resolution is
856     /// performed.
857     #[stable(feature = "rust1", since = "1.0.0")]
858     fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
859 }
860
861 #[stable(feature = "rust1", since = "1.0.0")]
862 impl ToSocketAddrs for SocketAddr {
863     type Iter = option::IntoIter<SocketAddr>;
864     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
865         Ok(Some(*self).into_iter())
866     }
867 }
868
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl ToSocketAddrs for SocketAddrV4 {
871     type Iter = option::IntoIter<SocketAddr>;
872     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
873         SocketAddr::V4(*self).to_socket_addrs()
874     }
875 }
876
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl ToSocketAddrs for SocketAddrV6 {
879     type Iter = option::IntoIter<SocketAddr>;
880     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
881         SocketAddr::V6(*self).to_socket_addrs()
882     }
883 }
884
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl ToSocketAddrs for (IpAddr, u16) {
887     type Iter = option::IntoIter<SocketAddr>;
888     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
889         let (ip, port) = *self;
890         match ip {
891             IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
892             IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
893         }
894     }
895 }
896
897 #[stable(feature = "rust1", since = "1.0.0")]
898 impl ToSocketAddrs for (Ipv4Addr, u16) {
899     type Iter = option::IntoIter<SocketAddr>;
900     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
901         let (ip, port) = *self;
902         SocketAddrV4::new(ip, port).to_socket_addrs()
903     }
904 }
905
906 #[stable(feature = "rust1", since = "1.0.0")]
907 impl ToSocketAddrs for (Ipv6Addr, u16) {
908     type Iter = option::IntoIter<SocketAddr>;
909     fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
910         let (ip, port) = *self;
911         SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
912     }
913 }
914
915 fn resolve_socket_addr(lh: LookupHost) -> io::Result<vec::IntoIter<SocketAddr>> {
916     let p = lh.port();
917     let v: Vec<_> = lh
918         .map(|mut a| {
919             a.set_port(p);
920             a
921         })
922         .collect();
923     Ok(v.into_iter())
924 }
925
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl ToSocketAddrs for (&str, u16) {
928     type Iter = vec::IntoIter<SocketAddr>;
929     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
930         let (host, port) = *self;
931
932         // try to parse the host as a regular IP address first
933         if let Ok(addr) = host.parse::<Ipv4Addr>() {
934             let addr = SocketAddrV4::new(addr, port);
935             return Ok(vec![SocketAddr::V4(addr)].into_iter());
936         }
937         if let Ok(addr) = host.parse::<Ipv6Addr>() {
938             let addr = SocketAddrV6::new(addr, port, 0, 0);
939             return Ok(vec![SocketAddr::V6(addr)].into_iter());
940         }
941
942         resolve_socket_addr((host, port).try_into()?)
943     }
944 }
945
946 #[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
947 impl ToSocketAddrs for (String, u16) {
948     type Iter = vec::IntoIter<SocketAddr>;
949     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
950         (&*self.0, self.1).to_socket_addrs()
951     }
952 }
953
954 // accepts strings like 'localhost:12345'
955 #[stable(feature = "rust1", since = "1.0.0")]
956 impl ToSocketAddrs for str {
957     type Iter = vec::IntoIter<SocketAddr>;
958     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
959         // try to parse as a regular SocketAddr first
960         if let Ok(addr) = self.parse() {
961             return Ok(vec![addr].into_iter());
962         }
963
964         resolve_socket_addr(self.try_into()?)
965     }
966 }
967
968 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
969 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
970     type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
971
972     fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
973         Ok(self.iter().cloned())
974     }
975 }
976
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
979     type Iter = T::Iter;
980     fn to_socket_addrs(&self) -> io::Result<T::Iter> {
981         (**self).to_socket_addrs()
982     }
983 }
984
985 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
986 impl ToSocketAddrs for String {
987     type Iter = vec::IntoIter<SocketAddr>;
988     fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
989         (&**self).to_socket_addrs()
990     }
991 }
992
993 #[cfg(all(test, not(target_os = "emscripten")))]
994 mod tests {
995     use crate::net::test::{sa4, sa6, tsa};
996     use crate::net::*;
997
998     #[test]
999     fn to_socket_addr_ipaddr_u16() {
1000         let a = Ipv4Addr::new(77, 88, 21, 11);
1001         let p = 12345;
1002         let e = SocketAddr::V4(SocketAddrV4::new(a, p));
1003         assert_eq!(Ok(vec![e]), tsa((a, p)));
1004     }
1005
1006     #[test]
1007     fn to_socket_addr_str_u16() {
1008         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
1009         assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
1010
1011         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
1012         assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
1013
1014         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
1015         #[cfg(not(target_env = "sgx"))]
1016         assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
1017         #[cfg(target_env = "sgx")]
1018         let _ = a;
1019     }
1020
1021     #[test]
1022     fn to_socket_addr_str() {
1023         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
1024         assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
1025
1026         let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
1027         assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
1028
1029         let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
1030         #[cfg(not(target_env = "sgx"))]
1031         assert!(tsa("localhost:23924").unwrap().contains(&a));
1032         #[cfg(target_env = "sgx")]
1033         let _ = a;
1034     }
1035
1036     #[test]
1037     fn to_socket_addr_string() {
1038         let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
1039         assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
1040         assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
1041         assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
1042
1043         let s = format!("{}:{}", "77.88.21.11", "24352");
1044         assert_eq!(Ok(vec![a]), tsa(s));
1045         // s has been moved into the tsa call
1046     }
1047
1048     #[test]
1049     fn bind_udp_socket_bad() {
1050         // rust-lang/rust#53957: This is a regression test for a parsing problem
1051         // discovered as part of issue rust-lang/rust#23076, where we were
1052         // incorrectly parsing invalid input and then that would result in a
1053         // successful `UdpSocket` binding when we would expect failure.
1054         //
1055         // At one time, this test was written as a call to `tsa` with
1056         // INPUT_23076. However, that structure yields an unreliable test,
1057         // because it ends up passing junk input to the DNS server, and some DNS
1058         // servers will respond with `Ok` to such input, with the ip address of
1059         // the DNS server itself.
1060         //
1061         // This form of the test is more robust: even when the DNS server
1062         // returns its own address, it is still an error to bind a UDP socket to
1063         // a non-local address, and so we still get an error here in that case.
1064
1065         const INPUT_23076: &'static str = "1200::AB00:1234::2552:7777:1313:34300";
1066
1067         assert!(crate::net::UdpSocket::bind(INPUT_23076).is_err())
1068     }
1069
1070     #[test]
1071     fn set_ip() {
1072         fn ip4(low: u8) -> Ipv4Addr {
1073             Ipv4Addr::new(77, 88, 21, low)
1074         }
1075         fn ip6(low: u16) -> Ipv6Addr {
1076             Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low)
1077         }
1078
1079         let mut v4 = SocketAddrV4::new(ip4(11), 80);
1080         assert_eq!(v4.ip(), &ip4(11));
1081         v4.set_ip(ip4(12));
1082         assert_eq!(v4.ip(), &ip4(12));
1083
1084         let mut addr = SocketAddr::V4(v4);
1085         assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
1086         addr.set_ip(IpAddr::V4(ip4(13)));
1087         assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
1088         addr.set_ip(IpAddr::V6(ip6(14)));
1089         assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
1090
1091         let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1092         assert_eq!(v6.ip(), &ip6(1));
1093         v6.set_ip(ip6(2));
1094         assert_eq!(v6.ip(), &ip6(2));
1095
1096         let mut addr = SocketAddr::V6(v6);
1097         assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
1098         addr.set_ip(IpAddr::V6(ip6(3)));
1099         assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
1100         addr.set_ip(IpAddr::V4(ip4(4)));
1101         assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
1102     }
1103
1104     #[test]
1105     fn set_port() {
1106         let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1107         assert_eq!(v4.port(), 80);
1108         v4.set_port(443);
1109         assert_eq!(v4.port(), 443);
1110
1111         let mut addr = SocketAddr::V4(v4);
1112         assert_eq!(addr.port(), 443);
1113         addr.set_port(8080);
1114         assert_eq!(addr.port(), 8080);
1115
1116         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1117         assert_eq!(v6.port(), 80);
1118         v6.set_port(443);
1119         assert_eq!(v6.port(), 443);
1120
1121         let mut addr = SocketAddr::V6(v6);
1122         assert_eq!(addr.port(), 443);
1123         addr.set_port(8080);
1124         assert_eq!(addr.port(), 8080);
1125     }
1126
1127     #[test]
1128     fn set_flowinfo() {
1129         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1130         assert_eq!(v6.flowinfo(), 10);
1131         v6.set_flowinfo(20);
1132         assert_eq!(v6.flowinfo(), 20);
1133     }
1134
1135     #[test]
1136     fn set_scope_id() {
1137         let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1138         assert_eq!(v6.scope_id(), 10);
1139         v6.set_scope_id(20);
1140         assert_eq!(v6.scope_id(), 20);
1141     }
1142
1143     #[test]
1144     fn is_v4() {
1145         let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1146         assert!(v4.is_ipv4());
1147         assert!(!v4.is_ipv6());
1148     }
1149
1150     #[test]
1151     fn is_v6() {
1152         let v6 = SocketAddr::V6(SocketAddrV6::new(
1153             Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1),
1154             80,
1155             10,
1156             0,
1157         ));
1158         assert!(!v6.is_ipv4());
1159         assert!(v6.is_ipv6());
1160     }
1161
1162     #[test]
1163     fn socket_v4_to_str() {
1164         let socket = SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 8080);
1165
1166         assert_eq!(format!("{}", socket), "192.168.0.1:8080");
1167         assert_eq!(format!("{:<20}", socket), "192.168.0.1:8080    ");
1168         assert_eq!(format!("{:>20}", socket), "    192.168.0.1:8080");
1169         assert_eq!(format!("{:^20}", socket), "  192.168.0.1:8080  ");
1170         assert_eq!(format!("{:.10}", socket), "192.168.0.");
1171     }
1172
1173     #[test]
1174     fn socket_v6_to_str() {
1175         let socket: SocketAddrV6 = "[2a02:6b8:0:1::1]:53".parse().unwrap();
1176
1177         assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1]:53");
1178         assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1]:53    ");
1179         assert_eq!(format!("{:>24}", socket), "    [2a02:6b8:0:1::1]:53");
1180         assert_eq!(format!("{:^24}", socket), "  [2a02:6b8:0:1::1]:53  ");
1181         assert_eq!(format!("{:.15}", socket), "[2a02:6b8:0:1::");
1182     }
1183
1184     #[test]
1185     fn compare() {
1186         let v4_1 = "224.120.45.1:23456".parse::<SocketAddrV4>().unwrap();
1187         let v4_2 = "224.210.103.5:12345".parse::<SocketAddrV4>().unwrap();
1188         let v4_3 = "224.210.103.5:23456".parse::<SocketAddrV4>().unwrap();
1189         let v6_1 = "[2001:db8:f00::1002]:23456".parse::<SocketAddrV6>().unwrap();
1190         let v6_2 = "[2001:db8:f00::2001]:12345".parse::<SocketAddrV6>().unwrap();
1191         let v6_3 = "[2001:db8:f00::2001]:23456".parse::<SocketAddrV6>().unwrap();
1192
1193         // equality
1194         assert_eq!(v4_1, v4_1);
1195         assert_eq!(v6_1, v6_1);
1196         assert_eq!(SocketAddr::V4(v4_1), SocketAddr::V4(v4_1));
1197         assert_eq!(SocketAddr::V6(v6_1), SocketAddr::V6(v6_1));
1198         assert!(v4_1 != v4_2);
1199         assert!(v6_1 != v6_2);
1200
1201         // compare different addresses
1202         assert!(v4_1 < v4_2);
1203         assert!(v6_1 < v6_2);
1204         assert!(v4_2 > v4_1);
1205         assert!(v6_2 > v6_1);
1206
1207         // compare the same address with different ports
1208         assert!(v4_2 < v4_3);
1209         assert!(v6_2 < v6_3);
1210         assert!(v4_3 > v4_2);
1211         assert!(v6_3 > v6_2);
1212
1213         // compare different addresses with the same port
1214         assert!(v4_1 < v4_3);
1215         assert!(v6_1 < v6_3);
1216         assert!(v4_3 > v4_1);
1217         assert!(v6_3 > v6_1);
1218
1219         // compare with an inferred right-hand side
1220         assert_eq!(v4_1, "224.120.45.1:23456".parse().unwrap());
1221         assert_eq!(v6_1, "[2001:db8:f00::1002]:23456".parse().unwrap());
1222         assert_eq!(SocketAddr::V4(v4_1), "224.120.45.1:23456".parse().unwrap());
1223     }
1224 }