Skip to main content

core/net/
socket_addr.rs

1use super::display_buffer::DisplayBuffer;
2use crate::fmt::{self, Write};
3use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr};
4
5/// An internet socket address, either IPv4 or IPv6.
6///
7/// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
8/// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
9/// [`SocketAddrV6`]'s respective documentation for more details.
10///
11/// [IP address]: IpAddr
12///
13/// # Portability
14///
15/// `SocketAddr` is intended to be a portable representation of socket addresses and is likely not
16/// the same as the internal socket address type used by the target operating system's API. Like all
17/// `repr(Rust)` structs, however, its exact layout remains undefined and should not be relied upon
18/// between builds.
19///
20/// # Examples
21///
22/// ```
23/// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
24///
25/// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
26///
27/// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
28/// assert_eq!(socket.port(), 8080);
29/// assert_eq!(socket.is_ipv4(), true);
30/// ```
31#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
32#[stable(feature = "rust1", since = "1.0.0")]
33pub enum SocketAddr {
34    /// An IPv4 socket address.
35    #[stable(feature = "rust1", since = "1.0.0")]
36    V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
37    /// An IPv6 socket address.
38    #[stable(feature = "rust1", since = "1.0.0")]
39    V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
40}
41
42/// An IPv4 socket address.
43///
44/// IPv4 socket addresses consist of an [`IPv4` address] and a 16-bit port number, as
45/// stated in [IETF RFC 793].
46///
47/// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
48///
49/// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
50/// [`IPv4` address]: Ipv4Addr
51///
52/// # Portability
53///
54/// `SocketAddrV4` is intended to be a portable representation of socket addresses and is likely not
55/// the same as the internal socket address type used by the target operating system's API. Like all
56/// `repr(Rust)` structs, however, its exact layout remains undefined and should not be relied upon
57/// between builds.
58///
59/// # Textual representation
60///
61/// `SocketAddrV4` provides a [`FromStr`](crate::str::FromStr) implementation.
62/// It accepts an IPv4 address in its [textual representation], followed by a
63/// single `:`, followed by the port encoded as a decimal integer.  Other
64/// formats are not accepted.
65///
66/// [textual representation]: Ipv4Addr#textual-representation
67///
68/// # Examples
69///
70/// ```
71/// use std::net::{Ipv4Addr, SocketAddrV4};
72///
73/// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
74///
75/// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
76/// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
77/// assert_eq!(socket.port(), 8080);
78/// ```
79#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
80#[stable(feature = "rust1", since = "1.0.0")]
81pub struct SocketAddrV4 {
82    ip: Ipv4Addr,
83    port: u16,
84}
85
86/// An IPv6 socket address.
87///
88/// IPv6 socket addresses consist of an [`IPv6` address], a 16-bit port number, as well
89/// as fields containing the traffic class, the flow label, and a scope identifier
90/// (see [IETF RFC 2553, Section 3.3] for more details).
91///
92/// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
93///
94/// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
95/// [`IPv6` address]: Ipv6Addr
96///
97/// # Portability
98///
99/// `SocketAddrV6` is intended to be a portable representation of socket addresses and is likely not
100/// the same as the internal socket address type used by the target operating system's API. Like all
101/// `repr(Rust)` structs, however, its exact layout remains undefined and should not be relied upon
102/// between builds.
103///
104/// # Textual representation
105///
106/// `SocketAddrV6` provides a [`FromStr`](crate::str::FromStr) implementation,
107/// based on the bracketed format recommended by [IETF RFC 5952],
108/// with scope identifiers based on those specified in [IETF RFC 4007].
109///
110/// It accepts addresses consisting of the following elements, in order:
111///   - A left square bracket (`[`)
112///   - The [textual representation] of an IPv6 address
113///   - _Optionally_, a percent sign (`%`) followed by the scope identifier
114///     encoded as a decimal integer
115///   - A right square bracket (`]`)
116///   - A colon (`:`)
117///   - The port, encoded as a decimal integer.
118///
119/// For example, the string `[2001:db8::413]:443` represents a `SocketAddrV6`
120/// with the address `2001:db8::413` and port `443`.  The string
121/// `[2001:db8::413%612]:443` represents the same address and port, with a
122/// scope identifier of `612`.
123///
124/// Other formats are not accepted.
125///
126/// [IETF RFC 5952]: https://tools.ietf.org/html/rfc5952#section-6
127/// [IETF RFC 4007]: https://tools.ietf.org/html/rfc4007#section-11
128/// [textual representation]: Ipv6Addr#textual-representation
129///
130/// # Examples
131///
132/// ```
133/// use std::net::{Ipv6Addr, SocketAddrV6};
134///
135/// let socket = SocketAddrV6::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
136///
137/// assert_eq!("[2001:db8::1]:8080".parse(), Ok(socket));
138/// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1));
139/// assert_eq!(socket.port(), 8080);
140///
141/// let mut with_scope = socket.clone();
142/// with_scope.set_scope_id(3);
143/// assert_eq!("[2001:db8::1%3]:8080".parse(), Ok(with_scope));
144/// ```
145#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
146#[stable(feature = "rust1", since = "1.0.0")]
147pub struct SocketAddrV6 {
148    ip: Ipv6Addr,
149    port: u16,
150    flowinfo: u32,
151    scope_id: u32,
152}
153
154impl SocketAddr {
155    /// Creates a new socket address from an [IP address] and a port number.
156    ///
157    /// [IP address]: IpAddr
158    ///
159    /// # Examples
160    ///
161    /// ```
162    /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
163    ///
164    /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
165    /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
166    /// assert_eq!(socket.port(), 8080);
167    /// ```
168    #[stable(feature = "ip_addr", since = "1.7.0")]
169    #[must_use]
170    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
171    #[inline]
172    pub const fn new(ip: IpAddr, port: u16) -> SocketAddr {
173        match ip {
174            IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
175            IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
176        }
177    }
178
179    /// Returns the IP address associated with this socket address.
180    ///
181    /// # Examples
182    ///
183    /// ```
184    /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
185    ///
186    /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
187    /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
188    /// ```
189    #[must_use]
190    #[stable(feature = "ip_addr", since = "1.7.0")]
191    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
192    #[inline]
193    pub const fn ip(&self) -> IpAddr {
194        match *self {
195            SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
196            SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
197        }
198    }
199
200    /// Changes the IP address associated with this socket address.
201    ///
202    /// # Examples
203    ///
204    /// ```
205    /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
206    ///
207    /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
208    /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
209    /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
210    /// ```
211    #[inline]
212    #[stable(feature = "sockaddr_setters", since = "1.9.0")]
213    #[rustc_const_stable(feature = "const_sockaddr_setters", since = "1.87.0")]
214    pub const fn set_ip(&mut self, new_ip: IpAddr) {
215        // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
216        match (self, new_ip) {
217            (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
218            (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
219            (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
220        }
221    }
222
223    /// Returns the port number associated with this socket address.
224    ///
225    /// # Examples
226    ///
227    /// ```
228    /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
229    ///
230    /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
231    /// assert_eq!(socket.port(), 8080);
232    /// ```
233    #[must_use]
234    #[stable(feature = "rust1", since = "1.0.0")]
235    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
236    #[inline]
237    pub const fn port(&self) -> u16 {
238        match *self {
239            SocketAddr::V4(ref a) => a.port(),
240            SocketAddr::V6(ref a) => a.port(),
241        }
242    }
243
244    /// Changes the port number associated with this socket address.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
250    ///
251    /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
252    /// socket.set_port(1025);
253    /// assert_eq!(socket.port(), 1025);
254    /// ```
255    #[inline]
256    #[stable(feature = "sockaddr_setters", since = "1.9.0")]
257    #[rustc_const_stable(feature = "const_sockaddr_setters", since = "1.87.0")]
258    pub const fn set_port(&mut self, new_port: u16) {
259        match *self {
260            SocketAddr::V4(ref mut a) => a.set_port(new_port),
261            SocketAddr::V6(ref mut a) => a.set_port(new_port),
262        }
263    }
264
265    /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
266    /// [`IPv4` address], and [`false`] otherwise.
267    ///
268    /// [IP address]: IpAddr
269    /// [`IPv4` address]: IpAddr::V4
270    ///
271    /// # Examples
272    ///
273    /// ```
274    /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
275    ///
276    /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
277    /// assert_eq!(socket.is_ipv4(), true);
278    /// assert_eq!(socket.is_ipv6(), false);
279    /// ```
280    #[must_use]
281    #[stable(feature = "sockaddr_checker", since = "1.16.0")]
282    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
283    #[inline]
284    pub const fn is_ipv4(&self) -> bool {
285        matches!(*self, SocketAddr::V4(_))
286    }
287
288    /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
289    /// [`IPv6` address], and [`false`] otherwise.
290    ///
291    /// [IP address]: IpAddr
292    /// [`IPv6` address]: IpAddr::V6
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
298    ///
299    /// let socket = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
300    /// assert_eq!(socket.is_ipv4(), false);
301    /// assert_eq!(socket.is_ipv6(), true);
302    /// ```
303    #[must_use]
304    #[stable(feature = "sockaddr_checker", since = "1.16.0")]
305    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
306    #[inline]
307    pub const fn is_ipv6(&self) -> bool {
308        matches!(*self, SocketAddr::V6(_))
309    }
310
311    /// Returns the unspecified socket address for the same IP version.
312    ///
313    /// Returns `0.0.0.0:0` for IPv4 and `[::]:0` for IPv6. For IPv6, this
314    /// method preserves the flow information and scope ID.
315    ///
316    /// Use this method when you must bind a socket to an unspecified local
317    /// address that uses the same IP version as a remote address.
318    ///
319    /// # Examples
320    /// ```
321    /// #![feature(addr_unspecified_from)]
322    /// use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr};
323    ///
324    /// let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 3000));
325    /// assert_eq!(
326    ///     SocketAddr::unspecified_from(addr),
327    ///     SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0))
328    /// );
329    ///
330    /// let addr = SocketAddr::V6(SocketAddrV6::new(
331    ///     Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1),
332    ///     443,
333    ///     0x1234,
334    ///     5,
335    /// ));
336    ///
337    /// let unspecified = SocketAddr::unspecified_from(addr);
338    /// assert_eq!(unspecified.ip(), Ipv6Addr::UNSPECIFIED);
339    /// if let SocketAddr::V6(v6) = unspecified {
340    ///     assert_eq!(v6.flowinfo(), 0x1234);
341    ///     assert_eq!(v6.scope_id(), 5);
342    /// }
343    /// ```
344    #[inline]
345    #[must_use]
346    #[unstable(feature = "addr_unspecified_from", issue = "158975")]
347    pub const fn unspecified_from(this: Self) -> Self {
348        match this {
349            Self::V4(_) => Self::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)),
350            Self::V6(addr) => Self::V6(SocketAddrV6::new(
351                Ipv6Addr::UNSPECIFIED,
352                0,
353                addr.flowinfo(),
354                addr.scope_id(),
355            )),
356        }
357    }
358}
359
360impl SocketAddrV4 {
361    /// Creates a new socket address from an [`IPv4` address] and a port number.
362    ///
363    /// [`IPv4` address]: Ipv4Addr
364    ///
365    /// # Examples
366    ///
367    /// ```
368    /// use std::net::{SocketAddrV4, Ipv4Addr};
369    ///
370    /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
371    /// ```
372    #[stable(feature = "rust1", since = "1.0.0")]
373    #[must_use]
374    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
375    #[inline]
376    pub const fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
377        SocketAddrV4 { ip, port }
378    }
379
380    /// Returns the IP address associated with this socket address.
381    ///
382    /// # Examples
383    ///
384    /// ```
385    /// use std::net::{SocketAddrV4, Ipv4Addr};
386    ///
387    /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
388    /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
389    /// ```
390    #[must_use]
391    #[stable(feature = "rust1", since = "1.0.0")]
392    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
393    #[inline]
394    pub const fn ip(&self) -> &Ipv4Addr {
395        &self.ip
396    }
397
398    /// Changes the IP address associated with this socket address.
399    ///
400    /// # Examples
401    ///
402    /// ```
403    /// use std::net::{SocketAddrV4, Ipv4Addr};
404    ///
405    /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
406    /// socket.set_ip(Ipv4Addr::new(192, 168, 0, 1));
407    /// assert_eq!(socket.ip(), &Ipv4Addr::new(192, 168, 0, 1));
408    /// ```
409    #[inline]
410    #[stable(feature = "sockaddr_setters", since = "1.9.0")]
411    #[rustc_const_stable(feature = "const_sockaddr_setters", since = "1.87.0")]
412    pub const fn set_ip(&mut self, new_ip: Ipv4Addr) {
413        self.ip = new_ip;
414    }
415
416    /// Returns the port number associated with this socket address.
417    ///
418    /// # Examples
419    ///
420    /// ```
421    /// use std::net::{SocketAddrV4, Ipv4Addr};
422    ///
423    /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
424    /// assert_eq!(socket.port(), 8080);
425    /// ```
426    #[must_use]
427    #[stable(feature = "rust1", since = "1.0.0")]
428    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
429    #[inline]
430    pub const fn port(&self) -> u16 {
431        self.port
432    }
433
434    /// Changes the port number associated with this socket address.
435    ///
436    /// # Examples
437    ///
438    /// ```
439    /// use std::net::{SocketAddrV4, Ipv4Addr};
440    ///
441    /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
442    /// socket.set_port(4242);
443    /// assert_eq!(socket.port(), 4242);
444    /// ```
445    #[inline]
446    #[stable(feature = "sockaddr_setters", since = "1.9.0")]
447    #[rustc_const_stable(feature = "const_sockaddr_setters", since = "1.87.0")]
448    pub const fn set_port(&mut self, new_port: u16) {
449        self.port = new_port;
450    }
451}
452
453impl SocketAddrV6 {
454    /// Creates a new socket address from an [`IPv6` address], a 16-bit port number,
455    /// and the `flowinfo` and `scope_id` fields.
456    ///
457    /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
458    /// parameters, see [IETF RFC 2553, Section 3.3].
459    ///
460    /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
461    /// [`IPv6` address]: Ipv6Addr
462    ///
463    /// # Examples
464    ///
465    /// ```
466    /// use std::net::{SocketAddrV6, Ipv6Addr};
467    ///
468    /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
469    /// ```
470    #[stable(feature = "rust1", since = "1.0.0")]
471    #[must_use]
472    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
473    #[inline]
474    pub const fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 {
475        SocketAddrV6 { ip, port, flowinfo, scope_id }
476    }
477
478    /// Returns the IP address associated with this socket address.
479    ///
480    /// # Examples
481    ///
482    /// ```
483    /// use std::net::{SocketAddrV6, Ipv6Addr};
484    ///
485    /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
486    /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
487    /// ```
488    #[must_use]
489    #[stable(feature = "rust1", since = "1.0.0")]
490    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
491    #[inline]
492    pub const fn ip(&self) -> &Ipv6Addr {
493        &self.ip
494    }
495
496    /// Changes the IP address associated with this socket address.
497    ///
498    /// # Examples
499    ///
500    /// ```
501    /// use std::net::{SocketAddrV6, Ipv6Addr};
502    ///
503    /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
504    /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
505    /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
506    /// ```
507    #[inline]
508    #[stable(feature = "sockaddr_setters", since = "1.9.0")]
509    #[rustc_const_stable(feature = "const_sockaddr_setters", since = "1.87.0")]
510    pub const fn set_ip(&mut self, new_ip: Ipv6Addr) {
511        self.ip = new_ip;
512    }
513
514    /// Returns the port number associated with this socket address.
515    ///
516    /// # Examples
517    ///
518    /// ```
519    /// use std::net::{SocketAddrV6, Ipv6Addr};
520    ///
521    /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
522    /// assert_eq!(socket.port(), 8080);
523    /// ```
524    #[must_use]
525    #[stable(feature = "rust1", since = "1.0.0")]
526    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
527    #[inline]
528    pub const fn port(&self) -> u16 {
529        self.port
530    }
531
532    /// Changes the port number associated with this socket address.
533    ///
534    /// # Examples
535    ///
536    /// ```
537    /// use std::net::{SocketAddrV6, Ipv6Addr};
538    ///
539    /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
540    /// socket.set_port(4242);
541    /// assert_eq!(socket.port(), 4242);
542    /// ```
543    #[inline]
544    #[stable(feature = "sockaddr_setters", since = "1.9.0")]
545    #[rustc_const_stable(feature = "const_sockaddr_setters", since = "1.87.0")]
546    pub const fn set_port(&mut self, new_port: u16) {
547        self.port = new_port;
548    }
549
550    /// Returns the flow information associated with this address.
551    ///
552    /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
553    /// as specified in [IETF RFC 2553, Section 3.3].
554    /// It combines information about the flow label and the traffic class as specified
555    /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
556    ///
557    /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
558    /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
559    /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
560    /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
561    ///
562    /// # Examples
563    ///
564    /// ```
565    /// use std::net::{SocketAddrV6, Ipv6Addr};
566    ///
567    /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
568    /// assert_eq!(socket.flowinfo(), 10);
569    /// ```
570    #[must_use]
571    #[stable(feature = "rust1", since = "1.0.0")]
572    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
573    #[inline]
574    pub const fn flowinfo(&self) -> u32 {
575        self.flowinfo
576    }
577
578    /// Changes the flow information associated with this socket address.
579    ///
580    /// See [`SocketAddrV6::flowinfo`]'s documentation for more details.
581    ///
582    /// # Examples
583    ///
584    /// ```
585    /// use std::net::{SocketAddrV6, Ipv6Addr};
586    ///
587    /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
588    /// socket.set_flowinfo(56);
589    /// assert_eq!(socket.flowinfo(), 56);
590    /// ```
591    #[inline]
592    #[stable(feature = "sockaddr_setters", since = "1.9.0")]
593    #[rustc_const_stable(feature = "const_sockaddr_setters", since = "1.87.0")]
594    pub const fn set_flowinfo(&mut self, new_flowinfo: u32) {
595        self.flowinfo = new_flowinfo;
596    }
597
598    /// Returns the scope ID associated with this address.
599    ///
600    /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
601    /// as specified in [IETF RFC 2553, Section 3.3].
602    ///
603    /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
604    ///
605    /// # Examples
606    ///
607    /// ```
608    /// use std::net::{SocketAddrV6, Ipv6Addr};
609    ///
610    /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
611    /// assert_eq!(socket.scope_id(), 78);
612    /// ```
613    #[must_use]
614    #[stable(feature = "rust1", since = "1.0.0")]
615    #[rustc_const_stable(feature = "const_socketaddr", since = "1.69.0")]
616    #[inline]
617    pub const fn scope_id(&self) -> u32 {
618        self.scope_id
619    }
620
621    /// Changes the scope ID associated with this socket address.
622    ///
623    /// See [`SocketAddrV6::scope_id`]'s documentation for more details.
624    ///
625    /// # Examples
626    ///
627    /// ```
628    /// use std::net::{SocketAddrV6, Ipv6Addr};
629    ///
630    /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
631    /// socket.set_scope_id(42);
632    /// assert_eq!(socket.scope_id(), 42);
633    /// ```
634    #[inline]
635    #[stable(feature = "sockaddr_setters", since = "1.9.0")]
636    #[rustc_const_stable(feature = "const_sockaddr_setters", since = "1.87.0")]
637    pub const fn set_scope_id(&mut self, new_scope_id: u32) {
638        self.scope_id = new_scope_id;
639    }
640}
641
642#[stable(feature = "ip_from_ip", since = "1.16.0")]
643#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
644const impl From<SocketAddrV4> for SocketAddr {
645    /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`].
646    #[inline]
647    fn from(sock4: SocketAddrV4) -> SocketAddr {
648        SocketAddr::V4(sock4)
649    }
650}
651
652#[stable(feature = "ip_from_ip", since = "1.16.0")]
653#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
654const impl From<SocketAddrV6> for SocketAddr {
655    /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`].
656    #[inline]
657    fn from(sock6: SocketAddrV6) -> SocketAddr {
658        SocketAddr::V6(sock6)
659    }
660}
661
662#[stable(feature = "addr_from_into_ip", since = "1.17.0")]
663#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
664const impl<I: [const] Into<IpAddr>> From<(I, u16)> for SocketAddr {
665    /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`].
666    ///
667    /// This conversion creates a [`SocketAddr::V4`] for an [`IpAddr::V4`]
668    /// and creates a [`SocketAddr::V6`] for an [`IpAddr::V6`].
669    ///
670    /// `u16` is treated as port of the newly created [`SocketAddr`].
671    fn from(pieces: (I, u16)) -> SocketAddr {
672        SocketAddr::new(pieces.0.into(), pieces.1)
673    }
674}
675
676#[stable(feature = "rust1", since = "1.0.0")]
677impl fmt::Display for SocketAddr {
678    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
679        match *self {
680            SocketAddr::V4(ref a) => a.fmt(f),
681            SocketAddr::V6(ref a) => a.fmt(f),
682        }
683    }
684}
685
686#[stable(feature = "rust1", since = "1.0.0")]
687impl fmt::Debug for SocketAddr {
688    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
689        fmt::Display::fmt(self, fmt)
690    }
691}
692
693#[stable(feature = "rust1", since = "1.0.0")]
694impl fmt::Display for SocketAddrV4 {
695    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
696        // If there are no alignment requirements, write the socket address directly to `f`.
697        // Otherwise, write it to a local buffer and then use `f.pad`.
698        if f.precision().is_none() && f.width().is_none() {
699            write!(f, "{}:{}", self.ip(), self.port())
700        } else {
701            const LONGEST_IPV4_SOCKET_ADDR: &str = "255.255.255.255:65535";
702
703            let mut buf = DisplayBuffer::buffer::<{ LONGEST_IPV4_SOCKET_ADDR.len() }>();
704            let mut buf = DisplayBuffer::new(&mut buf);
705            // Buffer is long enough for the longest possible IPv4 socket address, so this should never fail.
706            write!(buf, "{}:{}", self.ip(), self.port()).unwrap();
707
708            f.pad(buf.as_str())
709        }
710    }
711}
712
713#[stable(feature = "rust1", since = "1.0.0")]
714impl fmt::Debug for SocketAddrV4 {
715    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
716        fmt::Display::fmt(self, fmt)
717    }
718}
719
720#[stable(feature = "rust1", since = "1.0.0")]
721impl fmt::Display for SocketAddrV6 {
722    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723        // If there are no alignment requirements, write the socket address directly to `f`.
724        // Otherwise, write it to a local buffer and then use `f.pad`.
725        if f.precision().is_none() && f.width().is_none() {
726            match self.scope_id() {
727                0 => write!(f, "[{}]:{}", self.ip(), self.port()),
728                scope_id => write!(f, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
729            }
730        } else {
731            const LONGEST_IPV6_SOCKET_ADDR: &str =
732                "[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%4294967295]:65535";
733
734            let mut buf = DisplayBuffer::buffer::<{ LONGEST_IPV6_SOCKET_ADDR.len() }>();
735            let mut buf = DisplayBuffer::new(&mut buf);
736            match self.scope_id() {
737                0 => write!(buf, "[{}]:{}", self.ip(), self.port()),
738                scope_id => write!(buf, "[{}%{}]:{}", self.ip(), scope_id, self.port()),
739            }
740            // Buffer is long enough for the longest possible IPv6 socket address, so this should never fail.
741            .unwrap();
742
743            f.pad(buf.as_str())
744        }
745    }
746}
747
748#[stable(feature = "rust1", since = "1.0.0")]
749impl fmt::Debug for SocketAddrV6 {
750    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
751        fmt::Display::fmt(self, fmt)
752    }
753}