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.
16 use libc::{self, socklen_t, sa_family_t};
18 use net::{IpAddr, lookup_host, ntoh, hton};
20 use sys_common::{FromInner, AsInner, IntoInner};
23 /// Representation of a socket address for networking applications
25 /// A socket address consists of at least an (ip, port) pair and may also
26 /// contain other information depending on the protocol.
27 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
28 pub struct SocketAddr {
34 V4(libc::sockaddr_in),
35 V6(libc::sockaddr_in6),
39 /// Creates a new socket address from the (ip, port) pair.
40 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
42 IpAddr::V4(ref ip) => {
43 Repr::V4(libc::sockaddr_in {
44 sin_family: libc::AF_INET as sa_family_t,
46 sin_addr: *ip.as_inner(),
47 .. unsafe { mem::zeroed() }
50 IpAddr::V6(ref ip) => {
51 Repr::V6(libc::sockaddr_in6 {
52 sin6_family: libc::AF_INET6 as sa_family_t,
53 sin6_port: hton(port),
54 sin6_addr: *ip.as_inner(),
55 .. unsafe { mem::zeroed() }
59 SocketAddr { repr: repr }
62 /// Gets the IP address associated with this socket address.
63 pub fn ip(&self) -> IpAddr {
65 Repr::V4(ref sa) => IpAddr::V4(FromInner::from_inner(sa.sin_addr)),
66 Repr::V6(ref sa) => IpAddr::V6(FromInner::from_inner(sa.sin6_addr)),
70 /// Gets the port number associated with this socket address
71 pub fn port(&self) -> u16 {
73 Repr::V4(ref sa) => ntoh(sa.sin_port),
74 Repr::V6(ref sa) => ntoh(sa.sin6_port),
78 fn set_port(&mut self, port: u16) {
80 Repr::V4(ref mut sa) => sa.sin_port = hton(port),
81 Repr::V6(ref mut sa) => sa.sin6_port = hton(port),
86 #[stable(feature = "rust1", since = "1.0.0")]
87 impl fmt::Display for SocketAddr {
88 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90 Repr::V4(_) => write!(f, "{}:{}", self.ip(), self.port()),
91 Repr::V6(_) => write!(f, "[{}]:{}", self.ip(), self.port()),
96 impl FromInner<libc::sockaddr_in> for SocketAddr {
97 fn from_inner(addr: libc::sockaddr_in) -> SocketAddr {
98 SocketAddr { repr: Repr::V4(addr) }
102 impl FromInner<libc::sockaddr_in6> for SocketAddr {
103 fn from_inner(addr: libc::sockaddr_in6) -> SocketAddr {
104 SocketAddr { repr: Repr::V6(addr) }
108 impl<'a> IntoInner<(*const libc::sockaddr, socklen_t)> for &'a SocketAddr {
109 fn into_inner(self) -> (*const libc::sockaddr, socklen_t) {
112 (a as *const _ as *const _, mem::size_of_val(a) as socklen_t)
115 (a as *const _ as *const _, mem::size_of_val(a) as socklen_t)
121 impl fmt::Debug for SocketAddr {
122 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
123 fmt::Display::fmt(self, fmt)
127 impl Clone for Repr {
128 fn clone(&self) -> Repr { *self }
131 impl PartialEq for Repr {
132 fn eq(&self, other: &Repr) -> bool {
133 match (*self, *other) {
134 (Repr::V4(ref a), Repr::V4(ref b)) => {
135 a.sin_port == b.sin_port &&
136 a.sin_addr.s_addr == b.sin_addr.s_addr
138 (Repr::V6(ref a), Repr::V6(ref b)) => {
139 a.sin6_port == b.sin6_port &&
140 a.sin6_addr.s6_addr == b.sin6_addr.s6_addr &&
141 a.sin6_flowinfo == b.sin6_flowinfo &&
142 a.sin6_scope_id == b.sin6_scope_id
150 impl<S: hash::Hasher + hash::Writer> hash::Hash<S> for Repr {
151 fn hash(&self, s: &mut S) {
154 (a.sin_family, a.sin_port, a.sin_addr.s_addr).hash(s)
157 (a.sin6_family, a.sin6_port, &a.sin6_addr.s6_addr,
158 a.sin6_flowinfo, a.sin6_scope_id).hash(s)
164 /// A trait for objects which can be converted or resolved to one or more
165 /// `SocketAddr` values.
167 /// This trait is used for generic address resolution when constructing network
168 /// objects. By default it is implemented for the following types:
170 /// * `SocketAddr` - `to_socket_addrs` is identity function.
172 /// * `(IpAddr, u16)` - `to_socket_addrs` constructs `SocketAddr` trivially.
174 /// * `(&str, u16)` - the string should be either a string representation of an
175 /// IP address expected by `FromStr` implementation for `IpAddr` or a host
178 /// * `&str` - the string should be either a string representation of a
179 /// `SocketAddr` as expected by its `FromStr` implementation or a string like
180 /// `<host_name>:<port>` pair where `<port>` is a `u16` value.
182 /// This trait allows constructing network objects like `TcpStream` or
183 /// `UdpSocket` easily with values of various types for the bind/connection
184 /// address. It is needed because sometimes one type is more appropriate than
185 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
186 /// than manual construction of the corresponding `SocketAddr`, but sometimes
187 /// `SocketAddr` value is *the* main source of the address, and converting it to
188 /// some other type (e.g. a string) just for it to be converted back to
189 /// `SocketAddr` in constructor methods is pointless.
194 /// use std::net::{IpAddr, SocketAddr, TcpStream, UdpSocket, TcpListener};
197 /// let ip = IpAddr::new_v4(127, 0, 0, 1);
198 /// let port = 12345;
200 /// // The following lines are equivalent modulo possible "localhost" name
201 /// // resolution differences
202 /// let tcp_s = TcpStream::connect(&SocketAddr::new(ip, port));
203 /// let tcp_s = TcpStream::connect(&(ip, port));
204 /// let tcp_s = TcpStream::connect(&("127.0.0.1", port));
205 /// let tcp_s = TcpStream::connect(&("localhost", port));
206 /// let tcp_s = TcpStream::connect("127.0.0.1:12345");
207 /// let tcp_s = TcpStream::connect("localhost:12345");
209 /// // TcpListener::bind(), UdpSocket::bind() and UdpSocket::send_to()
210 /// // behave similarly
211 /// let tcp_l = TcpListener::bind("localhost:12345");
213 /// let mut udp_s = UdpSocket::bind(&("127.0.0.1", port)).unwrap();
214 /// udp_s.send_to(&[7], &(ip, 23451));
217 pub trait ToSocketAddrs {
218 /// Returned iterator over socket addresses which this type may correspond
220 type Iter: Iterator<Item=SocketAddr>;
222 /// Converts this object to an iterator of resolved `SocketAddr`s.
224 /// The returned iterator may not actually yield any values depending on the
225 /// outcome of any resolution performed.
227 /// Note that this function may block the current thread while resolution is
232 /// Any errors encountered during resolution will be returned as an `Err`.
233 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
236 impl ToSocketAddrs for SocketAddr {
237 type Iter = option::IntoIter<SocketAddr>;
238 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
239 Ok(Some(*self).into_iter())
243 impl ToSocketAddrs for (IpAddr, u16) {
244 type Iter = option::IntoIter<SocketAddr>;
245 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
246 let (ip, port) = *self;
247 Ok(Some(SocketAddr::new(ip, port)).into_iter())
251 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
252 let ips = try!(lookup_host(s));
253 let v: Vec<_> = try!(ips.map(|a| {
254 a.map(|mut a| { a.set_port(p); a })
259 impl<'a> ToSocketAddrs for (&'a str, u16) {
260 type Iter = vec::IntoIter<SocketAddr>;
261 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
262 let (host, port) = *self;
264 // try to parse the host as a regular IpAddr first
265 match host.parse().ok() {
266 Some(addr) => return Ok(vec![SocketAddr::new(addr, port)].into_iter()),
270 resolve_socket_addr(host, port)
274 // accepts strings like 'localhost:12345'
275 impl ToSocketAddrs for str {
276 type Iter = vec::IntoIter<SocketAddr>;
277 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
278 // try to parse as a regular SocketAddr first
279 match self.parse().ok() {
280 Some(addr) => return Ok(vec![addr].into_iter()),
284 macro_rules! try_opt {
285 ($e:expr, $msg:expr) => (
288 None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
294 // split the string by ':' and convert the second part to u16
295 let mut parts_iter = self.rsplitn(2, ':');
296 let port_str = try_opt!(parts_iter.next(), "invalid socket address");
297 let host = try_opt!(parts_iter.next(), "invalid socket address");
298 let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
299 resolve_socket_addr(host, port)
303 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
305 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
306 (**self).to_socket_addrs()
315 use net::Ipv6MulticastScope::*;
318 fn test_from_str_ipv4() {
319 assert_eq!(Ok(Ipv4Addr::new(127, 0, 0, 1)), "127.0.0.1".parse());
320 assert_eq!(Ok(Ipv4Addr::new(255, 255, 255, 255)), "255.255.255.255".parse());
321 assert_eq!(Ok(Ipv4Addr::new(0, 0, 0, 0)), "0.0.0.0".parse());
324 let none: Option<IpAddr> = "256.0.0.1".parse().ok();
325 assert_eq!(None, none);
327 let none: Option<IpAddr> = "255.0.0".parse().ok();
328 assert_eq!(None, none);
330 let none: Option<IpAddr> = "255.0.0.1.2".parse().ok();
331 assert_eq!(None, none);
332 // no number between dots
333 let none: Option<IpAddr> = "255.0..1".parse().ok();
334 assert_eq!(None, none);
338 fn test_from_str_ipv6() {
339 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "0:0:0:0:0:0:0:0".parse());
340 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "0:0:0:0:0:0:0:1".parse());
342 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)), "::1".parse());
343 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), "::".parse());
345 assert_eq!(Ok(Ipv6Addr::new(0x2a02, 0x6b8, 0, 0, 0, 0, 0x11, 0x11)),
346 "2a02:6b8::11:11".parse());
349 let none: Option<IpAddr> = "::00000".parse().ok();
350 assert_eq!(None, none);
352 let none: Option<IpAddr> = "1:2:3:4:5:6:7".parse().ok();
353 assert_eq!(None, none);
355 let none: Option<IpAddr> = "1:2:3:4:5:6:7:8:9".parse().ok();
356 assert_eq!(None, none);
358 let none: Option<IpAddr> = "1:2:::6:7:8".parse().ok();
359 assert_eq!(None, none);
361 let none: Option<IpAddr> = "1:2::6::8".parse().ok();
362 assert_eq!(None, none);
366 fn test_from_str_ipv4_in_ipv6() {
367 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 49152, 545)),
368 "::192.0.2.33".parse());
369 assert_eq!(Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0xFFFF, 49152, 545)),
370 "::FFFF:192.0.2.33".parse());
371 assert_eq!(Ok(Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 49152, 545)),
372 "64:ff9b::192.0.2.33".parse());
373 assert_eq!(Ok(Ipv6Addr::new(0x2001, 0xdb8, 0x122, 0xc000, 0x2, 0x2100, 49152, 545)),
374 "2001:db8:122:c000:2:2100:192.0.2.33".parse());
377 let none: Option<IpAddr> = "::127.0.0.1:".parse().ok();
378 assert_eq!(None, none);
380 let none: Option<IpAddr> = "1.2.3.4.5:127.0.0.1".parse().ok();
381 assert_eq!(None, none);
383 let none: Option<IpAddr> = "1.2.3.4.5:6:7:127.0.0.1".parse().ok();
384 assert_eq!(None, none);
388 fn test_from_str_socket_addr() {
389 assert_eq!(Ok(SocketAddr::new(IpAddr::new_v4(77, 88, 21, 11), 80)),
390 "77.88.21.11:80".parse());
391 assert_eq!(Ok(SocketAddr::new(IpAddr::new_v6(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53)),
392 "[2a02:6b8:0:1::1]:53".parse());
393 assert_eq!(Ok(SocketAddr::new(IpAddr::new_v6(0, 0, 0, 0, 0, 0, 0x7F00, 1), 22)),
394 "[::127.0.0.1]:22".parse());
397 let none: Option<SocketAddr> = "127.0.0.1".parse().ok();
398 assert_eq!(None, none);
400 let none: Option<SocketAddr> = "127.0.0.1:".parse().ok();
401 assert_eq!(None, none);
402 // wrong brackets around v4
403 let none: Option<SocketAddr> = "[127.0.0.1]:22".parse().ok();
404 assert_eq!(None, none);
406 let none: Option<SocketAddr> = "127.0.0.1:123456".parse().ok();
407 assert_eq!(None, none);
411 fn ipv6_addr_to_string() {
412 // ipv4-mapped address
413 let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc000, 0x280);
414 assert_eq!(a1.to_string(), "::ffff:192.0.2.128");
416 // ipv4-compatible address
417 let a1 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0xc000, 0x280);
418 assert_eq!(a1.to_string(), "::192.0.2.128");
420 // v6 address with no zero segments
421 assert_eq!(Ipv6Addr::new(8, 9, 10, 11, 12, 13, 14, 15).to_string(),
424 // reduce a single run of zeros
425 assert_eq!("ae::ffff:102:304",
426 Ipv6Addr::new(0xae, 0, 0, 0, 0, 0xffff, 0x0102, 0x0304).to_string());
428 // don't reduce just a single zero segment
429 assert_eq!("1:2:3:4:5:6:0:8",
430 Ipv6Addr::new(1, 2, 3, 4, 5, 6, 0, 8).to_string());
433 assert_eq!("::", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0).to_string());
436 assert_eq!("::1", Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).to_string());
439 assert_eq!("1::", Ipv6Addr::new(1, 0, 0, 0, 0, 0, 0, 0).to_string());
441 // two runs of zeros, second one is longer
442 assert_eq!("1:0:0:4::8", Ipv6Addr::new(1, 0, 0, 4, 0, 0, 0, 8).to_string());
444 // two runs of zeros, equal length
445 assert_eq!("1::4:5:0:0:8", Ipv6Addr::new(1, 0, 0, 4, 5, 0, 0, 8).to_string());
450 assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678),
451 Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_mapped());
452 assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678),
453 Ipv4Addr::new(0x12, 0x34, 0x56, 0x78).to_ipv6_compatible());
458 assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0x1234, 0x5678).to_ipv4(),
459 Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
460 assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
461 Some(Ipv4Addr::new(0x12, 0x34, 0x56, 0x78)));
462 assert_eq!(Ipv6Addr::new(0, 0, 1, 0, 0, 0, 0x1234, 0x5678).to_ipv4(),
467 fn ipv4_properties() {
468 fn check(octets: &[u8; 4], unspec: bool, loopback: bool,
469 private: bool, link_local: bool, global: bool,
471 let ip = Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]);
472 assert_eq!(octets, &ip.octets());
474 assert_eq!(ip.is_unspecified(), unspec);
475 assert_eq!(ip.is_loopback(), loopback);
476 assert_eq!(ip.is_private(), private);
477 assert_eq!(ip.is_link_local(), link_local);
478 assert_eq!(ip.is_global(), global);
479 assert_eq!(ip.is_multicast(), multicast);
482 // address unspec loopbk privt linloc global multicast
483 check(&[0, 0, 0, 0], true, false, false, false, true, false);
484 check(&[0, 0, 0, 1], false, false, false, false, true, false);
485 check(&[1, 0, 0, 0], false, false, false, false, true, false);
486 check(&[10, 9, 8, 7], false, false, true, false, false, false);
487 check(&[127, 1, 2, 3], false, true, false, false, false, false);
488 check(&[172, 31, 254, 253], false, false, true, false, false, false);
489 check(&[169, 254, 253, 242], false, false, false, true, false, false);
490 check(&[192, 168, 254, 253], false, false, true, false, false, false);
491 check(&[224, 0, 0, 0], false, false, false, false, true, true);
492 check(&[239, 255, 255, 255], false, false, false, false, true, true);
493 check(&[255, 255, 255, 255], false, false, false, false, true, false);
497 fn ipv6_properties() {
498 fn check(str_addr: &str, unspec: bool, loopback: bool,
499 unique_local: bool, global: bool,
500 u_link_local: bool, u_site_local: bool, u_global: bool,
501 m_scope: Option<Ipv6MulticastScope>) {
502 let ip: Ipv6Addr = str_addr.parse().ok().unwrap();
503 assert_eq!(str_addr, ip.to_string());
505 assert_eq!(ip.is_unspecified(), unspec);
506 assert_eq!(ip.is_loopback(), loopback);
507 assert_eq!(ip.is_unique_local(), unique_local);
508 assert_eq!(ip.is_global(), global);
509 assert_eq!(ip.is_unicast_link_local(), u_link_local);
510 assert_eq!(ip.is_unicast_site_local(), u_site_local);
511 assert_eq!(ip.is_unicast_global(), u_global);
512 assert_eq!(ip.multicast_scope(), m_scope);
513 assert_eq!(ip.is_multicast(), m_scope.is_some());
516 // unspec loopbk uniqlo global unill unisl uniglo mscope
518 true, false, false, true, false, false, true, None);
520 false, true, false, false, false, false, false, None);
522 false, false, false, true, false, false, true, None);
524 false, false, false, true, false, false, true, None);
526 false, false, true, false, false, false, false, None);
528 false, false, true, false, false, false, false, None);
530 false, false, false, false, true, false, false, None);
532 false, false, false, false, true, false, false, None);
534 false, false, false, false, false, true, false, None);
536 false, false, false, false, false, false, false, Some(InterfaceLocal));
538 false, false, false, false, false, false, false, Some(LinkLocal));
540 false, false, false, false, false, false, false, Some(RealmLocal));
542 false, false, false, false, false, false, false, Some(AdminLocal));
544 false, false, false, false, false, false, false, Some(SiteLocal));
546 false, false, false, false, false, false, false, Some(OrganizationLocal));
548 false, false, false, true, false, false, false, Some(Global));
551 fn tsa<A: ToSocketAddrs>(a: A) -> io::Result<Vec<SocketAddr>> {
552 Ok(try!(a.to_socket_addrs()).collect())
556 fn to_socket_addr_socketaddr() {
557 let a = SocketAddr::new(IpAddr::new_v4(77, 88, 21, 11), 12345);
558 assert_eq!(Ok(vec![a]), tsa(a));
562 fn to_socket_addr_ipaddr_u16() {
563 let a = IpAddr::new_v4(77, 88, 21, 11);
565 let e = SocketAddr::new(a, p);
566 assert_eq!(Ok(vec![e]), tsa((a, p)));
570 fn to_socket_addr_str_u16() {
571 let a = SocketAddr::new(IpAddr::new_v4(77, 88, 21, 11), 24352);
572 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352u16)));
574 let a = SocketAddr::new(IpAddr::new_v6(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
575 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
577 let a = SocketAddr::new(IpAddr::new_v4(127, 0, 0, 1), 23924);
578 assert!(tsa(("localhost", 23924u16)).unwrap().contains(&a));
582 fn to_socket_addr_str() {
583 let a = SocketAddr::new(IpAddr::new_v4(77, 88, 21, 11), 24352);
584 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
586 let a = SocketAddr::new(IpAddr::new_v6(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
587 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
589 let a = SocketAddr::new(IpAddr::new_v4(127, 0, 0, 1), 23924);
590 assert!(tsa("localhost:23924").unwrap().contains(&a));