]> git.proxmox.com Git - rustc.git/blob - src/libstd/net/addr.rs
New upstream version 1.22.1+dfsg1
[rustc.git] / src / libstd / net / addr.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use fmt;
12 use hash;
13 use io;
14 use mem;
15 use net::{lookup_host, ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
16 use option;
17 use sys::net::netc as c;
18 use sys_common::{FromInner, AsInner, IntoInner};
19 use vec;
20 use iter;
21 use slice;
22
23 /// An internet socket address, either IPv4 or IPv6.
24 ///
25 /// Internet socket addresses consist of an [IP address], a 16-bit port number, as well
26 /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and
27 /// [`SocketAddrV6`]'s respective documentation for more details.
28 ///
29 /// [IP address]: ../../std/net/enum.IpAddr.html
30 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
31 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
32 ///
33 /// # Examples
34 ///
35 /// ```
36 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
37 ///
38 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
39 ///
40 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
41 /// assert_eq!(socket.port(), 8080);
42 /// assert_eq!(socket.is_ipv4(), true);
43 /// ```
44 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub enum SocketAddr {
47 /// An IPv4 socket address.
48 #[stable(feature = "rust1", since = "1.0.0")]
49 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
50 /// An IPv6 socket address.
51 #[stable(feature = "rust1", since = "1.0.0")]
52 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
53 }
54
55 /// An IPv4 socket address.
56 ///
57 /// IPv4 socket addresses consist of an [IPv4 address] and a 16-bit port number, as
58 /// stated in [IETF RFC 793].
59 ///
60 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
61 ///
62 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
63 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
64 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
65 ///
66 /// # Examples
67 ///
68 /// ```
69 /// use std::net::{Ipv4Addr, SocketAddrV4};
70 ///
71 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
72 ///
73 /// assert_eq!("127.0.0.1:8080".parse(), Ok(socket));
74 /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1));
75 /// assert_eq!(socket.port(), 8080);
76 /// ```
77 #[derive(Copy)]
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub struct SocketAddrV4 { inner: c::sockaddr_in }
80
81 /// An IPv6 socket address.
82 ///
83 /// IPv6 socket addresses consist of an [Ipv6 address], a 16-bit port number, as well
84 /// as fields containing the traffic class, the flow label, and a scope identifier
85 /// (see [IETF RFC 2553, Section 3.3] for more details).
86 ///
87 /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses.
88 ///
89 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
90 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
91 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
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 { inner: c::sockaddr_in6 }
107
108 impl SocketAddr {
109 /// Creates a new socket address from an [IP address] and a port number.
110 ///
111 /// [IP address]: ../../std/net/enum.IpAddr.html
112 ///
113 /// # Examples
114 ///
115 /// ```
116 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
117 ///
118 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
119 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
120 /// assert_eq!(socket.port(), 8080);
121 /// ```
122 #[stable(feature = "ip_addr", since = "1.7.0")]
123 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
124 match ip {
125 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
126 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
127 }
128 }
129
130 /// Returns the IP address associated with this socket address.
131 ///
132 /// # Examples
133 ///
134 /// ```
135 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
136 ///
137 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
138 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
139 /// ```
140 #[stable(feature = "ip_addr", since = "1.7.0")]
141 pub fn ip(&self) -> IpAddr {
142 match *self {
143 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
144 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
145 }
146 }
147
148 /// Changes the IP address associated with this socket address.
149 ///
150 /// # Examples
151 ///
152 /// ```
153 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
154 ///
155 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
156 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
157 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
158 /// ```
159 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
160 pub fn set_ip(&mut self, new_ip: IpAddr) {
161 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
162 match (self, new_ip) {
163 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
164 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
165 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
166 }
167 }
168
169 /// Returns the port number 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.port(), 8080);
178 /// ```
179 #[stable(feature = "rust1", since = "1.0.0")]
180 pub fn port(&self) -> u16 {
181 match *self {
182 SocketAddr::V4(ref a) => a.port(),
183 SocketAddr::V6(ref a) => a.port(),
184 }
185 }
186
187 /// Changes the port number associated with this socket address.
188 ///
189 /// # Examples
190 ///
191 /// ```
192 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
193 ///
194 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
195 /// socket.set_port(1025);
196 /// assert_eq!(socket.port(), 1025);
197 /// ```
198 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
199 pub fn set_port(&mut self, new_port: u16) {
200 match *self {
201 SocketAddr::V4(ref mut a) => a.set_port(new_port),
202 SocketAddr::V6(ref mut a) => a.set_port(new_port),
203 }
204 }
205
206 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
207 /// [IPv4 address], and [`false`] otherwise.
208 ///
209 /// [`true`]: ../../std/primitive.bool.html
210 /// [`false`]: ../../std/primitive.bool.html
211 /// [IP address]: ../../std/net/enum.IpAddr.html
212 /// [IPv4 address]: ../../std/net/enum.IpAddr.html#variant.V4
213 ///
214 /// # Examples
215 ///
216 /// ```
217 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
218 ///
219 /// fn main() {
220 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
221 /// assert_eq!(socket.is_ipv4(), true);
222 /// assert_eq!(socket.is_ipv6(), false);
223 /// }
224 /// ```
225 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
226 pub fn is_ipv4(&self) -> bool {
227 match *self {
228 SocketAddr::V4(_) => true,
229 SocketAddr::V6(_) => false,
230 }
231 }
232
233 /// Returns [`true`] if the [IP address] in this `SocketAddr` is an
234 /// [IPv6 address], and [`false`] otherwise.
235 ///
236 /// [`true`]: ../../std/primitive.bool.html
237 /// [`false`]: ../../std/primitive.bool.html
238 /// [IP address]: ../../std/net/enum.IpAddr.html
239 /// [IPv6 address]: ../../std/net/enum.IpAddr.html#variant.V6
240 ///
241 /// # Examples
242 ///
243 /// ```
244 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
245 ///
246 /// fn main() {
247 /// let socket = SocketAddr::new(
248 /// IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
249 /// assert_eq!(socket.is_ipv4(), false);
250 /// assert_eq!(socket.is_ipv6(), true);
251 /// }
252 /// ```
253 #[stable(feature = "sockaddr_checker", since = "1.16.0")]
254 pub fn is_ipv6(&self) -> bool {
255 match *self {
256 SocketAddr::V4(_) => false,
257 SocketAddr::V6(_) => true,
258 }
259 }
260 }
261
262 impl SocketAddrV4 {
263 /// Creates a new socket address from an [IPv4 address] and a port number.
264 ///
265 /// [IPv4 address]: ../../std/net/struct.Ipv4Addr.html
266 ///
267 /// # Examples
268 ///
269 /// ```
270 /// use std::net::{SocketAddrV4, Ipv4Addr};
271 ///
272 /// let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
273 /// ```
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
276 SocketAddrV4 {
277 inner: c::sockaddr_in {
278 sin_family: c::AF_INET as c::sa_family_t,
279 sin_port: hton(port),
280 sin_addr: *ip.as_inner(),
281 .. unsafe { mem::zeroed() }
282 },
283 }
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 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn ip(&self) -> &Ipv4Addr {
298 unsafe {
299 &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
300 }
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.inner.sin_addr = *new_ip.as_inner()
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 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn port(&self) -> u16 {
331 ntoh(self.inner.sin_port)
332 }
333
334 /// Changes the port number associated with this socket address.
335 ///
336 /// # Examples
337 ///
338 /// ```
339 /// use std::net::{SocketAddrV4, Ipv4Addr};
340 ///
341 /// let mut socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
342 /// socket.set_port(4242);
343 /// assert_eq!(socket.port(), 4242);
344 /// ```
345 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
346 pub fn set_port(&mut self, new_port: u16) {
347 self.inner.sin_port = hton(new_port);
348 }
349 }
350
351 impl SocketAddrV6 {
352 /// Creates a new socket address from an [IPv6 address], a 16-bit port number,
353 /// and the `flowinfo` and `scope_id` fields.
354 ///
355 /// For more information on the meaning and layout of the `flowinfo` and `scope_id`
356 /// parameters, see [IETF RFC 2553, Section 3.3].
357 ///
358 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
359 /// [IPv6 address]: ../../std/net/struct.Ipv6Addr.html
360 ///
361 /// # Examples
362 ///
363 /// ```
364 /// use std::net::{SocketAddrV6, Ipv6Addr};
365 ///
366 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
367 /// ```
368 #[stable(feature = "rust1", since = "1.0.0")]
369 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
370 -> SocketAddrV6 {
371 SocketAddrV6 {
372 inner: c::sockaddr_in6 {
373 sin6_family: c::AF_INET6 as c::sa_family_t,
374 sin6_port: hton(port),
375 sin6_addr: *ip.as_inner(),
376 sin6_flowinfo: flowinfo,
377 sin6_scope_id: scope_id,
378 .. unsafe { mem::zeroed() }
379 },
380 }
381 }
382
383 /// Returns the IP address associated with this socket address.
384 ///
385 /// # Examples
386 ///
387 /// ```
388 /// use std::net::{SocketAddrV6, Ipv6Addr};
389 ///
390 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
391 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
392 /// ```
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn ip(&self) -> &Ipv6Addr {
395 unsafe {
396 &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
397 }
398 }
399
400 /// Changes the IP address associated with this socket address.
401 ///
402 /// # Examples
403 ///
404 /// ```
405 /// use std::net::{SocketAddrV6, Ipv6Addr};
406 ///
407 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
408 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
409 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
410 /// ```
411 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
412 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
413 self.inner.sin6_addr = *new_ip.as_inner()
414 }
415
416 /// Returns the port number associated with this socket address.
417 ///
418 /// # Examples
419 ///
420 /// ```
421 /// use std::net::{SocketAddrV6, Ipv6Addr};
422 ///
423 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
424 /// assert_eq!(socket.port(), 8080);
425 /// ```
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn port(&self) -> u16 {
428 ntoh(self.inner.sin6_port)
429 }
430
431 /// Changes the port number associated with this socket address.
432 ///
433 /// # Examples
434 ///
435 /// ```
436 /// use std::net::{SocketAddrV6, Ipv6Addr};
437 ///
438 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
439 /// socket.set_port(4242);
440 /// assert_eq!(socket.port(), 4242);
441 /// ```
442 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
443 pub fn set_port(&mut self, new_port: u16) {
444 self.inner.sin6_port = hton(new_port);
445 }
446
447 /// Returns the flow information associated with this address.
448 ///
449 /// This information corresponds to the `sin6_flowinfo` field in C's `netinet/in.h`,
450 /// as specified in [IETF RFC 2553, Section 3.3].
451 /// It combines information about the flow label and the traffic class as specified
452 /// in [IETF RFC 2460], respectively [Section 6] and [Section 7].
453 ///
454 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
455 /// [IETF RFC 2460]: https://tools.ietf.org/html/rfc2460
456 /// [Section 6]: https://tools.ietf.org/html/rfc2460#section-6
457 /// [Section 7]: https://tools.ietf.org/html/rfc2460#section-7
458 ///
459 /// # Examples
460 ///
461 /// ```
462 /// use std::net::{SocketAddrV6, Ipv6Addr};
463 ///
464 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
465 /// assert_eq!(socket.flowinfo(), 10);
466 /// ```
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub fn flowinfo(&self) -> u32 {
469 self.inner.sin6_flowinfo
470 }
471
472 /// Changes the flow information associated with this socket address.
473 ///
474 /// See the [`flowinfo`] method's documentation for more details.
475 ///
476 /// [`flowinfo`]: #method.flowinfo
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use std::net::{SocketAddrV6, Ipv6Addr};
482 ///
483 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
484 /// socket.set_flowinfo(56);
485 /// assert_eq!(socket.flowinfo(), 56);
486 /// ```
487 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
488 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
489 self.inner.sin6_flowinfo = new_flowinfo;
490 }
491
492 /// Returns the scope ID associated with this address.
493 ///
494 /// This information corresponds to the `sin6_scope_id` field in C's `netinet/in.h`,
495 /// as specified in [IETF RFC 2553, Section 3.3].
496 ///
497 /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3
498 ///
499 /// # Examples
500 ///
501 /// ```
502 /// use std::net::{SocketAddrV6, Ipv6Addr};
503 ///
504 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
505 /// assert_eq!(socket.scope_id(), 78);
506 /// ```
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn scope_id(&self) -> u32 {
509 self.inner.sin6_scope_id
510 }
511
512 /// Change the scope ID associated with this socket address.
513 ///
514 /// See the [`scope_id`] method's documentation for more details.
515 ///
516 /// [`scope_id`]: #method.scope_id
517 ///
518 /// # Examples
519 ///
520 /// ```
521 /// use std::net::{SocketAddrV6, Ipv6Addr};
522 ///
523 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
524 /// socket.set_scope_id(42);
525 /// assert_eq!(socket.scope_id(), 42);
526 /// ```
527 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
528 pub fn set_scope_id(&mut self, new_scope_id: u32) {
529 self.inner.sin6_scope_id = new_scope_id;
530 }
531 }
532
533 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
534 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
535 SocketAddrV4 { inner: addr }
536 }
537 }
538
539 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
540 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
541 SocketAddrV6 { inner: addr }
542 }
543 }
544
545 #[stable(feature = "ip_from_ip", since = "1.16.0")]
546 impl From<SocketAddrV4> for SocketAddr {
547 fn from(sock4: SocketAddrV4) -> SocketAddr {
548 SocketAddr::V4(sock4)
549 }
550 }
551
552 #[stable(feature = "ip_from_ip", since = "1.16.0")]
553 impl From<SocketAddrV6> for SocketAddr {
554 fn from(sock6: SocketAddrV6) -> SocketAddr {
555 SocketAddr::V6(sock6)
556 }
557 }
558
559 #[stable(feature = "addr_from_into_ip", since = "1.17.0")]
560 impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr {
561 fn from(pieces: (I, u16)) -> SocketAddr {
562 SocketAddr::new(pieces.0.into(), pieces.1)
563 }
564 }
565
566 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
567 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
568 match *self {
569 SocketAddr::V4(ref a) => {
570 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
571 }
572 SocketAddr::V6(ref a) => {
573 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
574 }
575 }
576 }
577 }
578
579 #[stable(feature = "rust1", since = "1.0.0")]
580 impl fmt::Display for SocketAddr {
581 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
582 match *self {
583 SocketAddr::V4(ref a) => a.fmt(f),
584 SocketAddr::V6(ref a) => a.fmt(f),
585 }
586 }
587 }
588
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl fmt::Display for SocketAddrV4 {
591 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
592 write!(f, "{}:{}", self.ip(), self.port())
593 }
594 }
595
596 #[stable(feature = "rust1", since = "1.0.0")]
597 impl fmt::Debug for SocketAddrV4 {
598 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
599 fmt::Display::fmt(self, fmt)
600 }
601 }
602
603 #[stable(feature = "rust1", since = "1.0.0")]
604 impl fmt::Display for SocketAddrV6 {
605 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
606 write!(f, "[{}]:{}", self.ip(), self.port())
607 }
608 }
609
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl fmt::Debug for SocketAddrV6 {
612 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
613 fmt::Display::fmt(self, fmt)
614 }
615 }
616
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl Clone for SocketAddrV4 {
619 fn clone(&self) -> SocketAddrV4 { *self }
620 }
621 #[stable(feature = "rust1", since = "1.0.0")]
622 impl Clone for SocketAddrV6 {
623 fn clone(&self) -> SocketAddrV6 { *self }
624 }
625
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl PartialEq for SocketAddrV4 {
628 fn eq(&self, other: &SocketAddrV4) -> bool {
629 self.inner.sin_port == other.inner.sin_port &&
630 self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
631 }
632 }
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl PartialEq for SocketAddrV6 {
635 fn eq(&self, other: &SocketAddrV6) -> bool {
636 self.inner.sin6_port == other.inner.sin6_port &&
637 self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
638 self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
639 self.inner.sin6_scope_id == other.inner.sin6_scope_id
640 }
641 }
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl Eq for SocketAddrV4 {}
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl Eq for SocketAddrV6 {}
646
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl hash::Hash for SocketAddrV4 {
649 fn hash<H: hash::Hasher>(&self, s: &mut H) {
650 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
651 }
652 }
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl hash::Hash for SocketAddrV6 {
655 fn hash<H: hash::Hasher>(&self, s: &mut H) {
656 (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
657 self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
658 }
659 }
660
661 /// A trait for objects which can be converted or resolved to one or more
662 /// [`SocketAddr`] values.
663 ///
664 /// This trait is used for generic address resolution when constructing network
665 /// objects. By default it is implemented for the following types:
666 ///
667 /// * [`SocketAddr`]: [`to_socket_addrs`] is the identity function.
668 ///
669 /// * [`SocketAddrV4`], [`SocketAddrV6`], `(`[`IpAddr`]`, `[`u16`]`)`,
670 /// `(`[`Ipv4Addr`]`, `[`u16`]`)`, `(`[`Ipv6Addr`]`, `[`u16`]`)`:
671 /// [`to_socket_addrs`] constructs a [`SocketAddr`] trivially.
672 ///
673 /// * `(`[`&str`]`, `[`u16`]`)`: the string should be either a string representation
674 /// of an [`IpAddr`] address as expected by [`FromStr`] implementation or a host
675 /// name.
676 ///
677 /// * [`&str`]: the string should be either a string representation of a
678 /// [`SocketAddr`] as expected by its [`FromStr`] implementation or a string like
679 /// `<host_name>:<port>` pair where `<port>` is a [`u16`] value.
680 ///
681 /// This trait allows constructing network objects like [`TcpStream`] or
682 /// [`UdpSocket`] easily with values of various types for the bind/connection
683 /// address. It is needed because sometimes one type is more appropriate than
684 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
685 /// than manual construction of the corresponding [`SocketAddr`], but sometimes
686 /// [`SocketAddr`] value is *the* main source of the address, and converting it to
687 /// some other type (e.g. a string) just for it to be converted back to
688 /// [`SocketAddr`] in constructor methods is pointless.
689 ///
690 /// Addresses returned by the operating system that are not IP addresses are
691 /// silently ignored.
692 ///
693 /// [`FromStr`]: ../../std/str/trait.FromStr.html
694 /// [`IpAddr`]: ../../std/net/enum.IpAddr.html
695 /// [`Ipv4Addr`]: ../../std/net/struct.Ipv4Addr.html
696 /// [`Ipv6Addr`]: ../../std/net/struct.Ipv6Addr.html
697 /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
698 /// [`SocketAddrV4`]: ../../std/net/struct.SocketAddrV4.html
699 /// [`SocketAddrV6`]: ../../std/net/struct.SocketAddrV6.html
700 /// [`&str`]: ../../std/primitive.str.html
701 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
702 /// [`to_socket_addrs`]: #tymethod.to_socket_addrs
703 /// [`UdpSocket`]: ../../std/net/struct.UdpSocket.html
704 /// [`u16`]: ../../std/primitive.u16.html
705 ///
706 /// # Examples
707 ///
708 /// Creating a [`SocketAddr`] iterator that yields one item:
709 ///
710 /// ```
711 /// use std::net::{ToSocketAddrs, SocketAddr};
712 ///
713 /// let addr = SocketAddr::from(([127, 0, 0, 1], 443));
714 /// let mut addrs_iter = addr.to_socket_addrs().unwrap();
715 ///
716 /// assert_eq!(Some(addr), addrs_iter.next());
717 /// assert!(addrs_iter.next().is_none());
718 /// ```
719 ///
720 /// Creating a [`SocketAddr`] iterator from a hostname:
721 ///
722 /// ```no_run
723 /// use std::net::{SocketAddr, ToSocketAddrs};
724 ///
725 /// // assuming 'localhost' resolves to 127.0.0.1
726 /// let mut addrs_iter = "localhost:443".to_socket_addrs().unwrap();
727 /// assert_eq!(addrs_iter.next(), Some(SocketAddr::from(([127, 0, 0, 1], 443))));
728 /// assert!(addrs_iter.next().is_none());
729 ///
730 /// // assuming 'foo' does not resolve
731 /// assert!("foo:443".to_socket_addrs().is_err());
732 /// ```
733 ///
734 /// Creating a [`SocketAddr`] iterator that yields multiple items:
735 ///
736 /// ```
737 /// use std::net::{SocketAddr, ToSocketAddrs};
738 ///
739 /// let addr1 = SocketAddr::from(([0, 0, 0, 0], 80));
740 /// let addr2 = SocketAddr::from(([127, 0, 0, 1], 443));
741 /// let addrs = vec![addr1, addr2];
742 ///
743 /// let mut addrs_iter = (&addrs[..]).to_socket_addrs().unwrap();
744 ///
745 /// assert_eq!(Some(addr1), addrs_iter.next());
746 /// assert_eq!(Some(addr2), addrs_iter.next());
747 /// assert!(addrs_iter.next().is_none());
748 /// ```
749 ///
750 /// Attempting to create a [`SocketAddr`] iterator from an improperly formatted
751 /// socket address `&str` (missing the port):
752 ///
753 /// ```
754 /// use std::io;
755 /// use std::net::ToSocketAddrs;
756 ///
757 /// let err = "127.0.0.1".to_socket_addrs().unwrap_err();
758 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
759 /// ```
760 ///
761 /// [`TcpStream::connect`] is an example of an function that utilizes
762 /// `ToSocketsAddr` as a trait bound on its parameter in order to accept
763 /// different types:
764 ///
765 /// ```no_run
766 /// use std::net::{TcpStream, Ipv4Addr};
767 ///
768 /// let stream = TcpStream::connect(("127.0.0.1", 443));
769 /// // or
770 /// let stream = TcpStream::connect("127.0.0.1:443");
771 /// // or
772 /// let stream = TcpStream::connect((Ipv4Addr::new(127, 0, 0, 1), 443));
773 /// ```
774 ///
775 /// [`TcpStream::connect`]: ../../std/net/struct.TcpStream.html#method.connect
776 #[stable(feature = "rust1", since = "1.0.0")]
777 pub trait ToSocketAddrs {
778 /// Returned iterator over socket addresses which this type may correspond
779 /// to.
780 #[stable(feature = "rust1", since = "1.0.0")]
781 type Iter: Iterator<Item=SocketAddr>;
782
783 /// Converts this object to an iterator of resolved `SocketAddr`s.
784 ///
785 /// The returned iterator may not actually yield any values depending on the
786 /// outcome of any resolution performed.
787 ///
788 /// Note that this function may block the current thread while resolution is
789 /// performed.
790 #[stable(feature = "rust1", since = "1.0.0")]
791 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
792 }
793
794 #[stable(feature = "rust1", since = "1.0.0")]
795 impl ToSocketAddrs for SocketAddr {
796 type Iter = option::IntoIter<SocketAddr>;
797 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
798 Ok(Some(*self).into_iter())
799 }
800 }
801
802 #[stable(feature = "rust1", since = "1.0.0")]
803 impl ToSocketAddrs for SocketAddrV4 {
804 type Iter = option::IntoIter<SocketAddr>;
805 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
806 SocketAddr::V4(*self).to_socket_addrs()
807 }
808 }
809
810 #[stable(feature = "rust1", since = "1.0.0")]
811 impl ToSocketAddrs for SocketAddrV6 {
812 type Iter = option::IntoIter<SocketAddr>;
813 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
814 SocketAddr::V6(*self).to_socket_addrs()
815 }
816 }
817
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl ToSocketAddrs for (IpAddr, u16) {
820 type Iter = option::IntoIter<SocketAddr>;
821 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
822 let (ip, port) = *self;
823 match ip {
824 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
825 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
826 }
827 }
828 }
829
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl ToSocketAddrs for (Ipv4Addr, u16) {
832 type Iter = option::IntoIter<SocketAddr>;
833 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
834 let (ip, port) = *self;
835 SocketAddrV4::new(ip, port).to_socket_addrs()
836 }
837 }
838
839 #[stable(feature = "rust1", since = "1.0.0")]
840 impl ToSocketAddrs for (Ipv6Addr, u16) {
841 type Iter = option::IntoIter<SocketAddr>;
842 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
843 let (ip, port) = *self;
844 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
845 }
846 }
847
848 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
849 let ips = lookup_host(s)?;
850 let v: Vec<_> = ips.map(|mut a| { a.set_port(p); a }).collect();
851 Ok(v.into_iter())
852 }
853
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl<'a> ToSocketAddrs for (&'a str, u16) {
856 type Iter = vec::IntoIter<SocketAddr>;
857 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
858 let (host, port) = *self;
859
860 // try to parse the host as a regular IP address first
861 if let Ok(addr) = host.parse::<Ipv4Addr>() {
862 let addr = SocketAddrV4::new(addr, port);
863 return Ok(vec![SocketAddr::V4(addr)].into_iter())
864 }
865 if let Ok(addr) = host.parse::<Ipv6Addr>() {
866 let addr = SocketAddrV6::new(addr, port, 0, 0);
867 return Ok(vec![SocketAddr::V6(addr)].into_iter())
868 }
869
870 resolve_socket_addr(host, port)
871 }
872 }
873
874 // accepts strings like 'localhost:12345'
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl ToSocketAddrs for str {
877 type Iter = vec::IntoIter<SocketAddr>;
878 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
879 // try to parse as a regular SocketAddr first
880 if let Some(addr) = self.parse().ok() {
881 return Ok(vec![addr].into_iter());
882 }
883
884 macro_rules! try_opt {
885 ($e:expr, $msg:expr) => (
886 match $e {
887 Some(r) => r,
888 None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
889 $msg)),
890 }
891 )
892 }
893
894 // split the string by ':' and convert the second part to u16
895 let mut parts_iter = self.rsplitn(2, ':');
896 let port_str = try_opt!(parts_iter.next(), "invalid socket address");
897 let host = try_opt!(parts_iter.next(), "invalid socket address");
898 let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
899 resolve_socket_addr(host, port)
900 }
901 }
902
903 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
904 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
905 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
906
907 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
908 Ok(self.iter().cloned())
909 }
910 }
911
912 #[stable(feature = "rust1", since = "1.0.0")]
913 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
914 type Iter = T::Iter;
915 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
916 (**self).to_socket_addrs()
917 }
918 }
919
920 #[stable(feature = "string_to_socket_addrs", since = "1.16.0")]
921 impl ToSocketAddrs for String {
922 type Iter = vec::IntoIter<SocketAddr>;
923 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
924 (&**self).to_socket_addrs()
925 }
926 }
927
928 #[cfg(all(test, not(target_os = "emscripten")))]
929 mod tests {
930 use net::*;
931 use net::test::{tsa, sa6, sa4};
932
933 #[test]
934 fn to_socket_addr_ipaddr_u16() {
935 let a = Ipv4Addr::new(77, 88, 21, 11);
936 let p = 12345;
937 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
938 assert_eq!(Ok(vec![e]), tsa((a, p)));
939 }
940
941 #[test]
942 fn to_socket_addr_str_u16() {
943 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
944 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
945
946 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
947 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
948
949 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
950 assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
951 }
952
953 #[test]
954 fn to_socket_addr_str() {
955 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
956 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
957
958 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
959 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
960
961 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
962 assert!(tsa("localhost:23924").unwrap().contains(&a));
963 }
964
965 #[test]
966 fn to_socket_addr_string() {
967 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
968 assert_eq!(Ok(vec![a]), tsa(&*format!("{}:{}", "77.88.21.11", "24352")));
969 assert_eq!(Ok(vec![a]), tsa(&format!("{}:{}", "77.88.21.11", "24352")));
970 assert_eq!(Ok(vec![a]), tsa(format!("{}:{}", "77.88.21.11", "24352")));
971
972 let s = format!("{}:{}", "77.88.21.11", "24352");
973 assert_eq!(Ok(vec![a]), tsa(s));
974 // s has been moved into the tsa call
975 }
976
977 // FIXME: figure out why this fails on openbsd and bitrig and fix it
978 #[test]
979 #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
980 fn to_socket_addr_str_bad() {
981 assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
982 }
983
984 #[test]
985 fn set_ip() {
986 fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
987 fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
988
989 let mut v4 = SocketAddrV4::new(ip4(11), 80);
990 assert_eq!(v4.ip(), &ip4(11));
991 v4.set_ip(ip4(12));
992 assert_eq!(v4.ip(), &ip4(12));
993
994 let mut addr = SocketAddr::V4(v4);
995 assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
996 addr.set_ip(IpAddr::V4(ip4(13)));
997 assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
998 addr.set_ip(IpAddr::V6(ip6(14)));
999 assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
1000
1001 let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
1002 assert_eq!(v6.ip(), &ip6(1));
1003 v6.set_ip(ip6(2));
1004 assert_eq!(v6.ip(), &ip6(2));
1005
1006 let mut addr = SocketAddr::V6(v6);
1007 assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
1008 addr.set_ip(IpAddr::V6(ip6(3)));
1009 assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
1010 addr.set_ip(IpAddr::V4(ip4(4)));
1011 assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
1012 }
1013
1014 #[test]
1015 fn set_port() {
1016 let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
1017 assert_eq!(v4.port(), 80);
1018 v4.set_port(443);
1019 assert_eq!(v4.port(), 443);
1020
1021 let mut addr = SocketAddr::V4(v4);
1022 assert_eq!(addr.port(), 443);
1023 addr.set_port(8080);
1024 assert_eq!(addr.port(), 8080);
1025
1026 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
1027 assert_eq!(v6.port(), 80);
1028 v6.set_port(443);
1029 assert_eq!(v6.port(), 443);
1030
1031 let mut addr = SocketAddr::V6(v6);
1032 assert_eq!(addr.port(), 443);
1033 addr.set_port(8080);
1034 assert_eq!(addr.port(), 8080);
1035 }
1036
1037 #[test]
1038 fn set_flowinfo() {
1039 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
1040 assert_eq!(v6.flowinfo(), 10);
1041 v6.set_flowinfo(20);
1042 assert_eq!(v6.flowinfo(), 20);
1043 }
1044
1045 #[test]
1046 fn set_scope_id() {
1047 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
1048 assert_eq!(v6.scope_id(), 10);
1049 v6.set_scope_id(20);
1050 assert_eq!(v6.scope_id(), 20);
1051 }
1052
1053 #[test]
1054 fn is_v4() {
1055 let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
1056 assert!(v4.is_ipv4());
1057 assert!(!v4.is_ipv6());
1058 }
1059
1060 #[test]
1061 fn is_v6() {
1062 let v6 = SocketAddr::V6(SocketAddrV6::new(
1063 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
1064 assert!(!v6.is_ipv4());
1065 assert!(v6.is_ipv6());
1066 }
1067 }