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