1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 
11 use std::fmt;
12 use std::io::{self, Read, Write};
13 use std::net::{self, Ipv4Addr, Ipv6Addr, Shutdown};
14 #[cfg(all(unix, feature = "unix"))]
15 use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
16 use std::time::Duration;
17 
18 #[cfg(any(unix, target_os = "redox"))]
19 use libc as c;
20 #[cfg(windows)]
21 use winapi::shared::ws2def as c;
22 
23 use crate::sys;
24 use crate::{Domain, Protocol, SockAddr, Socket, Type};
25 
26 impl Socket {
27     /// Creates a new socket ready to be configured.
28     ///
29     /// This function corresponds to `socket(2)` and simply creates a new
30     /// socket, no other configuration is done and further functions must be
31     /// invoked to configure this socket.
new(domain: Domain, type_: Type, protocol: Option<Protocol>) -> io::Result<Socket>32     pub fn new(domain: Domain, type_: Type, protocol: Option<Protocol>) -> io::Result<Socket> {
33         let protocol = protocol.map(|p| p.0).unwrap_or(0);
34         Ok(Socket {
35             inner: sys::Socket::new(domain.0, type_.0, protocol)?,
36         })
37     }
38 
39     /// Creates a pair of sockets which are connected to each other.
40     ///
41     /// This function corresponds to `socketpair(2)`.
42     ///
43     /// This function is only available on Unix when the `pair` feature is
44     /// enabled.
45     #[cfg(all(unix, feature = "pair"))]
pair( domain: Domain, type_: Type, protocol: Option<Protocol>, ) -> io::Result<(Socket, Socket)>46     pub fn pair(
47         domain: Domain,
48         type_: Type,
49         protocol: Option<Protocol>,
50     ) -> io::Result<(Socket, Socket)> {
51         let protocol = protocol.map(|p| p.0).unwrap_or(0);
52         let sockets = sys::Socket::pair(domain.0, type_.0, protocol)?;
53         Ok((Socket { inner: sockets.0 }, Socket { inner: sockets.1 }))
54     }
55 
56     /// Consumes this `Socket`, converting it to a `TcpStream`.
into_tcp_stream(self) -> net::TcpStream57     pub fn into_tcp_stream(self) -> net::TcpStream {
58         self.into()
59     }
60 
61     /// Consumes this `Socket`, converting it to a `TcpListener`.
into_tcp_listener(self) -> net::TcpListener62     pub fn into_tcp_listener(self) -> net::TcpListener {
63         self.into()
64     }
65 
66     /// Consumes this `Socket`, converting it to a `UdpSocket`.
into_udp_socket(self) -> net::UdpSocket67     pub fn into_udp_socket(self) -> net::UdpSocket {
68         self.into()
69     }
70 
71     /// Consumes this `Socket`, converting it into a `UnixStream`.
72     ///
73     /// This function is only available on Unix when the `unix` feature is
74     /// enabled.
75     #[cfg(all(unix, feature = "unix"))]
into_unix_stream(self) -> UnixStream76     pub fn into_unix_stream(self) -> UnixStream {
77         self.into()
78     }
79 
80     /// Consumes this `Socket`, converting it into a `UnixListener`.
81     ///
82     /// This function is only available on Unix when the `unix` feature is
83     /// enabled.
84     #[cfg(all(unix, feature = "unix"))]
into_unix_listener(self) -> UnixListener85     pub fn into_unix_listener(self) -> UnixListener {
86         self.into()
87     }
88 
89     /// Consumes this `Socket`, converting it into a `UnixDatagram`.
90     ///
91     /// This function is only available on Unix when the `unix` feature is
92     /// enabled.
93     #[cfg(all(unix, feature = "unix"))]
into_unix_datagram(self) -> UnixDatagram94     pub fn into_unix_datagram(self) -> UnixDatagram {
95         self.into()
96     }
97 
98     /// Initiate a connection on this socket to the specified address.
99     ///
100     /// This function directly corresponds to the connect(2) function on Windows
101     /// and Unix.
102     ///
103     /// An error will be returned if `listen` or `connect` has already been
104     /// called on this builder.
connect(&self, addr: &SockAddr) -> io::Result<()>105     pub fn connect(&self, addr: &SockAddr) -> io::Result<()> {
106         self.inner.connect(addr)
107     }
108 
109     /// Initiate a connection on this socket to the specified address, only
110     /// only waiting for a certain period of time for the connection to be
111     /// established.
112     ///
113     /// Unlike many other methods on `Socket`, this does *not* correspond to a
114     /// single C function. It sets the socket to nonblocking mode, connects via
115     /// connect(2), and then waits for the connection to complete with poll(2)
116     /// on Unix and select on Windows. When the connection is complete, the
117     /// socket is set back to blocking mode. On Unix, this will loop over
118     /// `EINTR` errors.
119     ///
120     /// # Warnings
121     ///
122     /// The nonblocking state of the socket is overridden by this function -
123     /// it will be returned in blocking mode on success, and in an indeterminate
124     /// state on failure.
125     ///
126     /// If the connection request times out, it may still be processing in the
127     /// background - a second call to `connect` or `connect_timeout` may fail.
connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()>128     pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> {
129         self.inner.connect_timeout(addr, timeout)
130     }
131 
132     /// Binds this socket to the specified address.
133     ///
134     /// This function directly corresponds to the bind(2) function on Windows
135     /// and Unix.
bind(&self, addr: &SockAddr) -> io::Result<()>136     pub fn bind(&self, addr: &SockAddr) -> io::Result<()> {
137         self.inner.bind(addr)
138     }
139 
140     /// Mark a socket as ready to accept incoming connection requests using
141     /// accept()
142     ///
143     /// This function directly corresponds to the listen(2) function on Windows
144     /// and Unix.
145     ///
146     /// An error will be returned if `listen` or `connect` has already been
147     /// called on this builder.
listen(&self, backlog: i32) -> io::Result<()>148     pub fn listen(&self, backlog: i32) -> io::Result<()> {
149         self.inner.listen(backlog)
150     }
151 
152     /// Accept a new incoming connection from this listener.
153     ///
154     /// This function will block the calling thread until a new connection is
155     /// established. When established, the corresponding `Socket` and the
156     /// remote peer's address will be returned.
accept(&self) -> io::Result<(Socket, SockAddr)>157     pub fn accept(&self) -> io::Result<(Socket, SockAddr)> {
158         self.inner
159             .accept()
160             .map(|(socket, addr)| (Socket { inner: socket }, addr))
161     }
162 
163     /// Returns the socket address of the local half of this TCP connection.
local_addr(&self) -> io::Result<SockAddr>164     pub fn local_addr(&self) -> io::Result<SockAddr> {
165         self.inner.local_addr()
166     }
167 
168     /// Returns the socket address of the remote peer of this TCP connection.
peer_addr(&self) -> io::Result<SockAddr>169     pub fn peer_addr(&self) -> io::Result<SockAddr> {
170         self.inner.peer_addr()
171     }
172 
173     /// Creates a new independently owned handle to the underlying socket.
174     ///
175     /// The returned `TcpStream` is a reference to the same stream that this
176     /// object references. Both handles will read and write the same stream of
177     /// data, and options set on one stream will be propagated to the other
178     /// stream.
try_clone(&self) -> io::Result<Socket>179     pub fn try_clone(&self) -> io::Result<Socket> {
180         self.inner.try_clone().map(|s| Socket { inner: s })
181     }
182 
183     /// Get the value of the `SO_ERROR` option on this socket.
184     ///
185     /// This will retrieve the stored error in the underlying socket, clearing
186     /// the field in the process. This can be useful for checking errors between
187     /// calls.
take_error(&self) -> io::Result<Option<io::Error>>188     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
189         self.inner.take_error()
190     }
191 
192     /// Moves this TCP stream into or out of nonblocking mode.
193     ///
194     /// On Unix this corresponds to calling fcntl, and on Windows this
195     /// corresponds to calling ioctlsocket.
set_nonblocking(&self, nonblocking: bool) -> io::Result<()>196     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
197         self.inner.set_nonblocking(nonblocking)
198     }
199 
200     /// Shuts down the read, write, or both halves of this connection.
201     ///
202     /// This function will cause all pending and future I/O on the specified
203     /// portions to return immediately with an appropriate value.
shutdown(&self, how: Shutdown) -> io::Result<()>204     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
205         self.inner.shutdown(how)
206     }
207 
208     /// Receives data on the socket from the remote address to which it is
209     /// connected.
210     ///
211     /// The [`connect`] method will connect this socket to a remote address. This
212     /// method will fail if the socket is not connected.
213     ///
214     /// [`connect`]: #method.connect
recv(&self, buf: &mut [u8]) -> io::Result<usize>215     pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
216         self.inner.recv(buf)
217     }
218 
219     /// Receives data on the socket from the remote adress to which it is
220     /// connected, without removing that data from the queue. On success,
221     /// returns the number of bytes peeked.
222     ///
223     /// Successive calls return the same data. This is accomplished by passing
224     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
peek(&self, buf: &mut [u8]) -> io::Result<usize>225     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
226         self.inner.peek(buf)
227     }
228 
229     /// Receives data from the socket. On success, returns the number of bytes
230     /// read and the address from whence the data came.
recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)>231     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> {
232         self.inner.recv_from(buf)
233     }
234 
235     /// Receives data from the socket, without removing it from the queue.
236     ///
237     /// Successive calls return the same data. This is accomplished by passing
238     /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
239     ///
240     /// On success, returns the number of bytes peeked and the address from
241     /// whence the data came.
peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)>242     pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> {
243         self.inner.peek_from(buf)
244     }
245 
246     /// Sends data on the socket to a connected peer.
247     ///
248     /// This is typically used on TCP sockets or datagram sockets which have
249     /// been connected.
250     ///
251     /// On success returns the number of bytes that were sent.
send(&self, buf: &[u8]) -> io::Result<usize>252     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
253         self.inner.send(buf)
254     }
255 
256     /// Sends data on the socket to the given address. On success, returns the
257     /// number of bytes written.
258     ///
259     /// This is typically used on UDP or datagram-oriented sockets. On success
260     /// returns the number of bytes that were sent.
send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize>261     pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> {
262         self.inner.send_to(buf, addr)
263     }
264 
265     // ================================================
266 
267     /// Gets the value of the `IP_TTL` option for this socket.
268     ///
269     /// For more information about this option, see [`set_ttl`][link].
270     ///
271     /// [link]: #method.set_ttl
ttl(&self) -> io::Result<u32>272     pub fn ttl(&self) -> io::Result<u32> {
273         self.inner.ttl()
274     }
275 
276     /// Sets the value for the `IP_TTL` option on this socket.
277     ///
278     /// This value sets the time-to-live field that is used in every packet sent
279     /// from this socket.
set_ttl(&self, ttl: u32) -> io::Result<()>280     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
281         self.inner.set_ttl(ttl)
282     }
283 
284     /// Gets the value of the `IPV6_UNICAST_HOPS` option for this socket.
285     ///
286     /// Specifies the hop limit for ipv6 unicast packets
unicast_hops_v6(&self) -> io::Result<u32>287     pub fn unicast_hops_v6(&self) -> io::Result<u32> {
288         self.inner.unicast_hops_v6()
289     }
290 
291     /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket.
292     ///
293     /// Specifies the hop limit for ipv6 unicast packets
set_unicast_hops_v6(&self, ttl: u32) -> io::Result<()>294     pub fn set_unicast_hops_v6(&self, ttl: u32) -> io::Result<()> {
295         self.inner.set_unicast_hops_v6(ttl)
296     }
297 
298     /// Gets the value of the `IPV6_V6ONLY` option for this socket.
299     ///
300     /// For more information about this option, see [`set_only_v6`][link].
301     ///
302     /// [link]: #method.set_only_v6
only_v6(&self) -> io::Result<bool>303     pub fn only_v6(&self) -> io::Result<bool> {
304         self.inner.only_v6()
305     }
306 
307     /// Sets the value for the `IPV6_V6ONLY` option on this socket.
308     ///
309     /// If this is set to `true` then the socket is restricted to sending and
310     /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications
311     /// can bind the same port at the same time.
312     ///
313     /// If this is set to `false` then the socket can be used to send and
314     /// receive packets from an IPv4-mapped IPv6 address.
set_only_v6(&self, only_v6: bool) -> io::Result<()>315     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
316         self.inner.set_only_v6(only_v6)
317     }
318 
319     /// Returns the read timeout of this socket.
320     ///
321     /// If the timeout is `None`, then `read` calls will block indefinitely.
read_timeout(&self) -> io::Result<Option<Duration>>322     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
323         self.inner.read_timeout()
324     }
325 
326     /// Sets the read timeout to the timeout specified.
327     ///
328     /// If the value specified is `None`, then `read` calls will block
329     /// indefinitely. It is an error to pass the zero `Duration` to this
330     /// method.
set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()>331     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
332         self.inner.set_read_timeout(dur)
333     }
334 
335     /// Returns the write timeout of this socket.
336     ///
337     /// If the timeout is `None`, then `write` calls will block indefinitely.
write_timeout(&self) -> io::Result<Option<Duration>>338     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
339         self.inner.write_timeout()
340     }
341 
342     /// Sets the write timeout to the timeout specified.
343     ///
344     /// If the value specified is `None`, then `write` calls will block
345     /// indefinitely. It is an error to pass the zero `Duration` to this
346     /// method.
set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()>347     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
348         self.inner.set_write_timeout(dur)
349     }
350 
351     /// Gets the value of the `TCP_NODELAY` option on this socket.
352     ///
353     /// For more information about this option, see [`set_nodelay`][link].
354     ///
355     /// [link]: #method.set_nodelay
nodelay(&self) -> io::Result<bool>356     pub fn nodelay(&self) -> io::Result<bool> {
357         self.inner.nodelay()
358     }
359 
360     /// Sets the value of the `TCP_NODELAY` option on this socket.
361     ///
362     /// If set, this option disables the Nagle algorithm. This means that
363     /// segments are always sent as soon as possible, even if there is only a
364     /// small amount of data. When not set, data is buffered until there is a
365     /// sufficient amount to send out, thereby avoiding the frequent sending of
366     /// small packets.
set_nodelay(&self, nodelay: bool) -> io::Result<()>367     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
368         self.inner.set_nodelay(nodelay)
369     }
370 
371     /// Sets the value of the `SO_BROADCAST` option for this socket.
372     ///
373     /// When enabled, this socket is allowed to send packets to a broadcast
374     /// address.
broadcast(&self) -> io::Result<bool>375     pub fn broadcast(&self) -> io::Result<bool> {
376         self.inner.broadcast()
377     }
378 
379     /// Gets the value of the `SO_BROADCAST` option for this socket.
380     ///
381     /// For more information about this option, see
382     /// [`set_broadcast`][link].
383     ///
384     /// [link]: #method.set_broadcast
set_broadcast(&self, broadcast: bool) -> io::Result<()>385     pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
386         self.inner.set_broadcast(broadcast)
387     }
388 
389     /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
390     ///
391     /// For more information about this option, see
392     /// [`set_multicast_loop_v4`][link].
393     ///
394     /// [link]: #method.set_multicast_loop_v4
multicast_loop_v4(&self) -> io::Result<bool>395     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
396         self.inner.multicast_loop_v4()
397     }
398 
399     /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
400     ///
401     /// If enabled, multicast packets will be looped back to the local socket.
402     /// Note that this may not have any affect on IPv6 sockets.
set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()>403     pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
404         self.inner.set_multicast_loop_v4(multicast_loop_v4)
405     }
406 
407     /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
408     ///
409     /// For more information about this option, see
410     /// [`set_multicast_ttl_v4`][link].
411     ///
412     /// [link]: #method.set_multicast_ttl_v4
multicast_ttl_v4(&self) -> io::Result<u32>413     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
414         self.inner.multicast_ttl_v4()
415     }
416 
417     /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
418     ///
419     /// Indicates the time-to-live value of outgoing multicast packets for
420     /// this socket. The default value is 1 which means that multicast packets
421     /// don't leave the local network unless explicitly requested.
422     ///
423     /// Note that this may not have any affect on IPv6 sockets.
set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()>424     pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
425         self.inner.set_multicast_ttl_v4(multicast_ttl_v4)
426     }
427 
428     /// Gets the value of the `IPV6_MULTICAST_HOPS` option for this socket
429     ///
430     /// For more information about this option, see
431     /// [`set_multicast_hops_v6`][link].
432     ///
433     /// [link]: #method.set_multicast_hops_v6
multicast_hops_v6(&self) -> io::Result<u32>434     pub fn multicast_hops_v6(&self) -> io::Result<u32> {
435         self.inner.multicast_hops_v6()
436     }
437 
438     /// Sets the value of the `IPV6_MULTICAST_HOPS` option for this socket
439     ///
440     /// Indicates the number of "routers" multicast packets will transit for
441     /// this socket. The default value is 1 which means that multicast packets
442     /// don't leave the local network unless explicitly requested.
set_multicast_hops_v6(&self, hops: u32) -> io::Result<()>443     pub fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()> {
444         self.inner.set_multicast_hops_v6(hops)
445     }
446 
447     /// Gets the value of the `IP_MULTICAST_IF` option for this socket.
448     ///
449     /// For more information about this option, see
450     /// [`set_multicast_if_v4`][link].
451     ///
452     /// [link]: #method.set_multicast_if_v4
453     ///
454     /// Returns the interface to use for routing multicast packets.
multicast_if_v4(&self) -> io::Result<Ipv4Addr>455     pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> {
456         self.inner.multicast_if_v4()
457     }
458 
459     /// Sets the value of the `IP_MULTICAST_IF` option for this socket.
460     ///
461     /// Specifies the interface to use for routing multicast packets.
set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()>462     pub fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()> {
463         self.inner.set_multicast_if_v4(interface)
464     }
465 
466     /// Gets the value of the `IPV6_MULTICAST_IF` option for this socket.
467     ///
468     /// For more information about this option, see
469     /// [`set_multicast_if_v6`][link].
470     ///
471     /// [link]: #method.set_multicast_if_v6
472     ///
473     /// Returns the interface to use for routing multicast packets.
multicast_if_v6(&self) -> io::Result<u32>474     pub fn multicast_if_v6(&self) -> io::Result<u32> {
475         self.inner.multicast_if_v6()
476     }
477 
478     /// Sets the value of the `IPV6_MULTICAST_IF` option for this socket.
479     ///
480     /// Specifies the interface to use for routing multicast packets. Unlike ipv4, this
481     /// is generally required in ipv6 contexts where network routing prefixes may
482     /// overlap.
set_multicast_if_v6(&self, interface: u32) -> io::Result<()>483     pub fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()> {
484         self.inner.set_multicast_if_v6(interface)
485     }
486 
487     /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
488     ///
489     /// For more information about this option, see
490     /// [`set_multicast_loop_v6`][link].
491     ///
492     /// [link]: #method.set_multicast_loop_v6
multicast_loop_v6(&self) -> io::Result<bool>493     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
494         self.inner.multicast_loop_v6()
495     }
496 
497     /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
498     ///
499     /// Controls whether this socket sees the multicast packets it sends itself.
500     /// Note that this may not have any affect on IPv4 sockets.
set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()>501     pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
502         self.inner.set_multicast_loop_v6(multicast_loop_v6)
503     }
504 
505     /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
506     ///
507     /// This function specifies a new multicast group for this socket to join.
508     /// The address must be a valid multicast address, and `interface` is the
509     /// address of the local interface with which the system should join the
510     /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
511     /// interface is chosen by the system.
join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>512     pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
513         self.inner.join_multicast_v4(multiaddr, interface)
514     }
515 
516     /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
517     ///
518     /// This function specifies a new multicast group for this socket to join.
519     /// The address must be a valid multicast address, and `interface` is the
520     /// index of the interface to join/leave (or 0 to indicate any interface).
join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>521     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
522         self.inner.join_multicast_v6(multiaddr, interface)
523     }
524 
525     /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
526     ///
527     /// For more information about this option, see
528     /// [`join_multicast_v4`][link].
529     ///
530     /// [link]: #method.join_multicast_v4
leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>531     pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
532         self.inner.leave_multicast_v4(multiaddr, interface)
533     }
534 
535     /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
536     ///
537     /// For more information about this option, see
538     /// [`join_multicast_v6`][link].
539     ///
540     /// [link]: #method.join_multicast_v6
leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>541     pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
542         self.inner.leave_multicast_v6(multiaddr, interface)
543     }
544 
545     /// Reads the linger duration for this socket by getting the SO_LINGER
546     /// option
linger(&self) -> io::Result<Option<Duration>>547     pub fn linger(&self) -> io::Result<Option<Duration>> {
548         self.inner.linger()
549     }
550 
551     /// Sets the linger duration of this socket by setting the SO_LINGER option
set_linger(&self, dur: Option<Duration>) -> io::Result<()>552     pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> {
553         self.inner.set_linger(dur)
554     }
555 
556     /// Check the `SO_REUSEADDR` option on this socket.
reuse_address(&self) -> io::Result<bool>557     pub fn reuse_address(&self) -> io::Result<bool> {
558         self.inner.reuse_address()
559     }
560 
561     /// Set value for the `SO_REUSEADDR` option on this socket.
562     ///
563     /// This indicates that futher calls to `bind` may allow reuse of local
564     /// addresses. For IPv4 sockets this means that a socket may bind even when
565     /// there's a socket already listening on this port.
set_reuse_address(&self, reuse: bool) -> io::Result<()>566     pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> {
567         self.inner.set_reuse_address(reuse)
568     }
569 
570     /// Gets the value of the `SO_RCVBUF` option on this socket.
571     ///
572     /// For more information about this option, see
573     /// [`set_recv_buffer_size`][link].
574     ///
575     /// [link]: #method.set_recv_buffer_size
recv_buffer_size(&self) -> io::Result<usize>576     pub fn recv_buffer_size(&self) -> io::Result<usize> {
577         self.inner.recv_buffer_size()
578     }
579 
580     /// Sets the value of the `SO_RCVBUF` option on this socket.
581     ///
582     /// Changes the size of the operating system's receive buffer associated
583     /// with the socket.
set_recv_buffer_size(&self, size: usize) -> io::Result<()>584     pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> {
585         self.inner.set_recv_buffer_size(size)
586     }
587 
588     /// Gets the value of the `SO_SNDBUF` option on this socket.
589     ///
590     /// For more information about this option, see [`set_send_buffer`][link].
591     ///
592     /// [link]: #method.set_send_buffer
send_buffer_size(&self) -> io::Result<usize>593     pub fn send_buffer_size(&self) -> io::Result<usize> {
594         self.inner.send_buffer_size()
595     }
596 
597     /// Sets the value of the `SO_SNDBUF` option on this socket.
598     ///
599     /// Changes the size of the operating system's send buffer associated with
600     /// the socket.
set_send_buffer_size(&self, size: usize) -> io::Result<()>601     pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> {
602         self.inner.set_send_buffer_size(size)
603     }
604 
605     /// Returns whether keepalive messages are enabled on this socket, and if so
606     /// the duration of time between them.
607     ///
608     /// For more information about this option, see [`set_keepalive`][link].
609     ///
610     /// [link]: #method.set_keepalive
keepalive(&self) -> io::Result<Option<Duration>>611     pub fn keepalive(&self) -> io::Result<Option<Duration>> {
612         self.inner.keepalive()
613     }
614 
615     /// Sets whether keepalive messages are enabled to be sent on this socket.
616     ///
617     /// On Unix, this option will set the `SO_KEEPALIVE` as well as the
618     /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform).
619     /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option.
620     ///
621     /// If `None` is specified then keepalive messages are disabled, otherwise
622     /// the duration specified will be the time to remain idle before sending a
623     /// TCP keepalive probe.
624     ///
625     /// Some platforms specify this value in seconds, so sub-second
626     /// specifications may be omitted.
set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()>627     pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> {
628         self.inner.set_keepalive(keepalive)
629     }
630 
631     /// Check the value of the `SO_REUSEPORT` option on this socket.
632     ///
633     /// This function is only available on Unix when the `reuseport` feature is
634     /// enabled.
635     #[cfg(all(unix, not(target_os = "solaris"), feature = "reuseport"))]
reuse_port(&self) -> io::Result<bool>636     pub fn reuse_port(&self) -> io::Result<bool> {
637         self.inner.reuse_port()
638     }
639 
640     /// Set value for the `SO_REUSEPORT` option on this socket.
641     ///
642     /// This indicates that further calls to `bind` may allow reuse of local
643     /// addresses. For IPv4 sockets this means that a socket may bind even when
644     /// there's a socket already listening on this port.
645     ///
646     /// This function is only available on Unix when the `reuseport` feature is
647     /// enabled.
648     #[cfg(all(unix, not(target_os = "solaris"), feature = "reuseport"))]
set_reuse_port(&self, reuse: bool) -> io::Result<()>649     pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> {
650         self.inner.set_reuse_port(reuse)
651     }
652 }
653 
654 impl Read for Socket {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>655     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
656         self.inner.read(buf)
657     }
658 }
659 
660 impl<'a> Read for &'a Socket {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>661     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
662         (&self.inner).read(buf)
663     }
664 }
665 
666 impl Write for Socket {
write(&mut self, buf: &[u8]) -> io::Result<usize>667     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
668         self.inner.write(buf)
669     }
670 
flush(&mut self) -> io::Result<()>671     fn flush(&mut self) -> io::Result<()> {
672         self.inner.flush()
673     }
674 }
675 
676 impl<'a> Write for &'a Socket {
write(&mut self, buf: &[u8]) -> io::Result<usize>677     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
678         (&self.inner).write(buf)
679     }
680 
flush(&mut self) -> io::Result<()>681     fn flush(&mut self) -> io::Result<()> {
682         (&self.inner).flush()
683     }
684 }
685 
686 impl fmt::Debug for Socket {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result687     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
688         self.inner.fmt(f)
689     }
690 }
691 
692 impl From<net::TcpStream> for Socket {
from(socket: net::TcpStream) -> Socket693     fn from(socket: net::TcpStream) -> Socket {
694         Socket {
695             inner: socket.into(),
696         }
697     }
698 }
699 
700 impl From<net::TcpListener> for Socket {
from(socket: net::TcpListener) -> Socket701     fn from(socket: net::TcpListener) -> Socket {
702         Socket {
703             inner: socket.into(),
704         }
705     }
706 }
707 
708 impl From<net::UdpSocket> for Socket {
from(socket: net::UdpSocket) -> Socket709     fn from(socket: net::UdpSocket) -> Socket {
710         Socket {
711             inner: socket.into(),
712         }
713     }
714 }
715 
716 #[cfg(all(unix, feature = "unix"))]
717 impl From<UnixStream> for Socket {
from(socket: UnixStream) -> Socket718     fn from(socket: UnixStream) -> Socket {
719         Socket {
720             inner: socket.into(),
721         }
722     }
723 }
724 
725 #[cfg(all(unix, feature = "unix"))]
726 impl From<UnixListener> for Socket {
from(socket: UnixListener) -> Socket727     fn from(socket: UnixListener) -> Socket {
728         Socket {
729             inner: socket.into(),
730         }
731     }
732 }
733 
734 #[cfg(all(unix, feature = "unix"))]
735 impl From<UnixDatagram> for Socket {
from(socket: UnixDatagram) -> Socket736     fn from(socket: UnixDatagram) -> Socket {
737         Socket {
738             inner: socket.into(),
739         }
740     }
741 }
742 
743 impl From<Socket> for net::TcpStream {
from(socket: Socket) -> net::TcpStream744     fn from(socket: Socket) -> net::TcpStream {
745         socket.inner.into()
746     }
747 }
748 
749 impl From<Socket> for net::TcpListener {
from(socket: Socket) -> net::TcpListener750     fn from(socket: Socket) -> net::TcpListener {
751         socket.inner.into()
752     }
753 }
754 
755 impl From<Socket> for net::UdpSocket {
from(socket: Socket) -> net::UdpSocket756     fn from(socket: Socket) -> net::UdpSocket {
757         socket.inner.into()
758     }
759 }
760 
761 #[cfg(all(unix, feature = "unix"))]
762 impl From<Socket> for UnixStream {
from(socket: Socket) -> UnixStream763     fn from(socket: Socket) -> UnixStream {
764         socket.inner.into()
765     }
766 }
767 
768 #[cfg(all(unix, feature = "unix"))]
769 impl From<Socket> for UnixListener {
from(socket: Socket) -> UnixListener770     fn from(socket: Socket) -> UnixListener {
771         socket.inner.into()
772     }
773 }
774 
775 #[cfg(all(unix, feature = "unix"))]
776 impl From<Socket> for UnixDatagram {
from(socket: Socket) -> UnixDatagram777     fn from(socket: Socket) -> UnixDatagram {
778         socket.inner.into()
779     }
780 }
781 
782 impl Domain {
783     /// Domain for IPv4 communication, corresponding to `AF_INET`.
ipv4() -> Domain784     pub fn ipv4() -> Domain {
785         Domain(c::AF_INET)
786     }
787 
788     /// Domain for IPv6 communication, corresponding to `AF_INET6`.
ipv6() -> Domain789     pub fn ipv6() -> Domain {
790         Domain(c::AF_INET6)
791     }
792 
793     /// Domain for Unix socket communication, corresponding to `AF_UNIX`.
794     ///
795     /// This function is only available on Unix when the `unix` feature is
796     /// activated.
797     #[cfg(all(unix, feature = "unix"))]
unix() -> Domain798     pub fn unix() -> Domain {
799         Domain(c::AF_UNIX)
800     }
801 }
802 
803 impl From<i32> for Domain {
from(a: i32) -> Domain804     fn from(a: i32) -> Domain {
805         Domain(a)
806     }
807 }
808 
809 impl From<Domain> for i32 {
from(a: Domain) -> i32810     fn from(a: Domain) -> i32 {
811         a.0
812     }
813 }
814 
815 impl Type {
816     /// Type corresponding to `SOCK_STREAM`
817     ///
818     /// Used for protocols such as TCP.
stream() -> Type819     pub fn stream() -> Type {
820         Type(c::SOCK_STREAM)
821     }
822 
823     /// Type corresponding to `SOCK_DGRAM`
824     ///
825     /// Used for protocols such as UDP.
dgram() -> Type826     pub fn dgram() -> Type {
827         Type(c::SOCK_DGRAM)
828     }
829 
830     /// Type corresponding to `SOCK_SEQPACKET`
seqpacket() -> Type831     pub fn seqpacket() -> Type {
832         Type(sys::SOCK_SEQPACKET)
833     }
834 
835     /// Type corresponding to `SOCK_RAW`
raw() -> Type836     pub fn raw() -> Type {
837         Type(sys::SOCK_RAW)
838     }
839 }
840 
841 impl crate::Protocol {
842     /// Protocol corresponding to `ICMPv4`
icmpv4() -> Self843     pub fn icmpv4() -> Self {
844         crate::Protocol(sys::IPPROTO_ICMP)
845     }
846 
847     /// Protocol corresponding to `ICMPv6`
icmpv6() -> Self848     pub fn icmpv6() -> Self {
849         crate::Protocol(sys::IPPROTO_ICMPV6)
850     }
851 
852     /// Protocol corresponding to `TCP`
tcp() -> Self853     pub fn tcp() -> Self {
854         crate::Protocol(sys::IPPROTO_TCP)
855     }
856 
857     /// Protocol corresponding to `UDP`
udp() -> Self858     pub fn udp() -> Self {
859         crate::Protocol(sys::IPPROTO_UDP)
860     }
861 }
862 
863 impl From<i32> for Type {
from(a: i32) -> Type864     fn from(a: i32) -> Type {
865         Type(a)
866     }
867 }
868 
869 impl From<Type> for i32 {
from(a: Type) -> i32870     fn from(a: Type) -> i32 {
871         a.0
872     }
873 }
874 
875 impl From<i32> for Protocol {
from(a: i32) -> Protocol876     fn from(a: i32) -> Protocol {
877         Protocol(a)
878     }
879 }
880 
881 impl From<Protocol> for i32 {
from(a: Protocol) -> i32882     fn from(a: Protocol) -> i32 {
883         a.0
884     }
885 }
886 
887 #[cfg(test)]
888 mod test {
889     use std::net::SocketAddr;
890 
891     use super::*;
892 
893     #[test]
connect_timeout_unrouteable()894     fn connect_timeout_unrouteable() {
895         // this IP is unroutable, so connections should always time out
896         let addr = "10.255.255.1:80".parse::<SocketAddr>().unwrap().into();
897 
898         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
899         match socket.connect_timeout(&addr, Duration::from_millis(250)) {
900             Ok(_) => panic!("unexpected success"),
901             Err(ref e) if e.kind() == io::ErrorKind::TimedOut => {}
902             Err(e) => panic!("unexpected error {}", e),
903         }
904     }
905 
906     #[test]
connect_timeout_unbound()907     fn connect_timeout_unbound() {
908         // bind and drop a socket to track down a "probably unassigned" port
909         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
910         let addr = "127.0.0.1:0".parse::<SocketAddr>().unwrap().into();
911         socket.bind(&addr).unwrap();
912         let addr = socket.local_addr().unwrap();
913         drop(socket);
914 
915         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
916         match socket.connect_timeout(&addr, Duration::from_millis(250)) {
917             Ok(_) => panic!("unexpected success"),
918             Err(ref e)
919                 if e.kind() == io::ErrorKind::ConnectionRefused
920                     || e.kind() == io::ErrorKind::TimedOut => {}
921             Err(e) => panic!("unexpected error {}", e),
922         }
923     }
924 
925     #[test]
connect_timeout_valid()926     fn connect_timeout_valid() {
927         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
928         socket
929             .bind(&"127.0.0.1:0".parse::<SocketAddr>().unwrap().into())
930             .unwrap();
931         socket.listen(128).unwrap();
932 
933         let addr = socket.local_addr().unwrap();
934 
935         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
936         socket
937             .connect_timeout(&addr, Duration::from_millis(250))
938             .unwrap();
939     }
940 
941     #[test]
942     #[cfg(all(unix, feature = "pair", feature = "unix"))]
pair()943     fn pair() {
944         let (mut a, mut b) = Socket::pair(Domain::unix(), Type::stream(), None).unwrap();
945         a.write_all(b"hello world").unwrap();
946         let mut buf = [0; 11];
947         b.read_exact(&mut buf).unwrap();
948         assert_eq!(buf, &b"hello world"[..]);
949     }
950 
951     #[test]
952     #[cfg(all(unix, feature = "unix"))]
unix()953     fn unix() {
954         use tempdir::TempDir;
955 
956         let dir = TempDir::new("unix").unwrap();
957         let addr = SockAddr::unix(dir.path().join("sock")).unwrap();
958 
959         let listener = Socket::new(Domain::unix(), Type::stream(), None).unwrap();
960         listener.bind(&addr).unwrap();
961         listener.listen(10).unwrap();
962 
963         let mut a = Socket::new(Domain::unix(), Type::stream(), None).unwrap();
964         a.connect(&addr).unwrap();
965 
966         let mut b = listener.accept().unwrap().0;
967 
968         a.write_all(b"hello world").unwrap();
969         let mut buf = [0; 11];
970         b.read_exact(&mut buf).unwrap();
971         assert_eq!(buf, &b"hello world"[..]);
972     }
973 
974     #[test]
keepalive()975     fn keepalive() {
976         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
977         socket.set_keepalive(Some(Duration::from_secs(7))).unwrap();
978         // socket.keepalive() doesn't work on Windows #24
979         #[cfg(unix)]
980         assert_eq!(socket.keepalive().unwrap(), Some(Duration::from_secs(7)));
981         socket.set_keepalive(None).unwrap();
982         #[cfg(unix)]
983         assert_eq!(socket.keepalive().unwrap(), None);
984     }
985 
986     #[test]
nodelay()987     fn nodelay() {
988         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
989 
990         assert!(socket.set_nodelay(true).is_ok());
991 
992         let result = socket.nodelay();
993 
994         assert!(result.is_ok());
995         assert!(result.unwrap());
996     }
997 }
998