1 // Copyright 2013-2014 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.
14 use ffi::{CStr, CString};
16 use io::{self, Error, ErrorKind};
17 use libc::{c_int, c_char, c_void, c_uint};
20 use net::{SocketAddr, Shutdown, IpAddr, Ipv4Addr, Ipv6Addr};
23 use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t};
24 use sys::net::netc as c;
25 use sys_common::{AsInner, FromInner, IntoInner};
28 #[cfg(any(target_os = "dragonfly", target_os = "freebsd",
29 target_os = "ios", target_os = "macos",
30 target_os = "openbsd"))]
31 use sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP;
32 #[cfg(not(any(target_os = "dragonfly", target_os = "freebsd",
33 target_os = "ios", target_os = "macos",
34 target_os = "openbsd")))]
35 use sys::net::netc::IPV6_ADD_MEMBERSHIP;
36 #[cfg(any(target_os = "dragonfly", target_os = "freebsd",
37 target_os = "ios", target_os = "macos",
38 target_os = "openbsd"))]
39 use sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP;
40 #[cfg(not(any(target_os = "dragonfly", target_os = "freebsd",
41 target_os = "ios", target_os = "macos",
42 target_os = "openbsd")))]
43 use sys::net::netc::IPV6_DROP_MEMBERSHIP;
45 ////////////////////////////////////////////////////////////////////////////////
46 // sockaddr and misc bindings
47 ////////////////////////////////////////////////////////////////////////////////
49 pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
50 payload: T) -> io::Result<()> {
52 let payload = &payload as *const T as *const c_void;
53 try!(cvt(c::setsockopt(*sock.as_inner(), opt, val, payload,
54 mem::size_of::<T>() as c::socklen_t)));
59 pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
60 val: c_int) -> io::Result<T> {
62 let mut slot: T = mem::zeroed();
63 let mut len = mem::size_of::<T>() as c::socklen_t;
64 try!(cvt(c::getsockopt(*sock.as_inner(), opt, val,
65 &mut slot as *mut _ as *mut _,
67 assert_eq!(len as usize, mem::size_of::<T>());
72 fn sockname<F>(f: F) -> io::Result<SocketAddr>
73 where F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int
76 let mut storage: c::sockaddr_storage = mem::zeroed();
77 let mut len = mem::size_of_val(&storage) as c::socklen_t;
78 try!(cvt(f(&mut storage as *mut _ as *mut _, &mut len)));
79 sockaddr_to_addr(&storage, len as usize)
83 fn sockaddr_to_addr(storage: &c::sockaddr_storage,
84 len: usize) -> io::Result<SocketAddr> {
85 match storage.ss_family as c_int {
87 assert!(len as usize >= mem::size_of::<c::sockaddr_in>());
88 Ok(SocketAddr::V4(FromInner::from_inner(unsafe {
89 *(storage as *const _ as *const c::sockaddr_in)
93 assert!(len as usize >= mem::size_of::<c::sockaddr_in6>());
94 Ok(SocketAddr::V6(FromInner::from_inner(unsafe {
95 *(storage as *const _ as *const c::sockaddr_in6)
99 Err(Error::new(ErrorKind::InvalidInput, "invalid argument"))
104 #[cfg(target_os = "android")]
105 fn to_ipv6mr_interface(value: u32) -> c_int {
109 #[cfg(not(target_os = "android"))]
110 fn to_ipv6mr_interface(value: u32) -> c_uint {
114 ////////////////////////////////////////////////////////////////////////////////
115 // get_host_addresses
116 ////////////////////////////////////////////////////////////////////////////////
118 pub struct LookupHost {
119 original: *mut c::addrinfo,
120 cur: *mut c::addrinfo,
123 impl Iterator for LookupHost {
124 type Item = io::Result<SocketAddr>;
125 fn next(&mut self) -> Option<io::Result<SocketAddr>> {
127 if self.cur.is_null() { return None }
128 let ret = sockaddr_to_addr(mem::transmute((*self.cur).ai_addr),
129 (*self.cur).ai_addrlen as usize);
130 self.cur = (*self.cur).ai_next as *mut c::addrinfo;
136 unsafe impl Sync for LookupHost {}
137 unsafe impl Send for LookupHost {}
139 impl Drop for LookupHost {
141 unsafe { c::freeaddrinfo(self.original) }
145 pub fn lookup_host(host: &str) -> io::Result<LookupHost> {
148 let c_host = try!(CString::new(host));
149 let mut res = ptr::null_mut();
151 try!(cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), ptr::null(),
153 Ok(LookupHost { original: res, cur: res })
157 ////////////////////////////////////////////////////////////////////////////////
159 ////////////////////////////////////////////////////////////////////////////////
162 pub fn lookup_addr(addr: &IpAddr) -> io::Result<String> {
165 let saddr = SocketAddr::new(*addr, 0);
166 let (inner, len) = saddr.into_inner();
167 let mut hostbuf = [0 as c_char; c::NI_MAXHOST as usize];
170 try!(cvt_gai(c::getnameinfo(inner, len,
171 hostbuf.as_mut_ptr(),
173 ptr::null_mut(), 0, 0)));
175 CStr::from_ptr(hostbuf.as_ptr())
178 match from_utf8(data.to_bytes()) {
179 Ok(name) => Ok(name.to_owned()),
180 Err(_) => Err(io::Error::new(io::ErrorKind::Other,
181 "failed to lookup address information"))
185 ////////////////////////////////////////////////////////////////////////////////
187 ////////////////////////////////////////////////////////////////////////////////
189 pub struct TcpStream {
194 pub fn connect(addr: &SocketAddr) -> io::Result<TcpStream> {
197 let sock = try!(Socket::new(addr, c::SOCK_STREAM));
199 let (addrp, len) = addr.into_inner();
200 try!(cvt_r(|| unsafe { c::connect(*sock.as_inner(), addrp, len) }));
201 Ok(TcpStream { inner: sock })
204 pub fn socket(&self) -> &Socket { &self.inner }
206 pub fn into_socket(self) -> Socket { self.inner }
208 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
209 self.inner.set_timeout(dur, c::SO_RCVTIMEO)
212 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
213 self.inner.set_timeout(dur, c::SO_SNDTIMEO)
216 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
217 self.inner.timeout(c::SO_RCVTIMEO)
220 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
221 self.inner.timeout(c::SO_SNDTIMEO)
224 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
228 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
229 let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
230 let ret = try!(cvt(unsafe {
231 c::send(*self.inner.as_inner(),
232 buf.as_ptr() as *const c_void,
239 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
240 sockname(|buf, len| unsafe {
241 c::getpeername(*self.inner.as_inner(), buf, len)
245 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
246 sockname(|buf, len| unsafe {
247 c::getsockname(*self.inner.as_inner(), buf, len)
251 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
252 self.inner.shutdown(how)
255 pub fn duplicate(&self) -> io::Result<TcpStream> {
256 self.inner.duplicate().map(|s| TcpStream { inner: s })
259 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
260 self.inner.set_nodelay(nodelay)
263 pub fn nodelay(&self) -> io::Result<bool> {
267 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
268 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
271 pub fn ttl(&self) -> io::Result<u32> {
272 let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL));
276 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
277 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int)
280 pub fn only_v6(&self) -> io::Result<bool> {
281 let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY));
285 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
286 let raw: c_int = try!(getsockopt(&self.inner, c::SOL_SOCKET, c::SO_ERROR));
290 Ok(Some(io::Error::from_raw_os_error(raw as i32)))
294 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
295 self.inner.set_nonblocking(nonblocking)
299 impl FromInner<Socket> for TcpStream {
300 fn from_inner(socket: Socket) -> TcpStream {
301 TcpStream { inner: socket }
305 impl fmt::Debug for TcpStream {
306 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
307 let mut res = f.debug_struct("TcpStream");
309 if let Ok(addr) = self.socket_addr() {
310 res.field("addr", &addr);
313 if let Ok(peer) = self.peer_addr() {
314 res.field("peer", &peer);
317 let name = if cfg!(windows) {"socket"} else {"fd"};
318 res.field(name, &self.inner.as_inner())
323 ////////////////////////////////////////////////////////////////////////////////
325 ////////////////////////////////////////////////////////////////////////////////
327 pub struct TcpListener {
332 pub fn bind(addr: &SocketAddr) -> io::Result<TcpListener> {
335 let sock = try!(Socket::new(addr, c::SOCK_STREAM));
337 // On platforms with Berkeley-derived sockets, this allows
338 // to quickly rebind a socket, without needing to wait for
339 // the OS to clean up the previous one.
341 try!(setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR,
345 // Bind our new socket
346 let (addrp, len) = addr.into_inner();
347 try!(cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) }));
350 try!(cvt(unsafe { c::listen(*sock.as_inner(), 128) }));
351 Ok(TcpListener { inner: sock })
354 pub fn socket(&self) -> &Socket { &self.inner }
356 pub fn into_socket(self) -> Socket { self.inner }
358 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
359 sockname(|buf, len| unsafe {
360 c::getsockname(*self.inner.as_inner(), buf, len)
364 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
365 let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
366 let mut len = mem::size_of_val(&storage) as c::socklen_t;
367 let sock = try!(self.inner.accept(&mut storage as *mut _ as *mut _,
369 let addr = try!(sockaddr_to_addr(&storage, len as usize));
370 Ok((TcpStream { inner: sock, }, addr))
373 pub fn duplicate(&self) -> io::Result<TcpListener> {
374 self.inner.duplicate().map(|s| TcpListener { inner: s })
377 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
378 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
381 pub fn ttl(&self) -> io::Result<u32> {
382 let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL));
386 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
387 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int)
390 pub fn only_v6(&self) -> io::Result<bool> {
391 let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY));
395 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
396 let raw: c_int = try!(getsockopt(&self.inner, c::SOL_SOCKET, c::SO_ERROR));
400 Ok(Some(io::Error::from_raw_os_error(raw as i32)))
404 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
405 self.inner.set_nonblocking(nonblocking)
409 impl FromInner<Socket> for TcpListener {
410 fn from_inner(socket: Socket) -> TcpListener {
411 TcpListener { inner: socket }
415 impl fmt::Debug for TcpListener {
416 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
417 let mut res = f.debug_struct("TcpListener");
419 if let Ok(addr) = self.socket_addr() {
420 res.field("addr", &addr);
423 let name = if cfg!(windows) {"socket"} else {"fd"};
424 res.field(name, &self.inner.as_inner())
429 ////////////////////////////////////////////////////////////////////////////////
431 ////////////////////////////////////////////////////////////////////////////////
433 pub struct UdpSocket {
438 pub fn bind(addr: &SocketAddr) -> io::Result<UdpSocket> {
441 let sock = try!(Socket::new(addr, c::SOCK_DGRAM));
442 let (addrp, len) = addr.into_inner();
443 try!(cvt(unsafe { c::bind(*sock.as_inner(), addrp, len) }));
444 Ok(UdpSocket { inner: sock })
447 pub fn socket(&self) -> &Socket { &self.inner }
449 pub fn into_socket(self) -> Socket { self.inner }
451 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
452 sockname(|buf, len| unsafe {
453 c::getsockname(*self.inner.as_inner(), buf, len)
457 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
458 let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
459 let mut addrlen = mem::size_of_val(&storage) as c::socklen_t;
460 let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
462 let n = try!(cvt(unsafe {
463 c::recvfrom(*self.inner.as_inner(),
464 buf.as_mut_ptr() as *mut c_void,
466 &mut storage as *mut _ as *mut _, &mut addrlen)
468 Ok((n as usize, try!(sockaddr_to_addr(&storage, addrlen as usize))))
471 pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result<usize> {
472 let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
473 let (dstp, dstlen) = dst.into_inner();
474 let ret = try!(cvt(unsafe {
475 c::sendto(*self.inner.as_inner(),
476 buf.as_ptr() as *const c_void, len,
482 pub fn duplicate(&self) -> io::Result<UdpSocket> {
483 self.inner.duplicate().map(|s| UdpSocket { inner: s })
486 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
487 self.inner.set_timeout(dur, c::SO_RCVTIMEO)
490 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
491 self.inner.set_timeout(dur, c::SO_SNDTIMEO)
494 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
495 self.inner.timeout(c::SO_RCVTIMEO)
498 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
499 self.inner.timeout(c::SO_SNDTIMEO)
502 pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
503 setsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST, broadcast as c_int)
506 pub fn broadcast(&self) -> io::Result<bool> {
507 let raw: c_int = try!(getsockopt(&self.inner, c::SOL_SOCKET, c::SO_BROADCAST));
511 pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
512 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP, multicast_loop_v4 as c_int)
515 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
516 let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_LOOP));
520 pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
521 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL, multicast_ttl_v4 as c_int)
524 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
525 let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_MULTICAST_TTL));
529 pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
530 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP, multicast_loop_v6 as c_int)
533 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
534 let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_MULTICAST_LOOP));
538 pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
540 let mreq = c::ip_mreq {
541 imr_multiaddr: *multiaddr.as_inner(),
542 imr_interface: *interface.as_inner(),
544 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq)
547 pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
549 let mreq = c::ipv6_mreq {
550 ipv6mr_multiaddr: *multiaddr.as_inner(),
551 ipv6mr_interface: to_ipv6mr_interface(interface),
553 setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq)
556 pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
558 let mreq = c::ip_mreq {
559 imr_multiaddr: *multiaddr.as_inner(),
560 imr_interface: *interface.as_inner(),
562 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq)
565 pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
567 let mreq = c::ipv6_mreq {
568 ipv6mr_multiaddr: *multiaddr.as_inner(),
569 ipv6mr_interface: to_ipv6mr_interface(interface),
571 setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq)
574 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
575 setsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL, ttl as c_int)
578 pub fn ttl(&self) -> io::Result<u32> {
579 let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IP, c::IP_TTL));
583 pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
584 setsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY, only_v6 as c_int)
587 pub fn only_v6(&self) -> io::Result<bool> {
588 let raw: c_int = try!(getsockopt(&self.inner, c::IPPROTO_IPV6, c::IPV6_V6ONLY));
592 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
593 let raw: c_int = try!(getsockopt(&self.inner, c::SOL_SOCKET, c::SO_ERROR));
597 Ok(Some(io::Error::from_raw_os_error(raw as i32)))
601 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
602 self.inner.set_nonblocking(nonblocking)
605 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
609 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
610 let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
611 let ret = try!(cvt(unsafe {
612 c::send(*self.inner.as_inner(),
613 buf.as_ptr() as *const c_void,
620 pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> {
621 let (addrp, len) = addr.into_inner();
622 cvt_r(|| unsafe { c::connect(*self.inner.as_inner(), addrp, len) }).map(|_| ())
626 impl FromInner<Socket> for UdpSocket {
627 fn from_inner(socket: Socket) -> UdpSocket {
628 UdpSocket { inner: socket }
632 impl fmt::Debug for UdpSocket {
633 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
634 let mut res = f.debug_struct("UdpSocket");
636 if let Ok(addr) = self.socket_addr() {
637 res.field("addr", &addr);
640 let name = if cfg!(windows) {"socket"} else {"fd"};
641 res.field(name, &self.inner.as_inner())