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.
17 use net::{lookup_host, ntoh, hton, Ipv4Addr, Ipv6Addr};
21 use sys::net::netc as c;
22 use sys_common::{FromInner, AsInner, IntoInner};
27 /// Representation of a socket address for networking applications.
29 /// A socket address can either represent the IPv4 or IPv6 protocol and is
30 /// paired with at least a port number as well. Each protocol may have more
31 /// specific information about the address available to it as well.
32 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
33 #[stable(feature = "rust1", since = "1.0.0")]
35 /// An IPv4 socket address which is a (ip, port) combination.
36 #[stable(feature = "rust1", since = "1.0.0")]
37 V4(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] SocketAddrV4),
38 /// An IPv6 socket address
39 #[stable(feature = "rust1", since = "1.0.0")]
40 V6(#[cfg_attr(not(stage0), stable(feature = "rust1", since = "1.0.0"))] SocketAddrV6),
43 /// An IPv4 socket address which is a (ip, port) combination.
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct SocketAddrV4 { inner: c::sockaddr_in }
48 /// An IPv6 socket address.
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub struct SocketAddrV6 { inner: c::sockaddr_in6 }
54 /// Creates a new socket address from the (ip, port) pair.
55 #[unstable(feature = "ip_addr", reason = "recent addition", issue = "27801")]
56 #[rustc_deprecated(reason = "ip type too small a type to pull its weight",
59 pub fn new(ip: IpAddr, port: u16) -> SocketAddr {
61 IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)),
62 IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)),
66 /// Returns the IP address associated with this socket address.
67 #[unstable(feature = "ip_addr", reason = "recent addition", issue = "27801")]
68 #[rustc_deprecated(reason = "too small a type to pull its weight",
71 pub fn ip(&self) -> IpAddr {
73 SocketAddr::V4(ref a) => IpAddr::V4(*a.ip()),
74 SocketAddr::V6(ref a) => IpAddr::V6(*a.ip()),
78 /// Returns the port number associated with this socket address.
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub fn port(&self) -> u16 {
82 SocketAddr::V4(ref a) => a.port(),
83 SocketAddr::V6(ref a) => a.port(),
89 /// Creates a new socket address from the (ip, port) pair.
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 {
93 inner: c::sockaddr_in {
94 sin_family: c::AF_INET as c::sa_family_t,
96 sin_addr: *ip.as_inner(),
97 .. unsafe { mem::zeroed() }
102 /// Returns the IP address associated with this socket address.
103 #[stable(feature = "rust1", since = "1.0.0")]
104 pub fn ip(&self) -> &Ipv4Addr {
106 &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr)
110 /// Returns the port number associated with this socket address.
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub fn port(&self) -> u16 { ntoh(self.inner.sin_port) }
116 /// Creates a new socket address from the ip/port/flowinfo/scope_id
118 #[stable(feature = "rust1", since = "1.0.0")]
119 pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32)
122 inner: c::sockaddr_in6 {
123 sin6_family: c::AF_INET6 as c::sa_family_t,
124 sin6_port: hton(port),
125 sin6_addr: *ip.as_inner(),
126 sin6_flowinfo: hton(flowinfo),
127 sin6_scope_id: hton(scope_id),
128 .. unsafe { mem::zeroed() }
133 /// Returns the IP address associated with this socket address.
134 #[stable(feature = "rust1", since = "1.0.0")]
135 pub fn ip(&self) -> &Ipv6Addr {
137 &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr)
141 /// Returns the port number associated with this socket address.
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub fn port(&self) -> u16 { ntoh(self.inner.sin6_port) }
145 /// Returns the flow information associated with this address,
146 /// corresponding to the `sin6_flowinfo` field in C.
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub fn flowinfo(&self) -> u32 { ntoh(self.inner.sin6_flowinfo) }
150 /// Returns the scope ID associated with this address,
151 /// corresponding to the `sin6_scope_id` field in C.
152 #[stable(feature = "rust1", since = "1.0.0")]
153 pub fn scope_id(&self) -> u32 { ntoh(self.inner.sin6_scope_id) }
156 impl FromInner<c::sockaddr_in> for SocketAddrV4 {
157 fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 {
158 SocketAddrV4 { inner: addr }
162 impl FromInner<c::sockaddr_in6> for SocketAddrV6 {
163 fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 {
164 SocketAddrV6 { inner: addr }
168 impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr {
169 fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) {
171 SocketAddr::V4(ref a) => {
172 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
174 SocketAddr::V6(ref a) => {
175 (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t)
181 #[stable(feature = "rust1", since = "1.0.0")]
182 impl fmt::Display for SocketAddr {
183 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
185 SocketAddr::V4(ref a) => a.fmt(f),
186 SocketAddr::V6(ref a) => a.fmt(f),
191 #[stable(feature = "rust1", since = "1.0.0")]
192 impl fmt::Display for SocketAddrV4 {
193 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
194 write!(f, "{}:{}", self.ip(), self.port())
198 #[stable(feature = "rust1", since = "1.0.0")]
199 impl fmt::Debug for SocketAddrV4 {
200 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
201 fmt::Display::fmt(self, fmt)
205 #[stable(feature = "rust1", since = "1.0.0")]
206 impl fmt::Display for SocketAddrV6 {
207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208 write!(f, "[{}]:{}", self.ip(), self.port())
212 #[stable(feature = "rust1", since = "1.0.0")]
213 impl fmt::Debug for SocketAddrV6 {
214 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
215 fmt::Display::fmt(self, fmt)
219 #[stable(feature = "rust1", since = "1.0.0")]
220 impl Clone for SocketAddrV4 {
221 fn clone(&self) -> SocketAddrV4 { *self }
223 #[stable(feature = "rust1", since = "1.0.0")]
224 impl Clone for SocketAddrV6 {
225 fn clone(&self) -> SocketAddrV6 { *self }
228 #[stable(feature = "rust1", since = "1.0.0")]
229 impl PartialEq for SocketAddrV4 {
230 fn eq(&self, other: &SocketAddrV4) -> bool {
231 self.inner.sin_port == other.inner.sin_port &&
232 self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl PartialEq for SocketAddrV6 {
237 fn eq(&self, other: &SocketAddrV6) -> bool {
238 self.inner.sin6_port == other.inner.sin6_port &&
239 self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr &&
240 self.inner.sin6_flowinfo == other.inner.sin6_flowinfo &&
241 self.inner.sin6_scope_id == other.inner.sin6_scope_id
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl Eq for SocketAddrV4 {}
246 #[stable(feature = "rust1", since = "1.0.0")]
247 impl Eq for SocketAddrV6 {}
249 #[stable(feature = "rust1", since = "1.0.0")]
250 impl hash::Hash for SocketAddrV4 {
251 fn hash<H: hash::Hasher>(&self, s: &mut H) {
252 (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s)
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl hash::Hash for SocketAddrV6 {
257 fn hash<H: hash::Hasher>(&self, s: &mut H) {
258 (self.inner.sin6_port, &self.inner.sin6_addr.s6_addr,
259 self.inner.sin6_flowinfo, self.inner.sin6_scope_id).hash(s)
263 /// A trait for objects which can be converted or resolved to one or more
264 /// `SocketAddr` values.
266 /// This trait is used for generic address resolution when constructing network
267 /// objects. By default it is implemented for the following types:
269 /// * `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` - `to_socket_addrs` is
270 /// identity function.
272 /// * `(IpvNAddr, u16)` - `to_socket_addrs` constructs `SocketAddr` trivially.
274 /// * `(&str, u16)` - the string should be either a string representation of an
275 /// IP address expected by `FromStr` implementation for `IpvNAddr` or a host
278 /// * `&str` - the string should be either a string representation of a
279 /// `SocketAddr` as expected by its `FromStr` implementation or a string like
280 /// `<host_name>:<port>` pair where `<port>` is a `u16` value.
282 /// This trait allows constructing network objects like `TcpStream` or
283 /// `UdpSocket` easily with values of various types for the bind/connection
284 /// address. It is needed because sometimes one type is more appropriate than
285 /// the other: for simple uses a string like `"localhost:12345"` is much nicer
286 /// than manual construction of the corresponding `SocketAddr`, but sometimes
287 /// `SocketAddr` value is *the* main source of the address, and converting it to
288 /// some other type (e.g. a string) just for it to be converted back to
289 /// `SocketAddr` in constructor methods is pointless.
294 /// use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
297 /// let ip = Ipv4Addr::new(127, 0, 0, 1);
298 /// let port = 12345;
300 /// // The following lines are equivalent modulo possible "localhost" name
301 /// // resolution differences
302 /// let tcp_s = TcpStream::connect(SocketAddrV4::new(ip, port));
303 /// let tcp_s = TcpStream::connect((ip, port));
304 /// let tcp_s = TcpStream::connect(("127.0.0.1", port));
305 /// let tcp_s = TcpStream::connect(("localhost", port));
306 /// let tcp_s = TcpStream::connect("127.0.0.1:12345");
307 /// let tcp_s = TcpStream::connect("localhost:12345");
309 /// // TcpListener::bind(), UdpSocket::bind() and UdpSocket::send_to()
310 /// // behave similarly
311 /// let tcp_l = TcpListener::bind("localhost:12345");
313 /// let mut udp_s = UdpSocket::bind(("127.0.0.1", port)).unwrap();
314 /// udp_s.send_to(&[7], (ip, 23451)).unwrap();
317 #[stable(feature = "rust1", since = "1.0.0")]
318 pub trait ToSocketAddrs {
319 /// Returned iterator over socket addresses which this type may correspond
321 #[stable(feature = "rust1", since = "1.0.0")]
322 type Iter: Iterator<Item=SocketAddr>;
324 /// Converts this object to an iterator of resolved `SocketAddr`s.
326 /// The returned iterator may not actually yield any values depending on the
327 /// outcome of any resolution performed.
329 /// Note that this function may block the current thread while resolution is
334 /// Any errors encountered during resolution will be returned as an `Err`.
335 #[stable(feature = "rust1", since = "1.0.0")]
336 fn to_socket_addrs(&self) -> io::Result<Self::Iter>;
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl ToSocketAddrs for SocketAddr {
341 type Iter = option::IntoIter<SocketAddr>;
342 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
343 Ok(Some(*self).into_iter())
347 #[stable(feature = "rust1", since = "1.0.0")]
348 impl ToSocketAddrs for SocketAddrV4 {
349 type Iter = option::IntoIter<SocketAddr>;
350 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
351 SocketAddr::V4(*self).to_socket_addrs()
355 #[stable(feature = "rust1", since = "1.0.0")]
356 impl ToSocketAddrs for SocketAddrV6 {
357 type Iter = option::IntoIter<SocketAddr>;
358 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
359 SocketAddr::V6(*self).to_socket_addrs()
363 #[stable(feature = "rust1", since = "1.0.0")]
365 impl ToSocketAddrs for (IpAddr, u16) {
366 type Iter = option::IntoIter<SocketAddr>;
367 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
368 let (ip, port) = *self;
370 IpAddr::V4(ref a) => (*a, port).to_socket_addrs(),
371 IpAddr::V6(ref a) => (*a, port).to_socket_addrs(),
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl ToSocketAddrs for (Ipv4Addr, u16) {
378 type Iter = option::IntoIter<SocketAddr>;
379 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
380 let (ip, port) = *self;
381 SocketAddrV4::new(ip, port).to_socket_addrs()
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl ToSocketAddrs for (Ipv6Addr, u16) {
387 type Iter = option::IntoIter<SocketAddr>;
388 fn to_socket_addrs(&self) -> io::Result<option::IntoIter<SocketAddr>> {
389 let (ip, port) = *self;
390 SocketAddrV6::new(ip, port, 0, 0).to_socket_addrs()
394 fn resolve_socket_addr(s: &str, p: u16) -> io::Result<vec::IntoIter<SocketAddr>> {
395 let ips = try!(lookup_host(s));
396 let v: Vec<_> = try!(ips.map(|a| {
399 SocketAddr::V4(ref a) => {
400 SocketAddr::V4(SocketAddrV4::new(*a.ip(), p))
402 SocketAddr::V6(ref a) => {
403 SocketAddr::V6(SocketAddrV6::new(*a.ip(), p, a.flowinfo(),
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl<'a> ToSocketAddrs for (&'a str, u16) {
414 type Iter = vec::IntoIter<SocketAddr>;
415 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
416 let (host, port) = *self;
418 // try to parse the host as a regular IP address first
419 if let Ok(addr) = host.parse::<Ipv4Addr>() {
420 let addr = SocketAddrV4::new(addr, port);
421 return Ok(vec![SocketAddr::V4(addr)].into_iter())
423 if let Ok(addr) = host.parse::<Ipv6Addr>() {
424 let addr = SocketAddrV6::new(addr, port, 0, 0);
425 return Ok(vec![SocketAddr::V6(addr)].into_iter())
428 resolve_socket_addr(host, port)
432 // accepts strings like 'localhost:12345'
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl ToSocketAddrs for str {
435 type Iter = vec::IntoIter<SocketAddr>;
436 fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
437 // try to parse as a regular SocketAddr first
438 match self.parse().ok() {
439 Some(addr) => return Ok(vec![addr].into_iter()),
443 macro_rules! try_opt {
444 ($e:expr, $msg:expr) => (
447 None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
453 // split the string by ':' and convert the second part to u16
454 let mut parts_iter = self.rsplitn(2, ':');
455 let port_str = try_opt!(parts_iter.next(), "invalid socket address");
456 let host = try_opt!(parts_iter.next(), "invalid socket address");
457 let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value");
458 resolve_socket_addr(host, port)
462 #[stable(feature = "slice_to_socket_addrs", since = "1.8.0")]
463 impl<'a> ToSocketAddrs for &'a [SocketAddr] {
464 type Iter = iter::Cloned<slice::Iter<'a, SocketAddr>>;
466 fn to_socket_addrs(&self) -> io::Result<Self::Iter> {
467 Ok(self.iter().cloned())
471 #[stable(feature = "rust1", since = "1.0.0")]
472 impl<'a, T: ToSocketAddrs + ?Sized> ToSocketAddrs for &'a T {
474 fn to_socket_addrs(&self) -> io::Result<T::Iter> {
475 (**self).to_socket_addrs()
483 use net::test::{tsa, sa6, sa4};
486 fn to_socket_addr_ipaddr_u16() {
487 let a = Ipv4Addr::new(77, 88, 21, 11);
489 let e = SocketAddr::V4(SocketAddrV4::new(a, p));
490 assert_eq!(Ok(vec![e]), tsa((a, p)));
494 fn to_socket_addr_str_u16() {
495 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
496 assert_eq!(Ok(vec![a]), tsa(("77.88.21.11", 24352)));
498 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
499 assert_eq!(Ok(vec![a]), tsa(("2a02:6b8:0:1::1", 53)));
501 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
502 assert!(tsa(("localhost", 23924)).unwrap().contains(&a));
506 fn to_socket_addr_str() {
507 let a = sa4(Ipv4Addr::new(77, 88, 21, 11), 24352);
508 assert_eq!(Ok(vec![a]), tsa("77.88.21.11:24352"));
510 let a = sa6(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53);
511 assert_eq!(Ok(vec![a]), tsa("[2a02:6b8:0:1::1]:53"));
513 let a = sa4(Ipv4Addr::new(127, 0, 0, 1), 23924);
514 assert!(tsa("localhost:23924").unwrap().contains(&a));
517 // FIXME: figure out why this fails on openbsd and bitrig and fix it
519 #[cfg(not(any(windows, target_os = "openbsd", target_os = "bitrig")))]
520 fn to_socket_addr_str_bad() {
521 assert!(tsa("1200::AB00:1234::2552:7777:1313:34300").is_err());