]> git.proxmox.com Git - rustc.git/blob - src/libstd/sys/unix/net.rs
Imported Upstream version 1.0.0-alpha.2
[rustc.git] / src / libstd / sys / unix / net.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 prelude::v1::*;
12
13 use ffi::CStr;
14 use io;
15 use libc::{self, c_int, size_t};
16 use str;
17 use sys::c;
18 use net::{SocketAddr, IpAddr};
19 use sys::fd::FileDesc;
20 use sys_common::AsInner;
21
22 pub use sys::{cvt, cvt_r};
23
24 pub type wrlen_t = size_t;
25
26 pub struct Socket(FileDesc);
27
28 pub fn init() {}
29
30 pub fn cvt_gai(err: c_int) -> io::Result<()> {
31 if err == 0 { return Ok(()) }
32
33 let detail = unsafe {
34 str::from_utf8(CStr::from_ptr(c::gai_strerror(err)).to_bytes()).unwrap()
35 .to_string()
36 };
37 Err(io::Error::new(io::ErrorKind::Other,
38 "failed to lookup address information", Some(detail)))
39 }
40
41 impl Socket {
42 pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
43 let fam = match addr.ip() {
44 IpAddr::V4(..) => libc::AF_INET,
45 IpAddr::V6(..) => libc::AF_INET6,
46 };
47 unsafe {
48 let fd = try!(cvt(libc::socket(fam, ty, 0)));
49 Ok(Socket(FileDesc::new(fd)))
50 }
51 }
52
53 pub fn accept(&self, storage: *mut libc::sockaddr,
54 len: *mut libc::socklen_t) -> io::Result<Socket> {
55 let fd = try!(cvt_r(|| unsafe {
56 libc::accept(self.0.raw(), storage, len)
57 }));
58 Ok(Socket(FileDesc::new(fd)))
59 }
60
61 pub fn duplicate(&self) -> io::Result<Socket> {
62 cvt(unsafe { libc::dup(self.0.raw()) }).map(|fd| {
63 Socket(FileDesc::new(fd))
64 })
65 }
66
67 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
68 self.0.read(buf)
69 }
70 }
71
72 impl AsInner<c_int> for Socket {
73 fn as_inner(&self) -> &c_int { self.0.as_inner() }
74 }