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.
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.
15 use net::{lookup_host, ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr};
17 use sys::net::netc as c;
18 use sys_common::{FromInner, AsInner, IntoInner};
23 /// Representation of a socket address for networking applications.
25 /// A socket address can either represent the IPv4 or IPv6 protocol and is
26 /// paired with at least a port number as well. Each protocol may have more
27 /// specific information about the address available to it as well.
28 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
29 #[stable(feature = "rust1", since = "1.0.0")]
31 /// An IPv4 socket address which is a (ip, port) combination.
32 #[stable(feature = "rust1", since = "1.0.0")]
33 V4(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV4),
34 /// An IPv6 socket address.
35 #[stable(feature = "rust1", since = "1.0.0")]
36 V6(#[stable(feature = "rust1", since = "1.0.0")] SocketAddrV6),
39 /// An IPv4 socket address which is a (ip, port) combination.
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub struct SocketAddrV4 { inner: c::sockaddr_in }
44 /// An IPv6 socket address.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
50 /// Creates a new socket address from the (ip, port) pair.
55 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
57 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
58 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
59 /// assert_eq!(socket.port(), 8080);
61 #[stable(feature = "ip_addr", since = "1.7.0")]
62 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
64 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
65 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
69 /// Returns the IP address associated with this socket address.
74 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
76 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
77 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
79 #[stable(feature = "ip_addr", since = "1.7.0")]
80 pub fn ip(&self) -> IpAddr {
82 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
83 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
87 /// Change the IP address associated with this socket address.
92 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
94 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
95 /// socket.set_ip(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
96 /// assert_eq!(socket.ip(), IpAddr::V4(Ipv4Addr::new(10, 10, 0, 1)));
98 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
99 pub fn set_ip(&mut self, new_ip: IpAddr) {
100 // `match (*self, new_ip)` would have us mutate a copy of self only to throw it away.
101 match (self, new_ip) {
102 (&mut SocketAddr::V4(ref mut a), IpAddr::V4(new_ip)) => a.set_ip(new_ip),
103 (&mut SocketAddr::V6(ref mut a), IpAddr::V6(new_ip)) => a.set_ip(new_ip),
104 (self_, new_ip) => *self_ = Self::new(new_ip, self_.port()),
108 /// Returns the port number associated with this socket address.
113 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
115 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
116 /// assert_eq!(socket.port(), 8080);
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub fn port(&self) -> u16 {
121 SocketAddr::V4(ref a) => a.port(),
122 SocketAddr::V6(ref a) => a.port(),
126 /// Change the port number associated with this socket address.
131 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
133 /// let mut socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
134 /// socket.set_port(1025);
135 /// assert_eq!(socket.port(), 1025);
137 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
138 pub fn set_port(&mut self, new_port: u16) {
140 SocketAddr::V4(ref mut a) => a.set_port(new_port),
141 SocketAddr::V6(ref mut a) => a.set_port(new_port),
145 /// Returns true if the IP in this `SocketAddr` is a valid IPv4 address,
146 /// false if it's a valid IPv6 address.
151 /// #![feature(sockaddr_checker)]
153 /// use std::net::{IpAddr, Ipv4Addr, SocketAddr};
156 /// let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
157 /// assert_eq!(socket.is_ipv4(), true);
158 /// assert_eq!(socket.is_ipv6(), false);
161 #[unstable(feature = "sockaddr_checker", issue = "36949")]
162 pub fn is_ipv4(&self) -> bool {
164 SocketAddr::V4(_) => true,
165 SocketAddr::V6(_) => false,
169 /// Returns true if the IP in this `SocketAddr` is a valid IPv6 address,
170 /// false if it's a valid IPv4 address.
175 /// #![feature(sockaddr_checker)]
177 /// use std::net::{IpAddr, Ipv6Addr, SocketAddr};
180 /// let socket = SocketAddr::new(
181 /// IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 65535, 0, 1)), 8080);
182 /// assert_eq!(socket.is_ipv4(), false);
183 /// assert_eq!(socket.is_ipv6(), true);
186 #[unstable(feature = "sockaddr_checker", issue = "36949")]
187 pub fn is_ipv6(&self) -> bool {
189 SocketAddr::V4(_) => false,
190 SocketAddr::V6(_) => true,
196 /// Creates a new socket address from the (ip, port) pair.
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
200 inner: c::sockaddr_in {
201 sin_family: c::AF_INET as c::sa_family_t,
202 sin_port: hton(port),
203 sin_addr: *ip.as_inner(),
204 .. unsafe { mem::zeroed() }
209 /// Returns the IP address associated with this socket address.
210 #[stable(feature = "rust1", since = "1.0.0")]
211 pub fn ip(&self) -> &Ipv4Addr {
213 &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
217 /// Change the IP address associated with this socket address.
218 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
219 pub fn set_ip(&mut self, new_ip: Ipv4Addr) {
220 self.inner.sin_addr = *new_ip.as_inner()
223 /// Returns the port number associated with this socket address.
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn port(&self) -> u16 {
226 ntoh(self.inner.sin_port)
229 /// Change the port number associated with this socket address.
230 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
231 pub fn set_port(&mut self, new_port: u16) {
232 self.inner.sin_port = hton(new_port);
237 /// Creates a new socket address from the ip/port/flowinfo/scope_id
243 /// use std::net::{SocketAddrV6, Ipv6Addr};
245 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
247 #[stable(feature = "rust1", since = "1.0.0")]
248 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
251 inner: c::sockaddr_in6 {
252 sin6_family: c::AF_INET6 as c::sa_family_t,
253 sin6_port: hton(port),
254 sin6_addr: *ip.as_inner(),
255 sin6_flowinfo: flowinfo,
256 sin6_scope_id: scope_id,
257 .. unsafe { mem::zeroed() }
262 /// Returns the IP address associated with this socket address.
267 /// use std::net::{SocketAddrV6, Ipv6Addr};
269 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
270 /// assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub fn ip(&self) -> &Ipv6Addr {
275 &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
279 /// Change the IP address associated with this socket address.
284 /// use std::net::{SocketAddrV6, Ipv6Addr};
286 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
287 /// socket.set_ip(Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
288 /// assert_eq!(socket.ip(), &Ipv6Addr::new(76, 45, 0, 0, 0, 0, 0, 0));
290 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
291 pub fn set_ip(&mut self, new_ip: Ipv6Addr) {
292 self.inner.sin6_addr = *new_ip.as_inner()
295 /// Returns the port number associated with this socket address.
300 /// use std::net::{SocketAddrV6, Ipv6Addr};
302 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
303 /// assert_eq!(socket.port(), 8080);
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn port(&self) -> u16 {
307 ntoh(self.inner.sin6_port)
310 /// Change the port number associated with this socket address.
315 /// use std::net::{SocketAddrV6, Ipv6Addr};
317 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0);
318 /// socket.set_port(4242);
319 /// assert_eq!(socket.port(), 4242);
321 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
322 pub fn set_port(&mut self, new_port: u16) {
323 self.inner.sin6_port = hton(new_port);
326 /// Returns the flow information associated with this address,
327 /// corresponding to the `sin6_flowinfo` field in C.
332 /// use std::net::{SocketAddrV6, Ipv6Addr};
334 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
335 /// assert_eq!(socket.flowinfo(), 10);
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn flowinfo(&self) -> u32 {
339 self.inner.sin6_flowinfo
342 /// Change the flow information associated with this socket address.
347 /// use std::net::{SocketAddrV6, Ipv6Addr};
349 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0);
350 /// socket.set_flowinfo(56);
351 /// assert_eq!(socket.flowinfo(), 56);
353 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
354 pub fn set_flowinfo(&mut self, new_flowinfo: u32) {
355 self.inner.sin6_flowinfo = new_flowinfo;
358 /// Returns the scope ID associated with this address,
359 /// corresponding to the `sin6_scope_id` field in C.
364 /// use std::net::{SocketAddrV6, Ipv6Addr};
366 /// let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
367 /// assert_eq!(socket.scope_id(), 78);
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn scope_id(&self) -> u32 {
371 self.inner.sin6_scope_id
374 /// Change the scope ID associated with this socket address.
379 /// use std::net::{SocketAddrV6, Ipv6Addr};
381 /// let mut socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78);
382 /// socket.set_scope_id(42);
383 /// assert_eq!(socket.scope_id(), 42);
385 #[stable(feature = "sockaddr_setters", since = "1.9.0")]
386 pub fn set_scope_id(&mut self, new_scope_id: u32) {
387 self.inner.sin6_scope_id = new_scope_id;
391 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
392 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
393 SocketAddrV4 { inner: addr }
397 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
398 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
399 SocketAddrV6 { inner: addr }
403 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
404 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
406 SocketAddr::V4(ref a) => {
407 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
409 SocketAddr::V6(ref a) => {
410 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
416 #[stable(feature = "rust1", since = "1.0.0")]
417 impl fmt::Display for SocketAddr {
418 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
420 SocketAddr::V4(ref a) => a.fmt(f),
421 SocketAddr::V6(ref a) => a.fmt(f),
426 #[stable(feature = "rust1", since = "1.0.0")]
427 impl fmt::Display for SocketAddrV4 {
428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
429 write!(f, "{}:{}", self.ip(), self.port())
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl fmt::Debug for SocketAddrV4 {
435 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
436 fmt::Display::fmt(self, fmt)
440 #[stable(feature = "rust1", since = "1.0.0")]
441 impl fmt::Display for SocketAddrV6 {
442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
443 write!(f, "[{}]:{}", self.ip(), self.port())
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl fmt::Debug for SocketAddrV6 {
449 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
450 fmt::Display::fmt(self, fmt)
454 #[stable(feature = "rust1", since = "1.0.0")]
455 impl Clone for SocketAddrV4 {
456 fn clone(&self) -> SocketAddrV4 { *self }
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl Clone for SocketAddrV6 {
460 fn clone(&self) -> SocketAddrV6 { *self }
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl PartialEq for SocketAddrV4 {
465 fn eq(&self, other: &SocketAddrV4) -> bool {
466 self.inner.sin_port == other.inner.sin_port &&
467 self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl PartialEq for SocketAddrV6 {
472 fn eq(&self, other: &SocketAddrV6) -> bool {
473 self.inner.sin6_port == other.inner.sin6_port &&
474 self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
475 self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
476 self.inner.sin6_scope_id == other.inner.sin6_scope_id
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl Eq for SocketAddrV4 {}
481 #[stable(feature = "rust1", since = "1.0.0")]
482 impl Eq for SocketAddrV6 {}
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl hash::Hash for SocketAddrV4 {
486 fn hash<H: hash::Hasher>(&self, s: &mut H) {
487 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl hash::Hash for SocketAddrV6 {
492 fn hash<H: hash::Hasher>(&self, s: &mut H) {
493 (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
494 self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
498 /// A trait for objects which can be converted or resolved to one or more
499 /// `SocketAddr` values.
501 /// This trait is used for generic address resolution when constructing network
502 /// objects. By default it is implemented for the following types:
504 /// * `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` - `to_socket_addrs` is
505 /// identity function.
507 /// * `(IpvNAddr, u16)` - `to_socket_addrs` constructs `SocketAddr` trivially.
509 /// * `(&str, u16)` - the string should be either a string representation of an
510 /// IP address expected by `FromStr` implementation for `IpvNAddr` or a host
513 /// * `&str` - the string should be either a string representation of a
514 /// `SocketAddr` as expected by its `FromStr` implementation or a string like
515 /// `<host_name>:<port>` pair where `<port>` is a `u16` value.
517 /// This trait allows constructing network objects like `TcpStream` or
518 /// `UdpSocket` easily with values of various types for the bind/connection
519 /// address. It is needed because sometimes one type is more appropriate than
520 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
521 /// than manual construction of the corresponding `SocketAddr`, but sometimes
522 /// `SocketAddr` value is *the* main source of the address, and converting it to
523 /// some other type (e.g. a string) just for it to be converted back to
524 /// `SocketAddr` in constructor methods is pointless.
526 /// Addresses returned by the operating system that are not IP addresses are
527 /// silently ignored.
532 /// use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
535 /// let ip = Ipv4Addr::new(127, 0, 0, 1);
536 /// let port = 12345;
538 /// // The following lines are equivalent modulo possible "localhost" name
539 /// // resolution differences
540 /// let tcp_s = TcpStream::connect(SocketAddrV4::new(ip, port));
541 /// let tcp_s = TcpStream::connect((ip, port));
542 /// let tcp_s = TcpStream::connect(("127.0.0.1", port));
543 /// let tcp_s = TcpStream::connect(("localhost", port));
544 /// let tcp_s = TcpStream::connect("127.0.0.1:12345");
545 /// let tcp_s = TcpStream::connect("localhost:12345");
547 /// // TcpListener::bind(), UdpSocket::bind() and UdpSocket::send_to()
548 /// // behave similarly
549 /// let tcp_l = TcpListener::bind("localhost:12345");
551 /// let mut udp_s = UdpSocket::bind(("127.0.0.1", port)).unwrap();
552 /// udp_s.send_to(&[7], (ip, 23451)).unwrap();
555 #[stable(feature = "rust1", since = "1.0.0")]
556 pub trait ToSocketAddrs {
557 /// Returned iterator over socket addresses which this type may correspond
559 #[stable(feature = "rust1", since = "1.0.0")]
560 type Iter: Iterator<Item=SocketAddr>;
562 /// Converts this object to an iterator of resolved `SocketAddr`s.
564 /// The returned iterator may not actually yield any values depending on the
565 /// outcome of any resolution performed.
567 /// Note that this function may block the current thread while resolution is
572 /// Any errors encountered during resolution will be returned as an `Err`.
573 #[stable(feature = "rust1", since = "1.0.0")]
574 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
577 #[stable(feature = "rust1", since = "1.0.0")]
578 impl ToSocketAddrs for SocketAddr {
579 type Iter = option::IntoIter<SocketAddr>;
580 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
581 Ok(Some(*self).into_iter())
585 #[stable(feature = "rust1", since = "1.0.0")]
586 impl ToSocketAddrs for SocketAddrV4 {
587 type Iter = option::IntoIter<SocketAddr>;
588 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
589 SocketAddr::V4(*self).to_socket_addrs()
593 #[stable(feature = "rust1", since = "1.0.0")]
594 impl ToSocketAddrs for SocketAddrV6 {
595 type Iter = option::IntoIter<SocketAddr>;
596 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
597 SocketAddr::V6(*self).to_socket_addrs()
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl ToSocketAddrs for (IpAddr, u16) {
603 type Iter = option::IntoIter<SocketAddr>;
604 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
605 let (ip, port) = *self;
607 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
608 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
613 #[stable(feature = "rust1", since = "1.0.0")]
614 impl ToSocketAddrs for (Ipv4Addr, u16) {
615 type Iter = option::IntoIter<SocketAddr>;
616 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
617 let (ip, port) = *self;
618 SocketAddrV4::new(ip, port).to_socket_addrs()
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl ToSocketAddrs for (Ipv6Addr, u16) {
624 type Iter = option::IntoIter<SocketAddr>;
625 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
626 let (ip, port) = *self;
627 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
631 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
632 let ips = lookup_host(s)?;
633 let v: Vec<_> = ips.map(|mut a| { a.set_port(p); a }).collect();
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl<'a> ToSocketAddrs for (&'a str, u16) {
639 type Iter = vec::IntoIter<SocketAddr>;
640 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
641 let (host, port) = *self;
643 // try to parse the host as a regular IP address first
644 if let Ok(addr) = host.parse::<Ipv4Addr>() {
645 let addr = SocketAddrV4::new(addr, port);
646 return Ok(vec![SocketAddr::V4(addr)].into_iter())
648 if let Ok(addr) = host.parse::<Ipv6Addr>() {
649 let addr = SocketAddrV6::new(addr, port, 0, 0);
650 return Ok(vec![SocketAddr::V6(addr)].into_iter())
653 resolve_socket_addr(host, port)
657 // accepts strings like 'localhost:12345'
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl ToSocketAddrs for str {
660 type Iter = vec::IntoIter<SocketAddr>;
661 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
662 // try to parse as a regular SocketAddr first
663 if let Some(addr) = self.parse().ok() {
664 return Ok(vec![addr].into_iter());
667 macro_rules! try_opt {
668 ($e:expr, $msg:expr) => (
671 None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
677 // split the string by ':' and convert the second part to u16
678 let mut parts_iter = self.rsplitn(2, ':');
679 let port_str = try_opt!(parts_iter.next(), "invalid socket address");
680 let host = try_opt!(parts_iter.next(), "invalid socket address");
681 let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
682 resolve_socket_addr(host, port)
686 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
687 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
688 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
690 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
691 Ok(self.iter().cloned())
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
698 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
699 (**self).to_socket_addrs()
703 #[cfg(all(test, not(target_os = "emscripten")))]
706 use net::test::{tsa, sa6, sa4};
709 fn to_socket_addr_ipaddr_u16() {
710 let a = Ipv4Addr::new(77, 88, 21, 11);
712 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
713 assert_eq!(Ok(vec![e]), tsa((a, p)));
717 fn to_socket_addr_str_u16() {
718 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
719 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
721 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
722 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
724 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
725 assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
729 fn to_socket_addr_str() {
730 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
731 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
733 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
734 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
736 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
737 assert!(tsa("localhost:23924").unwrap().contains(&a));
740 // FIXME: figure out why this fails on openbsd and bitrig and fix it
742 #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
743 fn to_socket_addr_str_bad() {
744 assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());
749 fn ip4(low: u8) -> Ipv4Addr { Ipv4Addr::new(77, 88, 21, low) }
750 fn ip6(low: u16) -> Ipv6Addr { Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, low) }
752 let mut v4 = SocketAddrV4::new(ip4(11), 80);
753 assert_eq!(v4.ip(), &ip4(11));
755 assert_eq!(v4.ip(), &ip4(12));
757 let mut addr = SocketAddr::V4(v4);
758 assert_eq!(addr.ip(), IpAddr::V4(ip4(12)));
759 addr.set_ip(IpAddr::V4(ip4(13)));
760 assert_eq!(addr.ip(), IpAddr::V4(ip4(13)));
761 addr.set_ip(IpAddr::V6(ip6(14)));
762 assert_eq!(addr.ip(), IpAddr::V6(ip6(14)));
764 let mut v6 = SocketAddrV6::new(ip6(1), 80, 0, 0);
765 assert_eq!(v6.ip(), &ip6(1));
767 assert_eq!(v6.ip(), &ip6(2));
769 let mut addr = SocketAddr::V6(v6);
770 assert_eq!(addr.ip(), IpAddr::V6(ip6(2)));
771 addr.set_ip(IpAddr::V6(ip6(3)));
772 assert_eq!(addr.ip(), IpAddr::V6(ip6(3)));
773 addr.set_ip(IpAddr::V4(ip4(4)));
774 assert_eq!(addr.ip(), IpAddr::V4(ip4(4)));
779 let mut v4 = SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80);
780 assert_eq!(v4.port(), 80);
782 assert_eq!(v4.port(), 443);
784 let mut addr = SocketAddr::V4(v4);
785 assert_eq!(addr.port(), 443);
787 assert_eq!(addr.port(), 8080);
789 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 0);
790 assert_eq!(v6.port(), 80);
792 assert_eq!(v6.port(), 443);
794 let mut addr = SocketAddr::V6(v6);
795 assert_eq!(addr.port(), 443);
797 assert_eq!(addr.port(), 8080);
802 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0);
803 assert_eq!(v6.flowinfo(), 10);
805 assert_eq!(v6.flowinfo(), 20);
810 let mut v6 = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 0, 10);
811 assert_eq!(v6.scope_id(), 10);
813 assert_eq!(v6.scope_id(), 20);
818 let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(77, 88, 21, 11), 80));
819 assert!(v4.is_ipv4());
820 assert!(!v4.is_ipv6());
825 let v6 = SocketAddr::V6(SocketAddrV6::new(
826 Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 80, 10, 0));
827 assert!(!v6.is_ipv4());
828 assert!(v6.is_ipv6());