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
// 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::fmt;
use std::io::{self, Read, Write};
use std::net::{self, Ipv4Addr, Ipv6Addr, Shutdown};
use std::time::Duration;
#[cfg(all(unix, feature = "unix"))]
use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};

#[cfg(unix)]
use libc as c;
#[cfg(windows)]
use winapi::shared::ws2def as c;

use sys;
use {Domain, Protocol, SockAddr, Socket, Type};

impl Socket {
    /// Creates a new socket ready to be configured.
    ///
    /// This function corresponds to `socket(2)` and simply creates a new
    /// socket, no other configuration is done and further functions must be
    /// invoked to configure this socket.
    pub fn new(domain: Domain, type_: Type, protocol: Option<Protocol>) -> io::Result<Socket> {
        let protocol = protocol.map(|p| p.0).unwrap_or(0);
        Ok(Socket {
            inner: sys::Socket::new(domain.0, type_.0, protocol)?,
        })
    }

    /// Creates a pair of sockets which are connected to each other.
    ///
    /// This function corresponds to `socketpair(2)`.
    ///
    /// This function is only available on Unix when the `pair` feature is
    /// enabled.
    #[cfg(all(unix, feature = "pair"))]
    pub fn pair(
        domain: Domain,
        type_: Type,
        protocol: Option<Protocol>,
    ) -> io::Result<(Socket, Socket)> {
        let protocol = protocol.map(|p| p.0).unwrap_or(0);
        let sockets = sys::Socket::pair(domain.0, type_.0, protocol)?;
        Ok((Socket { inner: sockets.0 }, Socket { inner: sockets.1 }))
    }

    /// Consumes this `Socket`, converting it to a `TcpStream`.
    pub fn into_tcp_stream(self) -> net::TcpStream {
        self.into()
    }

    /// Consumes this `Socket`, converting it to a `TcpListener`.
    pub fn into_tcp_listener(self) -> net::TcpListener {
        self.into()
    }

    /// Consumes this `Socket`, converting it to a `UdpSocket`.
    pub fn into_udp_socket(self) -> net::UdpSocket {
        self.into()
    }

    /// Consumes this `Socket`, converting it into a `UnixStream`.
    ///
    /// This function is only available on Unix when the `unix` feature is
    /// enabled.
    #[cfg(all(unix, feature = "unix"))]
    pub fn into_unix_stream(self) -> UnixStream {
        self.into()
    }

    /// Consumes this `Socket`, converting it into a `UnixListener`.
    ///
    /// This function is only available on Unix when the `unix` feature is
    /// enabled.
    #[cfg(all(unix, feature = "unix"))]
    pub fn into_unix_listener(self) -> UnixListener {
        self.into()
    }

    /// Consumes this `Socket`, converting it into a `UnixDatagram`.
    ///
    /// This function is only available on Unix when the `unix` feature is
    /// enabled.
    #[cfg(all(unix, feature = "unix"))]
    pub fn into_unix_datagram(self) -> UnixDatagram {
        self.into()
    }

    /// Initiate a connection on this socket to the specified address.
    ///
    /// This function directly corresponds to the connect(2) function on Windows
    /// and Unix.
    ///
    /// An error will be returned if `listen` or `connect` has already been
    /// called on this builder.
    pub fn connect(&self, addr: &SockAddr) -> io::Result<()> {
        self.inner.connect(addr)
    }

    /// Initiate a connection on this socket to the specified address, only
    /// only waiting for a certain period of time for the connection to be
    /// established.
    ///
    /// Unlike many other methods on `Socket`, this does *not* correspond to a
    /// single C function. It sets the socket to nonblocking mode, connects via
    /// connect(2), and then waits for the connection to complete with poll(2)
    /// on Unix and select on Windows. When the connection is complete, the
    /// socket is set back to blocking mode. On Unix, this will loop over
    /// `EINTR` errors.
    ///
    /// # Warnings
    ///
    /// The nonblocking state of the socket is overridden by this function -
    /// it will be returned in blocking mode on success, and in an indeterminate
    /// state on failure.
    ///
    /// If the connection request times out, it may still be processing in the
    /// background - a second call to `connect` or `connect_timeout` may fail.
    pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> {
        self.inner.connect_timeout(addr, timeout)
    }

    /// Binds this socket to the specified address.
    ///
    /// This function directly corresponds to the bind(2) function on Windows
    /// and Unix.
    pub fn bind(&self, addr: &SockAddr) -> io::Result<()> {
        self.inner.bind(addr)
    }

    /// Mark a socket as ready to accept incoming connection requests using
    /// accept()
    ///
    /// This function directly corresponds to the listen(2) function on Windows
    /// and Unix.
    ///
    /// An error will be returned if `listen` or `connect` has already been
    /// called on this builder.
    pub fn listen(&self, backlog: i32) -> io::Result<()> {
        self.inner.listen(backlog)
    }

    /// Accept a new incoming connection from this listener.
    ///
    /// This function will block the calling thread until a new connection is
    /// established. When established, the corresponding `Socket` and the
    /// remote peer's address will be returned.
    pub fn accept(&self) -> io::Result<(Socket, SockAddr)> {
        self.inner
            .accept()
            .map(|(socket, addr)| (Socket { inner: socket }, addr))
    }

    /// Returns the socket address of the local half of this TCP connection.
    pub fn local_addr(&self) -> io::Result<SockAddr> {
        self.inner.local_addr()
    }

    /// Returns the socket address of the remote peer of this TCP connection.
    pub fn peer_addr(&self) -> io::Result<SockAddr> {
        self.inner.peer_addr()
    }

    /// Creates a new independently owned handle to the underlying socket.
    ///
    /// The returned `TcpStream` is a reference to the same stream that this
    /// object references. Both handles will read and write the same stream of
    /// data, and options set on one stream will be propagated to the other
    /// stream.
    pub fn try_clone(&self) -> io::Result<Socket> {
        self.inner.try_clone().map(|s| Socket { inner: s })
    }

    /// Get the value of the `SO_ERROR` option on this socket.
    ///
    /// This will retrieve the stored error in the underlying socket, clearing
    /// the field in the process. This can be useful for checking errors between
    /// calls.
    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        self.inner.take_error()
    }

    /// Moves this TCP stream into or out of nonblocking mode.
    ///
    /// On Unix this corresponds to calling fcntl, and on Windows this
    /// corresponds to calling ioctlsocket.
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.inner.set_nonblocking(nonblocking)
    }

    /// Shuts down the read, write, or both halves of this connection.
    ///
    /// This function will cause all pending and future I/O on the specified
    /// portions to return immediately with an appropriate value.
    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        self.inner.shutdown(how)
    }

    /// Receives data on the socket from the remote address to which it is
    /// connected.
    ///
    /// The [`connect`] method will connect this socket to a remote address. This
    /// method will fail if the socket is not connected.
    ///
    /// [`connect`]: #method.connect
    pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.recv(buf)
    }

    /// Receives data on the socket from the remote adress to which it is
    /// connected, without removing that data from the queue. On success,
    /// returns the number of bytes peeked.
    ///
    /// Successive calls return the same data. This is accomplished by passing
    /// `MSG_PEEK` as a flag to the underlying `recv` system call.
    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.peek(buf)
    }

    /// Receives data from the socket. On success, returns the number of bytes
    /// read and the address from whence the data came.
    pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> {
        self.inner.recv_from(buf)
    }

    /// Receives data from the socket, without removing it from the queue.
    ///
    /// Successive calls return the same data. This is accomplished by passing
    /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
    ///
    /// On success, returns the number of bytes peeked and the address from
    /// whence the data came.
    pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> {
        self.inner.peek_from(buf)
    }

    /// Sends data on the socket to a connected peer.
    ///
    /// This is typically used on TCP sockets or datagram sockets which have
    /// been connected.
    ///
    /// On success returns the number of bytes that were sent.
    pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
        self.inner.send(buf)
    }

    /// Sends data on the socket to the given address. On success, returns the
    /// number of bytes written.
    ///
    /// This is typically used on UDP or datagram-oriented sockets. On success
    /// returns the number of bytes that were sent.
    pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> {
        self.inner.send_to(buf, addr)
    }

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

    /// Gets the value of the `IP_TTL` option for this socket.
    ///
    /// For more information about this option, see [`set_ttl`][link].
    ///
    /// [link]: #method.set_ttl
    pub fn ttl(&self) -> io::Result<u32> {
        self.inner.ttl()
    }

    /// Sets the value for the `IP_TTL` option on this socket.
    ///
    /// This value sets the time-to-live field that is used in every packet sent
    /// from this socket.
    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        self.inner.set_ttl(ttl)
    }

    /// Gets the value of the `IPV6_UNICAST_HOPS` option for this socket.
    ///
    /// Specifies the hop limit for ipv6 unicast packets
    pub fn unicast_hops_v6(&self) -> io::Result<u32> {
        self.inner.unicast_hops_v6()
    }

    /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket.
    ///
    /// Specifies the hop limit for ipv6 unicast packets
    pub fn set_unicast_hops_v6(&self, ttl: u32) -> io::Result<()> {
        self.inner.set_unicast_hops_v6(ttl)
    }

    /// Gets the value of the `IPV6_V6ONLY` option for this socket.
    ///
    /// For more information about this option, see [`set_only_v6`][link].
    ///
    /// [link]: #method.set_only_v6
    pub fn only_v6(&self) -> io::Result<bool> {
        self.inner.only_v6()
    }

    /// Sets the value for the `IPV6_V6ONLY` option on this socket.
    ///
    /// If this is set to `true` then the socket is restricted to sending and
    /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications
    /// can bind the same port at the same time.
    ///
    /// If this is set to `false` then the socket can be used to send and
    /// receive packets from an IPv4-mapped IPv6 address.
    pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
        self.inner.set_only_v6(only_v6)
    }

    /// Returns the read timeout of this socket.
    ///
    /// If the timeout is `None`, then `read` calls will block indefinitely.
    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.read_timeout()
    }

    /// Sets the read timeout to the timeout specified.
    ///
    /// If the value specified is `None`, then `read` calls will block
    /// indefinitely. It is an error to pass the zero `Duration` to this
    /// method.
    pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_read_timeout(dur)
    }

    /// Returns the write timeout of this socket.
    ///
    /// If the timeout is `None`, then `write` calls will block indefinitely.
    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        self.inner.write_timeout()
    }

    /// Sets the write timeout to the timeout specified.
    ///
    /// If the value specified is `None`, then `write` calls will block
    /// indefinitely. It is an error to pass the zero `Duration` to this
    /// method.
    pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_write_timeout(dur)
    }

    /// Gets the value of the `TCP_NODELAY` option on this socket.
    ///
    /// For more information about this option, see [`set_nodelay`][link].
    ///
    /// [link]: #method.set_nodelay
    pub fn nodelay(&self) -> io::Result<bool> {
        self.inner.nodelay()
    }

    /// Sets the value of the `TCP_NODELAY` option on this socket.
    ///
    /// If set, this option disables the Nagle algorithm. This means that
    /// segments are always sent as soon as possible, even if there is only a
    /// small amount of data. When not set, data is buffered until there is a
    /// sufficient amount to send out, thereby avoiding the frequent sending of
    /// small packets.
    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
        self.inner.set_nodelay(nodelay)
    }

    /// Sets the value of the `SO_BROADCAST` option for this socket.
    ///
    /// When enabled, this socket is allowed to send packets to a broadcast
    /// address.
    pub fn broadcast(&self) -> io::Result<bool> {
        self.inner.broadcast()
    }

    /// Gets the value of the `SO_BROADCAST` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_broadcast`][link].
    ///
    /// [link]: #method.set_broadcast
    pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
        self.inner.set_broadcast(broadcast)
    }

    /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_multicast_loop_v4`][link].
    ///
    /// [link]: #method.set_multicast_loop_v4
    pub fn multicast_loop_v4(&self) -> io::Result<bool> {
        self.inner.multicast_loop_v4()
    }

    /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
    ///
    /// If enabled, multicast packets will be looped back to the local socket.
    /// Note that this may not have any affect on IPv6 sockets.
    pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
        self.inner.set_multicast_loop_v4(multicast_loop_v4)
    }

    /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_multicast_ttl_v4`][link].
    ///
    /// [link]: #method.set_multicast_ttl_v4
    pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
        self.inner.multicast_ttl_v4()
    }

    /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
    ///
    /// Indicates the time-to-live value of outgoing multicast packets for
    /// this socket. The default value is 1 which means that multicast packets
    /// don't leave the local network unless explicitly requested.
    ///
    /// Note that this may not have any affect on IPv6 sockets.
    pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
        self.inner.set_multicast_ttl_v4(multicast_ttl_v4)
    }

    /// Gets the value of the `IPV6_MULTICAST_HOPS` option for this socket
    ///
    /// For more information about this option, see
    /// [`set_multicast_hops_v6`][link].
    ///
    /// [link]: #method.set_multicast_hops_v6
    pub fn multicast_hops_v6(&self) -> io::Result<u32> {
        self.inner.multicast_hops_v6()
    }

    /// Sets the value of the `IPV6_MULTICAST_HOPS` option for this socket
    ///
    /// Indicates the number of "routers" multicast packets will transit for
    /// this socket. The default value is 1 which means that multicast packets
    /// don't leave the local network unless explicitly requested.
    pub fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()> {
        self.inner.set_multicast_hops_v6(hops)
    }

    /// Gets the value of the `IP_MULTICAST_IF` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_multicast_if_v4`][link].
    ///
    /// [link]: #method.set_multicast_if_v4
    ///
    /// Returns the interface to use for routing multicast packets.
    pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> {
        self.inner.multicast_if_v4()
    }

    /// Sets the value of the `IP_MULTICAST_IF` option for this socket.
    ///
    /// Specifies the interface to use for routing multicast packets.
    pub fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()> {
        self.inner.set_multicast_if_v4(interface)
    }

    /// Gets the value of the `IPV6_MULTICAST_IF` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_multicast_if_v6`][link].
    ///
    /// [link]: #method.set_multicast_if_v6
    ///
    /// Returns the interface to use for routing multicast packets.
    pub fn multicast_if_v6(&self) -> io::Result<u32> {
        self.inner.multicast_if_v6()
    }

    /// Sets the value of the `IPV6_MULTICAST_IF` option for this socket.
    ///
    /// Specifies the interface to use for routing multicast packets. Unlike ipv4, this
    /// is generally required in ipv6 contexts where network routing prefixes may
    /// overlap.
    pub fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()> {
        self.inner.set_multicast_if_v6(interface)
    }

    /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
    ///
    /// For more information about this option, see
    /// [`set_multicast_loop_v6`][link].
    ///
    /// [link]: #method.set_multicast_loop_v6
    pub fn multicast_loop_v6(&self) -> io::Result<bool> {
        self.inner.multicast_loop_v6()
    }

    /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
    ///
    /// Controls whether this socket sees the multicast packets it sends itself.
    /// Note that this may not have any affect on IPv4 sockets.
    pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
        self.inner.set_multicast_loop_v6(multicast_loop_v6)
    }

    /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
    ///
    /// This function specifies a new multicast group for this socket to join.
    /// The address must be a valid multicast address, and `interface` is the
    /// address of the local interface with which the system should join the
    /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
    /// interface is chosen by the system.
    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
        self.inner.join_multicast_v4(multiaddr, interface)
    }

    /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
    ///
    /// This function specifies a new multicast group for this socket to join.
    /// The address must be a valid multicast address, and `interface` is the
    /// index of the interface to join/leave (or 0 to indicate any interface).
    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
        self.inner.join_multicast_v6(multiaddr, interface)
    }

    /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
    ///
    /// For more information about this option, see
    /// [`join_multicast_v4`][link].
    ///
    /// [link]: #method.join_multicast_v4
    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
        self.inner.leave_multicast_v4(multiaddr, interface)
    }

    /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
    ///
    /// For more information about this option, see
    /// [`join_multicast_v6`][link].
    ///
    /// [link]: #method.join_multicast_v6
    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
        self.inner.leave_multicast_v6(multiaddr, interface)
    }

    /// Reads the linger duration for this socket by getting the SO_LINGER
    /// option
    pub fn linger(&self) -> io::Result<Option<Duration>> {
        self.inner.linger()
    }

    /// Sets the linger duration of this socket by setting the SO_LINGER option
    pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> {
        self.inner.set_linger(dur)
    }

    /// Check the `SO_REUSEADDR` option on this socket.
    pub fn reuse_address(&self) -> io::Result<bool> {
        self.inner.reuse_address()
    }

    /// Set value for the `SO_REUSEADDR` option on this socket.
    ///
    /// This indicates that futher calls to `bind` may allow reuse of local
    /// addresses. For IPv4 sockets this means that a socket may bind even when
    /// there's a socket already listening on this port.
    pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> {
        self.inner.set_reuse_address(reuse)
    }

    /// Gets the value of the `SO_RCVBUF` option on this socket.
    ///
    /// For more information about this option, see
    /// [`set_recv_buffer_size`][link].
    ///
    /// [link]: #method.set_recv_buffer_size
    pub fn recv_buffer_size(&self) -> io::Result<usize> {
        self.inner.recv_buffer_size()
    }

    /// Sets the value of the `SO_RCVBUF` option on this socket.
    ///
    /// Changes the size of the operating system's receive buffer associated
    /// with the socket.
    pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> {
        self.inner.set_recv_buffer_size(size)
    }

    /// Gets the value of the `SO_SNDBUF` option on this socket.
    ///
    /// For more information about this option, see [`set_send_buffer`][link].
    ///
    /// [link]: #method.set_send_buffer
    pub fn send_buffer_size(&self) -> io::Result<usize> {
        self.inner.send_buffer_size()
    }

    /// Sets the value of the `SO_SNDBUF` option on this socket.
    ///
    /// Changes the size of the operating system's send buffer associated with
    /// the socket.
    pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> {
        self.inner.set_send_buffer_size(size)
    }

    /// Returns whether keepalive messages are enabled on this socket, and if so
    /// the duration of time between them.
    ///
    /// For more information about this option, see [`set_keepalive`][link].
    ///
    /// [link]: #method.set_keepalive
    pub fn keepalive(&self) -> io::Result<Option<Duration>> {
        self.inner.keepalive()
    }

    /// Sets whether keepalive messages are enabled to be sent on this socket.
    ///
    /// On Unix, this option will set the `SO_KEEPALIVE` as well as the
    /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform).
    /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option.
    ///
    /// If `None` is specified then keepalive messages are disabled, otherwise
    /// the duration specified will be the time to remain idle before sending a
    /// TCP keepalive probe.
    ///
    /// Some platforms specify this value in seconds, so sub-second
    /// specifications may be omitted.
    pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> {
        self.inner.set_keepalive(keepalive)
    }

    /// Check the value of the `SO_REUSEPORT` option on this socket.
    ///
    /// This function is only available on Unix when the `reuseport` feature is
    /// enabled.
    #[cfg(all(unix, feature = "reuseport"))]
    pub fn reuse_port(&self) -> io::Result<bool> {
        self.inner.reuse_port()
    }

    /// Set value for the `SO_REUSEPORT` option on this socket.
    ///
    /// This indicates that futher calls to `bind` may allow reuse of local
    /// addresses. For IPv4 sockets this means that a socket may bind even when
    /// there's a socket already listening on this port.
    ///
    /// This function is only available on Unix when the `reuseport` feature is
    /// enabled.
    #[cfg(all(unix, feature = "reuseport"))]
    pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> {
        self.inner.set_reuse_port(reuse)
    }
}

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

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

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

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

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

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

impl fmt::Debug for Socket {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.inner.fmt(f)
    }
}

impl From<net::TcpStream> for Socket {
    fn from(socket: net::TcpStream) -> Socket {
        Socket {
            inner: socket.into(),
        }
    }
}

impl From<net::TcpListener> for Socket {
    fn from(socket: net::TcpListener) -> Socket {
        Socket {
            inner: socket.into(),
        }
    }
}

impl From<net::UdpSocket> for Socket {
    fn from(socket: net::UdpSocket) -> Socket {
        Socket {
            inner: socket.into(),
        }
    }
}

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

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

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

impl From<Socket> for net::TcpStream {
    fn from(socket: Socket) -> net::TcpStream {
        socket.inner.into()
    }
}

impl From<Socket> for net::TcpListener {
    fn from(socket: Socket) -> net::TcpListener {
        socket.inner.into()
    }
}

impl From<Socket> for net::UdpSocket {
    fn from(socket: Socket) -> net::UdpSocket {
        socket.inner.into()
    }
}

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

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

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

impl Domain {
    /// Domain for IPv4 communication, corresponding to `AF_INET`.
    pub fn ipv4() -> Domain {
        Domain(c::AF_INET)
    }

    /// Domain for IPv6 communication, corresponding to `AF_INET6`.
    pub fn ipv6() -> Domain {
        Domain(c::AF_INET6)
    }

    /// Domain for Unix socket communication, corresponding to `AF_UNIX`.
    ///
    /// This function is only available on Unix when the `unix` feature is
    /// activated.
    #[cfg(all(unix, feature = "unix"))]
    pub fn unix() -> Domain {
        Domain(c::AF_UNIX)
    }
}

impl From<i32> for Domain {
    fn from(a: i32) -> Domain {
        Domain(a)
    }
}

impl From<Domain> for i32 {
    fn from(a: Domain) -> i32 {
        a.0
    }
}

impl Type {
    /// Type corresponding to `SOCK_STREAM`
    ///
    /// Used for protocols such as TCP.
    pub fn stream() -> Type {
        Type(c::SOCK_STREAM)
    }

    /// Type corresponding to `SOCK_DGRAM`
    ///
    /// Used for protocols such as UDP.
    pub fn dgram() -> Type {
        Type(c::SOCK_DGRAM)
    }

    /// Type corresponding to `SOCK_SEQPACKET`
    pub fn seqpacket() -> Type {
        Type(c::SOCK_SEQPACKET)
    }

    /// Type corresponding to `SOCK_RAW`
    pub fn raw() -> Type {
        Type(c::SOCK_RAW)
    }
}

impl ::Protocol {
    /// Protocol corresponding to `ICMPv4`
    pub fn icmpv4() -> Self {
        ::Protocol(sys::IPPROTO_ICMP)
    }

    /// Protocol corresponding to `ICMPv6`
    pub fn icmpv6() -> Self {
        ::Protocol(sys::IPPROTO_ICMPV6)
    }

    /// Protocol corresponding to `TCP`
    pub fn tcp() -> Self {
        ::Protocol(sys::IPPROTO_TCP)
    }

    /// Protocol corresponding to `UDP`
    pub fn udp() -> Self {
        ::Protocol(sys::IPPROTO_UDP)
    }
}

impl From<i32> for Type {
    fn from(a: i32) -> Type {
        Type(a)
    }
}

impl From<Type> for i32 {
    fn from(a: Type) -> i32 {
        a.0
    }
}

impl From<i32> for Protocol {
    fn from(a: i32) -> Protocol {
        Protocol(a)
    }
}

impl From<Protocol> for i32 {
    fn from(a: Protocol) -> i32 {
        a.0
    }
}

#[cfg(test)]
mod test {
    use std::net::SocketAddr;

    use super::*;

    #[test]
    fn connect_timeout_unrouteable() {
        // this IP is unroutable, so connections should always time out
        let addr = "10.255.255.1:80".parse::<SocketAddr>().unwrap().into();

        let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
        match socket.connect_timeout(&addr, Duration::from_millis(250)) {
            Ok(_) => panic!("unexpected success"),
            Err(ref e) if e.kind() == io::ErrorKind::TimedOut => {}
            Err(e) => panic!("unexpected error {}", e),
        }
    }

    #[test]
    fn connect_timeout_unbound() {
        // bind and drop a socket to track down a "probably unassigned" port
        let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
        let addr = "127.0.0.1:0".parse::<SocketAddr>().unwrap().into();
        socket.bind(&addr).unwrap();
        let addr = socket.local_addr().unwrap();
        drop(socket);

        let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
        match socket.connect_timeout(&addr, Duration::from_millis(250)) {
            Ok(_) => panic!("unexpected success"),
            Err(ref e)
                if e.kind() == io::ErrorKind::ConnectionRefused
                    || e.kind() == io::ErrorKind::TimedOut => {}
            Err(e) => panic!("unexpected error {}", e),
        }
    }

    #[test]
    fn connect_timeout_valid() {
        let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
        socket
            .bind(&"127.0.0.1:0".parse::<SocketAddr>().unwrap().into())
            .unwrap();
        socket.listen(128).unwrap();

        let addr = socket.local_addr().unwrap();

        let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
        socket
            .connect_timeout(&addr, Duration::from_millis(250))
            .unwrap();
    }

    #[test]
    #[cfg(all(unix, feature = "pair", feature = "unix"))]
    fn pair() {
        let (mut a, mut b) = Socket::pair(Domain::unix(), Type::stream(), None).unwrap();
        a.write_all(b"hello world").unwrap();
        let mut buf = [0; 11];
        b.read_exact(&mut buf).unwrap();
        assert_eq!(buf, &b"hello world"[..]);
    }

    #[test]
    #[cfg(all(unix, feature = "unix"))]
    fn unix() {
        use tempdir::TempDir;

        let dir = TempDir::new("unix").unwrap();
        let addr = SockAddr::unix(dir.path().join("sock")).unwrap();

        let listener = Socket::new(Domain::unix(), Type::stream(), None).unwrap();
        listener.bind(&addr).unwrap();
        listener.listen(10).unwrap();

        let mut a = Socket::new(Domain::unix(), Type::stream(), None).unwrap();
        a.connect(&addr).unwrap();

        let mut b = listener.accept().unwrap().0;

        a.write_all(b"hello world").unwrap();
        let mut buf = [0; 11];
        b.read_exact(&mut buf).unwrap();
        assert_eq!(buf, &b"hello world"[..]);
    }

    #[test]
    fn keepalive() {
        let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
        socket.set_keepalive(Some(Duration::from_secs(7))).unwrap();
        // socket.keepalive() doesn't work on Windows #24
        #[cfg(unix)]
        assert_eq!(socket.keepalive().unwrap(), Some(Duration::from_secs(7)));
        socket.set_keepalive(None).unwrap();
        #[cfg(unix)]
        assert_eq!(socket.keepalive().unwrap(), None);
    }
}