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 libc
::{self, c_int, size_t}
;
18 use net
::{SocketAddr, IpAddr}
;
19 use sys
::fd
::FileDesc
;
20 use sys_common
::AsInner
;
22 pub use sys
::{cvt, cvt_r}
;
24 pub type wrlen_t
= size_t
;
26 pub struct Socket(FileDesc
);
30 pub fn cvt_gai(err
: c_int
) -> io
::Result
<()> {
31 if err
== 0 { return Ok(()) }
34 str::from_utf8(CStr
::from_ptr(c
::gai_strerror(err
)).to_bytes()).unwrap()
37 Err(io
::Error
::new(io
::ErrorKind
::Other
,
38 "failed to lookup address information", Some(detail
)))
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
,
48 let fd
= try
!(cvt(libc
::socket(fam
, ty
, 0)));
49 Ok(Socket(FileDesc
::new(fd
)))
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
)
58 Ok(Socket(FileDesc
::new(fd
)))
61 pub fn duplicate(&self) -> io
::Result
<Socket
> {
62 cvt(unsafe { libc::dup(self.0.raw()) }
).map(|fd
| {
63 Socket(FileDesc
::new(fd
))
67 pub fn read(&self, buf
: &mut [u8]) -> io
::Result
<usize> {
72 impl AsInner
<c_int
> for Socket
{
73 fn as_inner(&self) -> &c_int { self.0.as_inner() }