# unix.rs - source
Source of the Rust file `/home/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/socket2-0.3.19/src/sys/unix.rs`.
Keywords: rust, rustlang, rust-lang

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
     100
     101
     102
     103
     104
     105
     106
     107
     108
     109
     110
     111
     112
     113
     114
     115
     116
     117
     118
     119
     120
     121
     122
     123
     124
     125
     126
     127
     128
     129
     130
     131
     132
     133
     134
     135
     136
     137
     138
     139
     140
     141
     142
     143
     144
     145
     146
     147
     148
     149
     150
     151
     152
     153
     154
     155
     156
     157
     158
     159
     160
     161
     162
     163
     164
     165
     166
     167
     168
     169
     170
     171
     172
     173
     174
     175
     176
     177
     178
     179
     180
     181
     182
     183
     184
     185
     186
     187
     188
     189
     190
     191
     192
     193
     194
     195
     196
     197
     198
     199
     200
     201
     202
     203
     204
     205
     206
     207
     208
     209
     210
     211
     212
     213
     214
     215
     216
     217
     218
     219
     220
     221
     222
     223
     224
     225
     226
     227
     228
     229
     230
     231
     232
     233
     234
     235
     236
     237
     238
     239
     240
     241
     242
     243
     244
     245
     246
     247
     248
     249
     250
     251
     252
     253
     254
     255
     256
     257
     258
     259
     260
     261
     262
     263
     264
     265
     266
     267
     268
     269
     270
     271
     272
     273
     274
     275
     276
     277
     278
     279
     280
     281
     282
     283
     284
     285
     286
     287
     288
     289
     290
     291
     292
     293
     294
     295
     296
     297
     298
     299
     300
     301
     302
     303
     304
     305
     306
     307
     308
     309
     310
     311
     312
     313
     314
     315
     316
     317
     318
     319
     320
     321
     322
     323
     324
     325
     326
     327
     328
     329
     330
     331
     332
     333
     334
     335
     336
     337
     338
     339
     340
     341
     342
     343
     344
     345
     346
     347
     348
     349
     350
     351
     352
     353
     354
     355
     356
     357
     358
     359
     360
     361
     362
     363
     364
     365
     366
     367
     368
     369
     370
     371
     372
     373
     374
     375
     376
     377
     378
     379
     380
     381
     382
     383
     384
     385
     386
     387
     388
     389
     390
     391
     392
     393
     394
     395
     396
     397
     398
     399
     400
     401
     402
     403
     404
     405
     406
     407
     408
     409
     410
     411
     412
     413
     414
     415
     416
     417
     418
     419
     420
     421
     422
     423
     424
     425
     426
     427
     428
     429
     430
     431
     432
     433
     434
     435
     436
     437
     438
     439
     440
     441
     442
     443
     444
     445
     446
     447
     448
     449
     450
     451
     452
     453
     454
     455
     456
     457
     458
     459
     460
     461
     462
     463
     464
     465
     466
     467
     468
     469
     470
     471
     472
     473
     474
     475
     476
     477
     478
     479
     480
     481
     482
     483
     484
     485
     486
     487
     488
     489
     490
     491
     492
     493
     494
     495
     496
     497
     498
     499
     500
     501
     502
     503
     504
     505
     506
     507
     508
     509
     510
     511
     512
     513
     514
     515
     516
     517
     518
     519
     520
     521
     522
     523
     524
     525
     526
     527
     528
     529
     530
     531
     532
     533
     534
     535
     536
     537
     538
     539
     540
     541
     542
     543
     544
     545
     546
     547
     548
     549
     550
     551
     552
     553
     554
     555
     556
     557
     558
     559
     560
     561
     562
     563
     564
     565
     566
     567
     568
     569
     570
     571
     572
     573
     574
     575
     576
     577
     578
     579
     580
     581
     582
     583
     584
     585
     586
     587
     588
     589
     590
     591
     592
     593
     594
     595
     596
     597
     598
     599
     600
     601
     602
     603
     604
     605
     606
     607
     608
     609
     610
     611
     612
     613
     614
     615
     616
     617
     618
     619
     620
     621
     622
     623
     624
     625
     626
     627
     628
     629
     630
     631
     632
     633
     634
     635
     636
     637
     638
     639
     640
     641
     642
     643
     644
     645
     646
     647
     648
     649
     650
     651
     652
     653
     654
     655
     656
     657
     658
     659
     660
     661
     662
     663
     664
     665
     666
     667
     668
     669
     670
     671
     672
     673
     674
     675
     676
     677
     678
     679
     680
     681
     682
     683
     684
     685
     686
     687
     688
     689
     690
     691
     692
     693
     694
     695
     696
     697
     698
     699
     700
     701
     702
     703
     704
     705
     706
     707
     708
     709
     710
     711
     712
     713
     714
     715
     716
     717
     718
     719
     720
     721
     722
     723
     724
     725
     726
     727
     728
     729
     730
     731
     732
     733
     734
     735
     736
     737
     738
     739
     740
     741
     742
     743
     744
     745
     746
     747
     748
     749
     750
     751
     752
     753
     754
     755
     756
     757
     758
     759
     760
     761
     762
     763
     764
     765
     766
     767
     768
     769
     770
     771
     772
     773
     774
     775
     776
     777
     778
     779
     780
     781
     782
     783
     784
     785
     786
     787
     788
     789
     790
     791
     792
     793
     794
     795
     796
     797
     798
     799
     800
     801
     802
     803
     804
     805
     806
     807
     808
     809
     810
     811
     812
     813
     814
     815
     816
     817
     818
     819
     820
     821
     822
     823
     824
     825
     826
     827
     828
     829
     830
     831
     832
     833
     834
     835
     836
     837
     838
     839
     840
     841
     842
     843
     844
     845
     846
     847
     848
     849
     850
     851
     852
     853
     854
     855
     856
     857
     858
     859
     860
     861
     862
     863
     864
     865
     866
     867
     868
     869
     870
     871
     872
     873
     874
     875
     876
     877
     878
     879
     880
     881
     882
     883
     884
     885
     886
     887
     888
     889
     890
     891
     892
     893
     894
     895
     896
     897
     898
     899
     900
     901
     902
     903
     904
     905
     906
     907
     908
     909
     910
     911
     912
     913
     914
     915
     916
     917
     918
     919
     920
     921
     922
     923
     924
     925
     926
     927
     928
     929
     930
     931
     932
     933
     934
     935
     936
     937
     938
     939
     940
     941
     942
     943
     944
     945
     946
     947
     948
     949
     950
     951
     952
     953
     954
     955
     956
     957
     958
     959
     960
     961
     962
     963
     964
     965
     966
     967
     968
     969
     970
     971
     972
     973
     974
     975
     976
     977
     978
     979
     980
     981
     982
     983
     984
     985
     986
     987
     988
     989
     990
     991
     992
     993
     994
     995
     996
     997
     998
     999
    1000
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    1141
    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223
    1224
    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238
    1239
    1240
    1241
    1242
    1243
    1244
    1245
    1246
    1247
    1248
    1249
    1250
    1251
    1252
    1253
    1254
    1255
    1256
    1257
    1258
    1259
    1260
    1261
    1262
    1263
    1264
    1265
    1266
    1267
    1268
    1269
    1270
    1271
    1272
    1273
    1274
    1275
    1276
    1277
    1278
    1279
    1280
    1281
    1282
    1283
    1284
    1285
    1286
    1287
    1288
    1289
    1290
    1291
    1292
    1293
    1294
    1295
    1296
    1297
    1298
    1299
    1300
    1301
    1302
    1303
    1304
    1305
    1306
    1307
    1308
    1309
    1310
    1311
    1312
    1313
    1314
    1315
    1316
    1317

    // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
    // file at the top-level directory of this distribution and at
    // http://rust-lang.org/COPYRIGHT.
    //
    // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
    // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
    // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
    // option. This file may not be copied, modified, or distributed
    // except according to those terms.

    use std::cmp;
    #[cfg(target_os = "linux")]
    use std::ffi::{CStr, CString};
    use std::fmt;
    use std::io;
    use std::io::{ErrorKind, Read, Write};
    use std::mem;
    #[cfg(target_os = "linux")]
    use std::mem::MaybeUninit;
    use std::net::Shutdown;
    use std::net::{self, Ipv4Addr, Ipv6Addr};
    use std::ops::Neg;
    #[cfg(feature = "unix")]
    use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
    use std::os::unix::prelude::*;
    #[cfg(target_os = "linux")]
    use std::ptr;
    #[cfg(target_os = "linux")]
    use std::slice;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::{Duration, Instant};

    use libc::{self, c_void, socklen_t, ssize_t};

    use crate::{Domain, Type};

    pub use libc::c_int;

    // Used in `Domain`.
    pub(crate) use libc::{AF_INET, AF_INET6};
    // Used in `Type`.
    #[cfg(not(target_os = "redox"))]
    pub(crate) use libc::SOCK_RAW;
    pub(crate) use libc::{SOCK_DGRAM, SOCK_SEQPACKET, SOCK_STREAM};
    // Used in `Protocol`.
    pub(crate) use libc::{IPPROTO_ICMP, IPPROTO_ICMPV6, IPPROTO_TCP, IPPROTO_UDP};

    cfg_if::cfg_if! {
        if #[cfg(any(target_os = "dragonfly", target_os = "freebsd",
                     target_os = "ios", target_os = "macos",
                     target_os = "openbsd", target_os = "netbsd",
                     target_os = "solaris", target_os = "illumos",
                     target_os = "haiku"))] {
            use libc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP;
            use libc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP;
        } else {
            use libc::IPV6_ADD_MEMBERSHIP;
            use libc::IPV6_DROP_MEMBERSHIP;
        }
    }

    cfg_if::cfg_if! {
        if #[cfg(any(target_os = "macos", target_os = "ios"))] {
            use libc::TCP_KEEPALIVE as KEEPALIVE_OPTION;
        } else if #[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "haiku"))] {
            use libc::SO_KEEPALIVE as KEEPALIVE_OPTION;
        } else {
            use libc::TCP_KEEPIDLE as KEEPALIVE_OPTION;
        }
    }

    use crate::utils::One;
    use crate::SockAddr;

    /// Unix only API.
    impl Domain {
        /// Domain for Unix socket communication, corresponding to `AF_UNIX`.
        pub fn unix() -> Domain {
            Domain(libc::AF_UNIX)
        }

        /// Domain for low-level packet interface, corresponding to `AF_PACKET`.
        ///
        /// # Notes
        ///
        /// This function is only available on Linux.
        #[cfg(target_os = "linux")]
        pub fn packet() -> Domain {
            Domain(libc::AF_PACKET)
        }
    }

    impl_debug!(
        Domain,
        libc::AF_INET,
        libc::AF_INET6,
        libc::AF_UNIX,
        libc::AF_UNSPEC, // = 0.
    );

    /// Unix only API.
    impl Type {
        /// Set `SOCK_NONBLOCK` on the `Type`.
        ///
        /// # Notes
        ///
        /// This function is only available on Android, DragonFlyBSD, FreeBSD,
        /// Linux, NetBSD and OpenBSD.
        #[cfg(any(
            target_os = "android",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "linux",
            target_os = "netbsd",
            target_os = "openbsd"
        ))]
        pub fn non_blocking(self) -> Type {
            Type(self.0 | libc::SOCK_NONBLOCK)
        }

        /// Set `SOCK_CLOEXEC` on the `Type`.
        ///
        /// # Notes
        ///
        /// This function is only available on Android, DragonFlyBSD, FreeBSD,
        /// Linux, NetBSD and OpenBSD.
        #[cfg(any(
            target_os = "android",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "linux",
            target_os = "netbsd",
            target_os = "openbsd"
        ))]
        pub fn cloexec(self) -> Type {
            Type(self.0 | libc::SOCK_CLOEXEC)
        }
    }

    impl_debug!(
        crate::Type,
        libc::SOCK_STREAM,
        libc::SOCK_DGRAM,
        #[cfg(not(target_os = "redox"))]
        libc::SOCK_RAW,
        #[cfg(not(any(target_os = "haiku", target_os = "redox")))]
        libc::SOCK_RDM,
        libc::SOCK_SEQPACKET,
        /* TODO: add these optional bit OR-ed flags:
        #[cfg(any(
            target_os = "android",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "linux",
            target_os = "netbsd",
            target_os = "openbsd"
        ))]
        libc::SOCK_NONBLOCK,
        #[cfg(any(
            target_os = "android",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "linux",
            target_os = "netbsd",
            target_os = "openbsd"
        ))]
        libc::SOCK_CLOEXEC,
        */
    );

    impl_debug!(
        crate::Protocol,
        libc::IPPROTO_ICMP,
        libc::IPPROTO_ICMPV6,
        libc::IPPROTO_TCP,
        libc::IPPROTO_UDP,
    );

    pub struct Socket {
        fd: c_int,
    }

    impl Socket {
        pub fn new(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> {
            unsafe {
                // On linux we first attempt to pass the SOCK_CLOEXEC flag to
                // atomically create the socket and set it as CLOEXEC. Support for
                // this option, however, was added in 2.6.27, and we still support
                // 2.6.18 as a kernel, so if the returned error is EINVAL we
                // fallthrough to the fallback.
                #[cfg(target_os = "linux")]
                {
                    match cvt(libc::socket(family, ty | libc::SOCK_CLOEXEC, protocol)) {
                        Ok(fd) => return Ok(Socket::from_raw_fd(fd)),
                        Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
                        Err(e) => return Err(e),
                    }
                }

                let fd = cvt(libc::socket(family, ty, protocol))?;
                let fd = Socket::from_raw_fd(fd);
                set_cloexec(fd.as_raw_fd())?;
                #[cfg(any(target_os = "macos", target_os = "ios"))]
                {
                    fd.setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?;
                }
                Ok(fd)
            }
        }

        pub fn pair(family: c_int, ty: c_int, protocol: c_int) -> io::Result<(Socket, Socket)> {
            unsafe {
                let mut fds = [0, 0];
                cvt(libc::socketpair(family, ty, protocol, fds.as_mut_ptr()))?;
                let fds = (Socket::from_raw_fd(fds[0]), Socket::from_raw_fd(fds[1]));
                set_cloexec(fds.0.as_raw_fd())?;
                set_cloexec(fds.1.as_raw_fd())?;
                #[cfg(any(target_os = "macos", target_os = "ios"))]
                {
                    fds.0
                        .setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?;
                    fds.1
                        .setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?;
                }
                Ok(fds)
            }
        }

        pub fn bind(&self, addr: &SockAddr) -> io::Result<()> {
            unsafe { cvt(libc::bind(self.fd, addr.as_ptr(), addr.len() as _)).map(|_| ()) }
        }

        pub fn listen(&self, backlog: i32) -> io::Result<()> {
            unsafe { cvt(libc::listen(self.fd, backlog)).map(|_| ()) }
        }

        pub fn connect(&self, addr: &SockAddr) -> io::Result<()> {
            unsafe { cvt(libc::connect(self.fd, addr.as_ptr(), addr.len())).map(|_| ()) }
        }

        pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> {
            self.set_nonblocking(true)?;
            let r = self.connect(addr);
            self.set_nonblocking(false)?;

            match r {
                Ok(()) => return Ok(()),
                // there's no io::ErrorKind conversion registered for EINPROGRESS :(
                Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
                Err(e) => return Err(e),
            }

            let mut pollfd = libc::pollfd {
                fd: self.fd,
                events: libc::POLLOUT,
                revents: 0,
            };

            if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "cannot set a 0 duration timeout",
                ));
            }

            let start = Instant::now();

            loop {
                let elapsed = start.elapsed();
                if elapsed >= timeout {
                    return Err(io::Error::new(
                        io::ErrorKind::TimedOut,
                        "connection timed out",
                    ));
                }

                let timeout = timeout - elapsed;
                let mut timeout = timeout
                    .as_secs()
                    .saturating_mul(1_000)
                    .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
                if timeout == 0 {
                    timeout = 1;
                }

                let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int;

                match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
                    -1 => {
                        let err = io::Error::last_os_error();
                        if err.kind() != io::ErrorKind::Interrupted {
                            return Err(err);
                        }
                    }
                    0 => {
                        return Err(io::Error::new(
                            io::ErrorKind::TimedOut,
                            "connection timed out",
                        ))
                    }
                    _ => {
                        // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
                        // for POLLHUP rather than read readiness
                        if pollfd.revents & libc::POLLHUP != 0 {
                            let e = self.take_error()?.unwrap_or_else(|| {
                                io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
                            });
                            return Err(e);
                        }
                        return Ok(());
                    }
                }
            }
        }

        pub fn local_addr(&self) -> io::Result<SockAddr> {
            unsafe {
                let mut storage: libc::sockaddr_storage = mem::zeroed();
                let mut len = mem::size_of_val(&storage) as libc::socklen_t;
                cvt(libc::getsockname(
                    self.fd,
                    &mut storage as *mut _ as *mut _,
                    &mut len,
                ))?;
                Ok(SockAddr::from_raw_parts(
                    &storage as *const _ as *const _,
                    len,
                ))
            }
        }

        pub fn peer_addr(&self) -> io::Result<SockAddr> {
            unsafe {
                let mut storage: libc::sockaddr_storage = mem::zeroed();
                let mut len = mem::size_of_val(&storage) as libc::socklen_t;
                cvt(libc::getpeername(
                    self.fd,
                    &mut storage as *mut _ as *mut _,
                    &mut len,
                ))?;
                Ok(SockAddr::from_raw_parts(
                    &storage as *const _ as *const _,
                    len,
                ))
            }
        }

        pub fn try_clone(&self) -> io::Result<Socket> {
            // implementation lifted from libstd
            #[cfg(any(target_os = "android", target_os = "haiku"))]
            use libc::F_DUPFD as F_DUPFD_CLOEXEC;
            #[cfg(not(any(target_os = "android", target_os = "haiku")))]
            use libc::F_DUPFD_CLOEXEC;

            static CLOEXEC_FAILED: AtomicBool = AtomicBool::new(false);
            unsafe {
                if !CLOEXEC_FAILED.load(Ordering::Relaxed) {
                    match cvt(libc::fcntl(self.fd, F_DUPFD_CLOEXEC, 0)) {
                        Ok(fd) => {
                            let fd = Socket::from_raw_fd(fd);
                            if cfg!(target_os = "linux") {
                                set_cloexec(fd.as_raw_fd())?;
                            }
                            return Ok(fd);
                        }
                        Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
                            CLOEXEC_FAILED.store(true, Ordering::Relaxed);
                        }
                        Err(e) => return Err(e),
                    }
                }
                let fd = cvt(libc::fcntl(self.fd, libc::F_DUPFD, 0))?;
                let fd = Socket::from_raw_fd(fd);
                set_cloexec(fd.as_raw_fd())?;
                Ok(fd)
            }
        }

        #[allow(unused_mut)]
        pub fn accept(&self) -> io::Result<(Socket, SockAddr)> {
            let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
            let mut len = mem::size_of_val(&storage) as socklen_t;

            let mut socket = None;
            #[cfg(target_os = "linux")]
            {
                let res = cvt_r(|| unsafe {
                    libc::syscall(
                        libc::SYS_accept4,
                        self.fd as libc::c_long,
                        &mut storage as *mut _ as libc::c_long,
                        &mut len,
                        libc::SOCK_CLOEXEC as libc::c_long,
                    ) as libc::c_int
                });
                match res {
                    Ok(fd) => socket = Some(Socket { fd: fd }),
                    Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {}
                    Err(e) => return Err(e),
                }
            }

            let socket = match socket {
                Some(socket) => socket,
                None => unsafe {
                    let fd =
                        cvt_r(|| libc::accept(self.fd, &mut storage as *mut _ as *mut _, &mut len))?;
                    let fd = Socket::from_raw_fd(fd);
                    set_cloexec(fd.as_raw_fd())?;
                    fd
                },
            };
            let addr = unsafe { SockAddr::from_raw_parts(&storage as *const _ as *const _, len) };
            Ok((socket, addr))
        }

        pub fn take_error(&self) -> io::Result<Option<io::Error>> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_ERROR)?;
                if raw == 0 {
                    Ok(None)
                } else {
                    Ok(Some(io::Error::from_raw_os_error(raw as i32)))
                }
            }
        }

        pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
            unsafe {
                let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
                let new = if nonblocking {
                    previous | libc::O_NONBLOCK
                } else {
                    previous & !libc::O_NONBLOCK
                };
                if new != previous {
                    cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
                }
                Ok(())
            }
        }

        pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
            let how = match how {
                Shutdown::Write => libc::SHUT_WR,
                Shutdown::Read => libc::SHUT_RD,
                Shutdown::Both => libc::SHUT_RDWR,
            };
            cvt(unsafe { libc::shutdown(self.fd, how) })?;
            Ok(())
        }

        pub fn recv(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
            unsafe {
                let n = cvt({
                    libc::recv(
                        self.fd,
                        buf.as_mut_ptr() as *mut c_void,
                        cmp::min(buf.len(), max_len()),
                        flags,
                    )
                })?;
                Ok(n as usize)
            }
        }

        pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
            unsafe {
                let n = cvt({
                    libc::recv(
                        self.fd,
                        buf.as_mut_ptr() as *mut c_void,
                        cmp::min(buf.len(), max_len()),
                        libc::MSG_PEEK,
                    )
                })?;
                Ok(n as usize)
            }
        }

        pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> {
            self.recv_from(buf, libc::MSG_PEEK)
        }

        pub fn recv_from(&self, buf: &mut [u8], flags: c_int) -> io::Result<(usize, SockAddr)> {
            unsafe {
                let mut storage: libc::sockaddr_storage = mem::zeroed();
                let mut addrlen = mem::size_of_val(&storage) as socklen_t;

                let n = cvt({
                    libc::recvfrom(
                        self.fd,
                        buf.as_mut_ptr() as *mut c_void,
                        cmp::min(buf.len(), max_len()),
                        flags,
                        &mut storage as *mut _ as *mut _,
                        &mut addrlen,
                    )
                })?;
                let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, addrlen);
                Ok((n as usize, addr))
            }
        }

        pub fn send(&self, buf: &[u8], flags: c_int) -> io::Result<usize> {
            unsafe {
                let n = cvt({
                    libc::send(
                        self.fd,
                        buf.as_ptr() as *const c_void,
                        cmp::min(buf.len(), max_len()),
                        flags,
                    )
                })?;
                Ok(n as usize)
            }
        }

        pub fn send_to(&self, buf: &[u8], flags: c_int, addr: &SockAddr) -> io::Result<usize> {
            unsafe {
                let n = cvt({
                    libc::sendto(
                        self.fd,
                        buf.as_ptr() as *const c_void,
                        cmp::min(buf.len(), max_len()),
                        flags,
                        addr.as_ptr(),
                        addr.len(),
                    )
                })?;
                Ok(n as usize)
            }
        }

        // ================================================

        pub fn ttl(&self) -> io::Result<u32> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_TTL)?;
                Ok(raw as u32)
            }
        }

        pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
            unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int) }
        }

        #[cfg(not(target_os = "redox"))]
        pub fn mss(&self) -> io::Result<u32> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_TCP, libc::TCP_MAXSEG)?;
                Ok(raw as u32)
            }
        }

        #[cfg(not(target_os = "redox"))]
        pub fn set_mss(&self, mss: u32) -> io::Result<()> {
            unsafe { self.setsockopt(libc::IPPROTO_TCP, libc::TCP_MAXSEG, mss as c_int) }
        }

        #[cfg(target_os = "linux")]
        pub fn mark(&self) -> io::Result<u32> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_MARK)?;
                Ok(raw as u32)
            }
        }

        #[cfg(target_os = "linux")]
        pub fn set_mark(&self, mark: u32) -> io::Result<()> {
            unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_MARK, mark as c_int) }
        }

        #[cfg(target_os = "linux")]
        pub fn device(&self) -> io::Result<Option<CString>> {
            // TODO: replace with `MaybeUninit::uninit_array` once stable.
            let mut buf: [MaybeUninit<u8>; libc::IFNAMSIZ] =
                unsafe { MaybeUninit::<[MaybeUninit<u8>; libc::IFNAMSIZ]>::uninit().assume_init() };
            let mut len = buf.len() as libc::socklen_t;
            let len = unsafe {
                cvt(libc::getsockopt(
                    self.fd,
                    libc::SOL_SOCKET,
                    libc::SO_BINDTODEVICE,
                    buf.as_mut_ptr().cast(),
                    &mut len,
                ))?
            };
            if len == 0 {
                Ok(None)
            } else {
                // Allocate a buffer for `CString` with the length including the
                // null terminator.
                let len = len as usize;
                let mut name = Vec::with_capacity(len);

                // TODO: use `MaybeUninit::slice_assume_init_ref` once stable.
                // Safety: `len` bytes are writen by the OS, this includes a null
                // terminator. However we don't copy the null terminator because
                // `CString::from_vec_unchecked` adds its own null terminator.
                let buf = unsafe { slice::from_raw_parts(buf.as_ptr().cast(), len - 1) };
                name.extend_from_slice(buf);

                // Safety: the OS initialised the string for us, which shouldn't
                // include any null bytes.
                Ok(Some(unsafe { CString::from_vec_unchecked(name) }))
            }
        }

        #[cfg(target_os = "linux")]
        pub fn bind_device(&self, interface: Option<&CStr>) -> io::Result<()> {
            let (value, len) = if let Some(interface) = interface {
                (interface.as_ptr(), interface.to_bytes_with_nul().len())
            } else {
                (ptr::null(), 0)
            };

            unsafe {
                cvt(libc::setsockopt(
                    self.fd,
                    libc::SOL_SOCKET,
                    libc::SO_BINDTODEVICE,
                    value.cast(),
                    len as libc::socklen_t,
                ))
                .map(|_| ())
            }
        }

        pub fn unicast_hops_v6(&self) -> io::Result<u32> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_UNICAST_HOPS)?;
                Ok(raw as u32)
            }
        }

        pub fn set_unicast_hops_v6(&self, hops: u32) -> io::Result<()> {
            unsafe {
                self.setsockopt(
                    libc::IPPROTO_IPV6 as c_int,
                    libc::IPV6_UNICAST_HOPS,
                    hops as c_int,
                )
            }
        }

        pub fn only_v6(&self) -> io::Result<bool> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_V6ONLY)?;
                Ok(raw != 0)
            }
        }

        pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
            unsafe { self.setsockopt(libc::IPPROTO_IPV6, libc::IPV6_V6ONLY, only_v6 as c_int) }
        }

        pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
            unsafe {
                Ok(timeval2dur(
                    self.getsockopt(libc::SOL_SOCKET, libc::SO_RCVTIMEO)?,
                ))
            }
        }

        pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
            unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_RCVTIMEO, dur2timeval(dur)?) }
        }

        pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
            unsafe {
                Ok(timeval2dur(
                    self.getsockopt(libc::SOL_SOCKET, libc::SO_SNDTIMEO)?,
                ))
            }
        }

        pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
            unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_SNDTIMEO, dur2timeval(dur)?) }
        }

        pub fn nodelay(&self) -> io::Result<bool> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
                Ok(raw != 0)
            }
        }

        pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
            unsafe { self.setsockopt(libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int) }
        }

        pub fn broadcast(&self) -> io::Result<bool> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_BROADCAST)?;
                Ok(raw != 0)
            }
        }

        pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
            unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_BROADCAST, broadcast as c_int) }
        }

        pub fn multicast_loop_v4(&self) -> io::Result<bool> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_LOOP)?;
                Ok(raw != 0)
            }
        }

        pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
            unsafe {
                self.setsockopt(
                    libc::IPPROTO_IP,
                    libc::IP_MULTICAST_LOOP,
                    multicast_loop_v4 as c_int,
                )
            }
        }

        pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_TTL)?;
                Ok(raw as u32)
            }
        }

        pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
            unsafe {
                self.setsockopt(
                    libc::IPPROTO_IP,
                    libc::IP_MULTICAST_TTL,
                    multicast_ttl_v4 as c_int,
                )
            }
        }

        pub fn multicast_hops_v6(&self) -> io::Result<u32> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_HOPS)?;
                Ok(raw as u32)
            }
        }

        pub fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()> {
            unsafe { self.setsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_HOPS, hops as c_int) }
        }

        pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> {
            unsafe {
                let imr_interface: libc::in_addr =
                    self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_IF)?;
                Ok(from_s_addr(imr_interface.s_addr))
            }
        }

        pub fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()> {
            let interface = to_s_addr(interface);
            let imr_interface = libc::in_addr { s_addr: interface };

            unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_IF, imr_interface) }
        }

        pub fn multicast_if_v6(&self) -> io::Result<u32> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_IF)?;
                Ok(raw as u32)
            }
        }

        pub fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()> {
            unsafe {
                self.setsockopt(
                    libc::IPPROTO_IPV6,
                    libc::IPV6_MULTICAST_IF,
                    interface as c_int,
                )
            }
        }

        pub fn multicast_loop_v6(&self) -> io::Result<bool> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_LOOP)?;
                Ok(raw != 0)
            }
        }

        pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
            unsafe {
                self.setsockopt(
                    libc::IPPROTO_IPV6,
                    libc::IPV6_MULTICAST_LOOP,
                    multicast_loop_v6 as c_int,
                )
            }
        }

        pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
            let multiaddr = to_s_addr(multiaddr);
            let interface = to_s_addr(interface);
            let mreq = libc::ip_mreq {
                imr_multiaddr: libc::in_addr { s_addr: multiaddr },
                imr_interface: libc::in_addr { s_addr: interface },
            };
            unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_ADD_MEMBERSHIP, mreq) }
        }

        pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
            let multiaddr = to_in6_addr(multiaddr);
            let mreq = libc::ipv6_mreq {
                ipv6mr_multiaddr: multiaddr,
                ipv6mr_interface: to_ipv6mr_interface(interface),
            };
            unsafe { self.setsockopt(libc::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq) }
        }

        pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
            let multiaddr = to_s_addr(multiaddr);
            let interface = to_s_addr(interface);
            let mreq = libc::ip_mreq {
                imr_multiaddr: libc::in_addr { s_addr: multiaddr },
                imr_interface: libc::in_addr { s_addr: interface },
            };
            unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_DROP_MEMBERSHIP, mreq) }
        }

        pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
            let multiaddr = to_in6_addr(multiaddr);
            let mreq = libc::ipv6_mreq {
                ipv6mr_multiaddr: multiaddr,
                ipv6mr_interface: to_ipv6mr_interface(interface),
            };
            unsafe { self.setsockopt(libc::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq) }
        }

        pub fn linger(&self) -> io::Result<Option<Duration>> {
            unsafe {
                Ok(linger2dur(
                    self.getsockopt(libc::SOL_SOCKET, libc::SO_LINGER)?,
                ))
            }
        }

        pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> {
            unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_LINGER, dur2linger(dur)) }
        }

        pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> {
            unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_REUSEADDR, reuse as c_int) }
        }

        pub fn reuse_address(&self) -> io::Result<bool> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_REUSEADDR)?;
                Ok(raw != 0)
            }
        }

        pub fn recv_buffer_size(&self) -> io::Result<usize> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF)?;
                Ok(raw as usize)
            }
        }

        pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> {
            unsafe {
                // TODO: casting usize to a c_int should be a checked cast
                self.setsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF, size as c_int)
            }
        }

        pub fn send_buffer_size(&self) -> io::Result<usize> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF)?;
                Ok(raw as usize)
            }
        }

        pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> {
            unsafe {
                // TODO: casting usize to a c_int should be a checked cast
                self.setsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF, size as c_int)
            }
        }

        pub fn keepalive(&self) -> io::Result<Option<Duration>> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_KEEPALIVE)?;
                if raw == 0 {
                    return Ok(None);
                }
                let secs: c_int = self.getsockopt(libc::IPPROTO_TCP, KEEPALIVE_OPTION)?;
                Ok(Some(Duration::new(secs as u64, 0)))
            }
        }

        pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> {
            unsafe {
                self.setsockopt(
                    libc::SOL_SOCKET,
                    libc::SO_KEEPALIVE,
                    keepalive.is_some() as c_int,
                )?;
                if let Some(dur) = keepalive {
                    // TODO: checked cast here
                    self.setsockopt(libc::IPPROTO_TCP, KEEPALIVE_OPTION, dur.as_secs() as c_int)?;
                }
                Ok(())
            }
        }

        #[cfg(all(
            unix,
            not(any(target_os = "solaris", target_os = "illumos")),
            feature = "reuseport"
        ))]
        pub fn reuse_port(&self) -> io::Result<bool> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_REUSEPORT)?;
                Ok(raw != 0)
            }
        }

        #[cfg(all(
            unix,
            not(any(target_os = "solaris", target_os = "illumos")),
            feature = "reuseport"
        ))]
        pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> {
            unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_REUSEPORT, reuse as c_int) }
        }

        pub fn out_of_band_inline(&self) -> io::Result<bool> {
            unsafe {
                let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_OOBINLINE)?;
                Ok(raw != 0)
            }
        }

        pub fn set_out_of_band_inline(&self, oob_inline: bool) -> io::Result<()> {
            unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_OOBINLINE, oob_inline as c_int) }
        }

        unsafe fn setsockopt<T>(&self, opt: c_int, val: c_int, payload: T) -> io::Result<()>
        where
            T: Copy,
        {
            let payload = &payload as *const T as *const c_void;
            cvt(libc::setsockopt(
                self.fd,
                opt,
                val,
                payload,
                mem::size_of::<T>() as libc::socklen_t,
            ))?;
            Ok(())
        }

        unsafe fn getsockopt<T: Copy>(&self, opt: c_int, val: c_int) -> io::Result<T> {
            let mut slot: T = mem::zeroed();
            let mut len = mem::size_of::<T>() as libc::socklen_t;
            cvt(libc::getsockopt(
                self.fd,
                opt,
                val,
                &mut slot as *mut _ as *mut _,
                &mut len,
            ))?;
            assert_eq!(len as usize, mem::size_of::<T>());
            Ok(slot)
        }
    }

    impl Read for Socket {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            <&Socket>::read(&mut &*self, buf)
        }
    }

    impl<'a> Read for &'a Socket {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            unsafe {
                let n = cvt({
                    libc::read(
                        self.fd,
                        buf.as_mut_ptr() as *mut c_void,
                        cmp::min(buf.len(), max_len()),
                    )
                })?;
                Ok(n as usize)
            }
        }
    }

    impl Write for Socket {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            <&Socket>::write(&mut &*self, buf)
        }

        fn flush(&mut self) -> io::Result<()> {
            <&Socket>::flush(&mut &*self)
        }
    }

    impl<'a> Write for &'a Socket {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.send(buf, 0)
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    impl fmt::Debug for Socket {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            let mut f = f.debug_struct("Socket");
            f.field("fd", &self.fd);
            if let Ok(addr) = self.local_addr() {
                f.field("local_addr", &addr);
            }
            if let Ok(addr) = self.peer_addr() {
                f.field("peer_addr", &addr);
            }
            f.finish()
        }
    }

    impl AsRawFd for Socket {
        fn as_raw_fd(&self) -> c_int {
            self.fd
        }
    }

    impl IntoRawFd for Socket {
        fn into_raw_fd(self) -> c_int {
            let fd = self.fd;
            mem::forget(self);
            return fd;
        }
    }

    impl FromRawFd for Socket {
        unsafe fn from_raw_fd(fd: c_int) -> Socket {
            Socket { fd: fd }
        }
    }

    impl AsRawFd for crate::Socket {
        fn as_raw_fd(&self) -> c_int {
            self.inner.as_raw_fd()
        }
    }

    impl IntoRawFd for crate::Socket {
        fn into_raw_fd(self) -> c_int {
            self.inner.into_raw_fd()
        }
    }

    impl FromRawFd for crate::Socket {
        unsafe fn from_raw_fd(fd: c_int) -> crate::Socket {
            crate::Socket {
                inner: Socket::from_raw_fd(fd),
            }
        }
    }

    impl Drop for Socket {
        fn drop(&mut self) {
            unsafe {
                let _ = libc::close(self.fd);
            }
        }
    }

    impl From<Socket> for net::TcpStream {
        fn from(socket: Socket) -> net::TcpStream {
            unsafe { net::TcpStream::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    impl From<Socket> for net::TcpListener {
        fn from(socket: Socket) -> net::TcpListener {
            unsafe { net::TcpListener::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    impl From<Socket> for net::UdpSocket {
        fn from(socket: Socket) -> net::UdpSocket {
            unsafe { net::UdpSocket::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    #[cfg(all(unix, feature = "unix"))]
    impl From<Socket> for UnixStream {
        fn from(socket: Socket) -> UnixStream {
            unsafe { UnixStream::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    #[cfg(all(unix, feature = "unix"))]
    impl From<Socket> for UnixListener {
        fn from(socket: Socket) -> UnixListener {
            unsafe { UnixListener::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    #[cfg(all(unix, feature = "unix"))]
    impl From<Socket> for UnixDatagram {
        fn from(socket: Socket) -> UnixDatagram {
            unsafe { UnixDatagram::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    impl From<net::TcpStream> for Socket {
        fn from(socket: net::TcpStream) -> Socket {
            unsafe { Socket::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    impl From<net::TcpListener> for Socket {
        fn from(socket: net::TcpListener) -> Socket {
            unsafe { Socket::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    impl From<net::UdpSocket> for Socket {
        fn from(socket: net::UdpSocket) -> Socket {
            unsafe { Socket::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    #[cfg(all(unix, feature = "unix"))]
    impl From<UnixStream> for Socket {
        fn from(socket: UnixStream) -> Socket {
            unsafe { Socket::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    #[cfg(all(unix, feature = "unix"))]
    impl From<UnixListener> for Socket {
        fn from(socket: UnixListener) -> Socket {
            unsafe { Socket::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    #[cfg(all(unix, feature = "unix"))]
    impl From<UnixDatagram> for Socket {
        fn from(socket: UnixDatagram) -> Socket {
            unsafe { Socket::from_raw_fd(socket.into_raw_fd()) }
        }
    }

    fn max_len() -> usize {
        // The maximum read limit on most posix-like systems is `SSIZE_MAX`,
        // with the man page quoting that if the count of bytes to read is
        // greater than `SSIZE_MAX` the result is "unspecified".
        //
        // On macOS, however, apparently the 64-bit libc is either buggy or
        // intentionally showing odd behavior by rejecting any read with a size
        // larger than or equal to INT_MAX. To handle both of these the read
        // size is capped on both platforms.
        if cfg!(target_os = "macos") {
            <c_int>::max_value() as usize - 1
        } else {
            <ssize_t>::max_value() as usize
        }
    }

    fn cvt<T: One + PartialEq + Neg<Output = T>>(t: T) -> io::Result<T> {
        let one: T = T::one();
        if t == -one {
            Err(io::Error::last_os_error())
        } else {
            Ok(t)
        }
    }

    fn cvt_r<F, T>(mut f: F) -> io::Result<T>
    where
        F: FnMut() -> T,
        T: One + PartialEq + Neg<Output = T>,
    {
        loop {
            match cvt(f()) {
                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
                other => return other,
            }
        }
    }

    fn set_cloexec(fd: c_int) -> io::Result<()> {
        unsafe {
            let previous = cvt(libc::fcntl(fd, libc::F_GETFD))?;
            let new = previous | libc::FD_CLOEXEC;
            if new != previous {
                cvt(libc::fcntl(fd, libc::F_SETFD, new))?;
            }
            Ok(())
        }
    }

    fn dur2timeval(dur: Option<Duration>) -> io::Result<libc::timeval> {
        match dur {
            Some(dur) => {
                if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "cannot set a 0 duration timeout",
                    ));
                }

                let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
                    libc::time_t::max_value()
                } else {
                    dur.as_secs() as libc::time_t
                };
                let mut timeout = libc::timeval {
                    tv_sec: secs,
                    tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t,
                };
                if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
                    timeout.tv_usec = 1;
                }
                Ok(timeout)
            }
            None => Ok(libc::timeval {
                tv_sec: 0,
                tv_usec: 0,
            }),
        }
    }

    fn timeval2dur(raw: libc::timeval) -> Option<Duration> {
        if raw.tv_sec == 0 && raw.tv_usec == 0 {
            None
        } else {
            let sec = raw.tv_sec as u64;
            let nsec = (raw.tv_usec as u32) * 1000;
            Some(Duration::new(sec, nsec))
        }
    }

    fn to_s_addr(addr: &Ipv4Addr) -> libc::in_addr_t {
        let octets = addr.octets();
        crate::hton(
            ((octets[0] as libc::in_addr_t) << 24)
                | ((octets[1] as libc::in_addr_t) << 16)
                | ((octets[2] as libc::in_addr_t) << 8)
                | ((octets[3] as libc::in_addr_t) << 0),
        )
    }

    fn from_s_addr(in_addr: libc::in_addr_t) -> Ipv4Addr {
        let h_addr = crate::ntoh(in_addr);

        let a: u8 = (h_addr >> 24) as u8;
        let b: u8 = (h_addr >> 16) as u8;
        let c: u8 = (h_addr >> 8) as u8;
        let d: u8 = (h_addr >> 0) as u8;

        Ipv4Addr::new(a, b, c, d)
    }

    fn to_in6_addr(addr: &Ipv6Addr) -> libc::in6_addr {
        let mut ret: libc::in6_addr = unsafe { mem::zeroed() };
        ret.s6_addr = addr.octets();
        return ret;
    }

    #[cfg(target_os = "android")]
    fn to_ipv6mr_interface(value: u32) -> c_int {
        value as c_int
    }

    #[cfg(not(target_os = "android"))]
    fn to_ipv6mr_interface(value: u32) -> libc::c_uint {
        value as libc::c_uint
    }

    fn linger2dur(linger_opt: libc::linger) -> Option<Duration> {
        if linger_opt.l_onoff == 0 {
            None
        } else {
            Some(Duration::from_secs(linger_opt.l_linger as u64))
        }
    }

    fn dur2linger(dur: Option<Duration>) -> libc::linger {
        match dur {
            Some(d) => libc::linger {
                l_onoff: 1,
                l_linger: d.as_secs() as c_int,
            },
            None => libc::linger {
                l_onoff: 0,
                l_linger: 0,
            },
        }
    }

    #[test]
    fn test_ip() {
        let ip = Ipv4Addr::new(127, 0, 0, 1);
        assert_eq!(ip, from_s_addr(to_s_addr(&ip)));
    }

    #[test]
    fn test_out_of_band_inline() {
        let tcp = Socket::new(libc::AF_INET, libc::SOCK_STREAM, 0).unwrap();
        assert_eq!(tcp.out_of_band_inline().unwrap(), false);

        tcp.set_out_of_band_inline(true).unwrap();
        assert_eq!(tcp.out_of_band_inline().unwrap(), true);
    }