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