]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/udp.rs
Incorporate a stray test
[rust.git] / src / libstd / net / udp.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use fmt;
12 use io::{self, Error, ErrorKind};
13 use net::{ToSocketAddrs, SocketAddr, Ipv4Addr, Ipv6Addr};
14 use sys_common::net as net_imp;
15 use sys_common::{AsInner, FromInner, IntoInner};
16 use time::Duration;
17
18 /// A UDP socket.
19 ///
20 /// After creating a `UdpSocket` by [`bind`]ing it to a socket address, data can be
21 /// [sent to] and [received from] any other socket address.
22 ///
23 /// Although UDP is a connectionless protocol, this implementation provides an interface
24 /// to set an address where data should be sent and received from. After setting a remote
25 /// address with [`connect`], data can be sent to and received from that address with
26 /// [`send`] and [`recv`].
27 ///
28 /// As stated in the User Datagram Protocol's specification in [IETF RFC 768], UDP is
29 /// an unordered, unreliable protocol; refer to [`TcpListener`] and [`TcpStream`] for TCP
30 /// primitives.
31 ///
32 /// [`bind`]: #method.bind
33 /// [`connect`]: #method.connect
34 /// [IETF RFC 768]: https://tools.ietf.org/html/rfc768
35 /// [`recv`]: #method.recv
36 /// [received from]: #method.recv_from
37 /// [`send`]: #method.send
38 /// [sent to]: #method.send_to
39 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
40 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
41 ///
42 /// # Examples
43 ///
44 /// ```no_run
45 /// use std::net::UdpSocket;
46 ///
47 /// fn main() -> std::io::Result<()> {
48 ///     {
49 ///         let mut socket = UdpSocket::bind("127.0.0.1:34254")?;
50 ///
51 ///         // Receives a single datagram message on the socket. If `buf` is too small to hold
52 ///         // the message, it will be cut off.
53 ///         let mut buf = [0; 10];
54 ///         let (amt, src) = socket.recv_from(&mut buf)?;
55 ///
56 ///         // Redeclare `buf` as slice of the received data and send reverse data back to origin.
57 ///         let buf = &mut buf[..amt];
58 ///         buf.reverse();
59 ///         socket.send_to(buf, &src)?;
60 ///     } // the socket is closed here
61 ///     Ok(())
62 /// }
63 /// ```
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub struct UdpSocket(net_imp::UdpSocket);
66
67 impl UdpSocket {
68     /// Creates a UDP socket from the given address.
69     ///
70     /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
71     /// its documentation for concrete examples.
72     ///
73     /// If `addr` yields multiple addresses, `bind` will be attempted with
74     /// each of the addresses until one succeeds and returns the socket. If none
75     /// of the addresses succeed in creating a socket, the error returned from
76     /// the last attempt (the last address) is returned.
77     ///
78     /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
79     ///
80     /// # Examples
81     ///
82     /// Create a UDP socket bound to `127.0.0.1:3400`:
83     ///
84     /// ```no_run
85     /// use std::net::UdpSocket;
86     ///
87     /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
88     /// ```
89     ///
90     /// Create a UDP socket bound to `127.0.0.1:3400`. If the socket cannot be
91     /// bound to that address, create a UDP socket bound to `127.0.0.1:3401`:
92     ///
93     /// ```no_run
94     /// use std::net::{SocketAddr, UdpSocket};
95     ///
96     /// let addrs = [
97     ///     SocketAddr::from(([127, 0, 0, 1], 3400)),
98     ///     SocketAddr::from(([127, 0, 0, 1], 3401)),
99     /// ];
100     /// let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address");
101     /// ```
102     #[stable(feature = "rust1", since = "1.0.0")]
103     pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
104         super::each_addr(addr, net_imp::UdpSocket::bind).map(UdpSocket)
105     }
106
107     /// Receives a single datagram message on the socket. On success, returns the number
108     /// of bytes read and the origin.
109     ///
110     /// The function must be called with valid byte array `buf` of sufficient size to
111     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
112     /// excess bytes may be discarded.
113     ///
114     /// # Examples
115     ///
116     /// ```no_run
117     /// use std::net::UdpSocket;
118     ///
119     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
120     /// let mut buf = [0; 10];
121     /// let (number_of_bytes, src_addr) = socket.recv_from(&mut buf)
122     ///                                         .expect("Didn't receive data");
123     /// let filled_buf = &mut buf[..number_of_bytes];
124     /// ```
125     #[stable(feature = "rust1", since = "1.0.0")]
126     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
127         self.0.recv_from(buf)
128     }
129
130     /// Receives a single datagram message on the socket, without removing it from the
131     /// queue. On success, returns the number of bytes read and the origin.
132     ///
133     /// The function must be called with valid byte array `buf` of sufficient size to
134     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
135     /// excess bytes may be discarded.
136     ///
137     /// Successive calls return the same data. This is accomplished by passing
138     /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
139     ///
140     /// Do not use this function to implement busy waiting, instead use `libc::poll` to
141     /// synchronize IO events on one or more sockets.
142     ///
143     /// # Examples
144     ///
145     /// ```no_run
146     /// use std::net::UdpSocket;
147     ///
148     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
149     /// let mut buf = [0; 10];
150     /// let (number_of_bytes, src_addr) = socket.peek_from(&mut buf)
151     ///                                         .expect("Didn't receive data");
152     /// let filled_buf = &mut buf[..number_of_bytes];
153     /// ```
154     #[stable(feature = "peek", since = "1.18.0")]
155     pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
156         self.0.peek_from(buf)
157     }
158
159     /// Sends data on the socket to the given address. On success, returns the
160     /// number of bytes written.
161     ///
162     /// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
163     /// documentation for concrete examples.
164     ///
165     /// It is possible for `addr` to yield multiple addresses, but `send_to`
166     /// will only send data to the first address yielded by `addr`.
167     ///
168     /// This will return an error when the IP version of the local socket
169     /// does not match that returned from [`ToSocketAddrs`].
170     ///
171     /// See <https://github.com/rust-lang/rust/issues/34202> for more details.
172     ///
173     /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
174     ///
175     /// # Examples
176     ///
177     /// ```no_run
178     /// use std::net::UdpSocket;
179     ///
180     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
181     /// socket.send_to(&[0; 10], "127.0.0.1:4242").expect("couldn't send data");
182     /// ```
183     #[stable(feature = "rust1", since = "1.0.0")]
184     pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
185                                      -> io::Result<usize> {
186         match addr.to_socket_addrs()?.next() {
187             Some(addr) => self.0.send_to(buf, &addr),
188             None => Err(Error::new(ErrorKind::InvalidInput,
189                                    "no addresses to send data to")),
190         }
191     }
192
193     /// Returns the socket address that this socket was created from.
194     ///
195     /// # Examples
196     ///
197     /// ```no_run
198     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
199     ///
200     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
201     /// assert_eq!(socket.local_addr().unwrap(),
202     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)));
203     /// ```
204     #[stable(feature = "rust1", since = "1.0.0")]
205     pub fn local_addr(&self) -> io::Result<SocketAddr> {
206         self.0.socket_addr()
207     }
208
209     /// Creates a new independently owned handle to the underlying socket.
210     ///
211     /// The returned `UdpSocket` is a reference to the same socket that this
212     /// object references. Both handles will read and write the same port, and
213     /// options set on one socket will be propagated to the other.
214     ///
215     /// # Examples
216     ///
217     /// ```no_run
218     /// use std::net::UdpSocket;
219     ///
220     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
221     /// let socket_clone = socket.try_clone().expect("couldn't clone the socket");
222     /// ```
223     #[stable(feature = "rust1", since = "1.0.0")]
224     pub fn try_clone(&self) -> io::Result<UdpSocket> {
225         self.0.duplicate().map(UdpSocket)
226     }
227
228     /// Sets the read timeout to the timeout specified.
229     ///
230     /// If the value specified is [`None`], then [`read`] calls will block
231     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
232     /// passed to this method.
233     ///
234     /// # Platform-specific behavior
235     ///
236     /// Platforms may return a different error code whenever a read times out as
237     /// a result of setting this option. For example Unix typically returns an
238     /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
239     ///
240     /// [`None`]: ../../std/option/enum.Option.html#variant.None
241     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
242     /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
243     /// [`Duration`]: ../../std/time/struct.Duration.html
244     /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
245     /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
246     ///
247     /// # Examples
248     ///
249     /// ```no_run
250     /// use std::net::UdpSocket;
251     ///
252     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
253     /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
254     /// ```
255     ///
256     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
257     /// method:
258     ///
259     /// ```no_run
260     /// use std::io;
261     /// use std::net::UdpSocket;
262     /// use std::time::Duration;
263     ///
264     /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
265     /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
266     /// let err = result.unwrap_err();
267     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
268     /// ```
269     #[stable(feature = "socket_timeout", since = "1.4.0")]
270     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
271         self.0.set_read_timeout(dur)
272     }
273
274     /// Sets the write timeout to the timeout specified.
275     ///
276     /// If the value specified is [`None`], then [`write`] calls will block
277     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
278     /// passed to this method.
279     ///
280     /// # Platform-specific behavior
281     ///
282     /// Platforms may return a different error code whenever a write times out
283     /// as a result of setting this option. For example Unix typically returns
284     /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
285     ///
286     /// [`None`]: ../../std/option/enum.Option.html#variant.None
287     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
288     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
289     /// [`Duration`]: ../../std/time/struct.Duration.html
290     /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
291     /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
292     ///
293     /// # Examples
294     ///
295     /// ```no_run
296     /// use std::net::UdpSocket;
297     ///
298     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
299     /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
300     /// ```
301     ///
302     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
303     /// method:
304     ///
305     /// ```no_run
306     /// use std::io;
307     /// use std::net::UdpSocket;
308     /// use std::time::Duration;
309     ///
310     /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
311     /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
312     /// let err = result.unwrap_err();
313     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
314     /// ```
315     #[stable(feature = "socket_timeout", since = "1.4.0")]
316     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
317         self.0.set_write_timeout(dur)
318     }
319
320     /// Returns the read timeout of this socket.
321     ///
322     /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
323     ///
324     /// [`None`]: ../../std/option/enum.Option.html#variant.None
325     /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
326     ///
327     /// # Examples
328     ///
329     /// ```no_run
330     /// use std::net::UdpSocket;
331     ///
332     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
333     /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
334     /// assert_eq!(socket.read_timeout().unwrap(), None);
335     /// ```
336     #[stable(feature = "socket_timeout", since = "1.4.0")]
337     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
338         self.0.read_timeout()
339     }
340
341     /// Returns the write timeout of this socket.
342     ///
343     /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
344     ///
345     /// [`None`]: ../../std/option/enum.Option.html#variant.None
346     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
347     ///
348     /// # Examples
349     ///
350     /// ```no_run
351     /// use std::net::UdpSocket;
352     ///
353     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
354     /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
355     /// assert_eq!(socket.write_timeout().unwrap(), None);
356     /// ```
357     #[stable(feature = "socket_timeout", since = "1.4.0")]
358     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
359         self.0.write_timeout()
360     }
361
362     /// Sets the value of the `SO_BROADCAST` option for this socket.
363     ///
364     /// When enabled, this socket is allowed to send packets to a broadcast
365     /// address.
366     ///
367     /// # Examples
368     ///
369     /// ```no_run
370     /// use std::net::UdpSocket;
371     ///
372     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
373     /// socket.set_broadcast(false).expect("set_broadcast call failed");
374     /// ```
375     #[stable(feature = "net2_mutators", since = "1.9.0")]
376     pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
377         self.0.set_broadcast(broadcast)
378     }
379
380     /// Gets the value of the `SO_BROADCAST` option for this socket.
381     ///
382     /// For more information about this option, see
383     /// [`set_broadcast`][link].
384     ///
385     /// [link]: #method.set_broadcast
386     ///
387     /// # Examples
388     ///
389     /// ```no_run
390     /// use std::net::UdpSocket;
391     ///
392     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
393     /// socket.set_broadcast(false).expect("set_broadcast call failed");
394     /// assert_eq!(socket.broadcast().unwrap(), false);
395     /// ```
396     #[stable(feature = "net2_mutators", since = "1.9.0")]
397     pub fn broadcast(&self) -> io::Result<bool> {
398         self.0.broadcast()
399     }
400
401     /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
402     ///
403     /// If enabled, multicast packets will be looped back to the local socket.
404     /// Note that this may not have any affect on IPv6 sockets.
405     ///
406     /// # Examples
407     ///
408     /// ```no_run
409     /// use std::net::UdpSocket;
410     ///
411     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
412     /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
413     /// ```
414     #[stable(feature = "net2_mutators", since = "1.9.0")]
415     pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
416         self.0.set_multicast_loop_v4(multicast_loop_v4)
417     }
418
419     /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
420     ///
421     /// For more information about this option, see
422     /// [`set_multicast_loop_v4`][link].
423     ///
424     /// [link]: #method.set_multicast_loop_v4
425     ///
426     /// # Examples
427     ///
428     /// ```no_run
429     /// use std::net::UdpSocket;
430     ///
431     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
432     /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
433     /// assert_eq!(socket.multicast_loop_v4().unwrap(), false);
434     /// ```
435     #[stable(feature = "net2_mutators", since = "1.9.0")]
436     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
437         self.0.multicast_loop_v4()
438     }
439
440     /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
441     ///
442     /// Indicates the time-to-live value of outgoing multicast packets for
443     /// this socket. The default value is 1 which means that multicast packets
444     /// don't leave the local network unless explicitly requested.
445     ///
446     /// Note that this may not have any affect on IPv6 sockets.
447     ///
448     /// # Examples
449     ///
450     /// ```no_run
451     /// use std::net::UdpSocket;
452     ///
453     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
454     /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
455     /// ```
456     #[stable(feature = "net2_mutators", since = "1.9.0")]
457     pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
458         self.0.set_multicast_ttl_v4(multicast_ttl_v4)
459     }
460
461     /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
462     ///
463     /// For more information about this option, see
464     /// [`set_multicast_ttl_v4`][link].
465     ///
466     /// [link]: #method.set_multicast_ttl_v4
467     ///
468     /// # Examples
469     ///
470     /// ```no_run
471     /// use std::net::UdpSocket;
472     ///
473     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
474     /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
475     /// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
476     /// ```
477     #[stable(feature = "net2_mutators", since = "1.9.0")]
478     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
479         self.0.multicast_ttl_v4()
480     }
481
482     /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
483     ///
484     /// Controls whether this socket sees the multicast packets it sends itself.
485     /// Note that this may not have any affect on IPv4 sockets.
486     ///
487     /// # Examples
488     ///
489     /// ```no_run
490     /// use std::net::UdpSocket;
491     ///
492     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
493     /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
494     /// ```
495     #[stable(feature = "net2_mutators", since = "1.9.0")]
496     pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
497         self.0.set_multicast_loop_v6(multicast_loop_v6)
498     }
499
500     /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
501     ///
502     /// For more information about this option, see
503     /// [`set_multicast_loop_v6`][link].
504     ///
505     /// [link]: #method.set_multicast_loop_v6
506     ///
507     /// # Examples
508     ///
509     /// ```no_run
510     /// use std::net::UdpSocket;
511     ///
512     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
513     /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
514     /// assert_eq!(socket.multicast_loop_v6().unwrap(), false);
515     /// ```
516     #[stable(feature = "net2_mutators", since = "1.9.0")]
517     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
518         self.0.multicast_loop_v6()
519     }
520
521     /// Sets the value for the `IP_TTL` option on this socket.
522     ///
523     /// This value sets the time-to-live field that is used in every packet sent
524     /// from this socket.
525     ///
526     /// # Examples
527     ///
528     /// ```no_run
529     /// use std::net::UdpSocket;
530     ///
531     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
532     /// socket.set_ttl(42).expect("set_ttl call failed");
533     /// ```
534     #[stable(feature = "net2_mutators", since = "1.9.0")]
535     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
536         self.0.set_ttl(ttl)
537     }
538
539     /// Gets the value of the `IP_TTL` option for this socket.
540     ///
541     /// For more information about this option, see [`set_ttl`][link].
542     ///
543     /// [link]: #method.set_ttl
544     ///
545     /// # Examples
546     ///
547     /// ```no_run
548     /// use std::net::UdpSocket;
549     ///
550     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
551     /// socket.set_ttl(42).expect("set_ttl call failed");
552     /// assert_eq!(socket.ttl().unwrap(), 42);
553     /// ```
554     #[stable(feature = "net2_mutators", since = "1.9.0")]
555     pub fn ttl(&self) -> io::Result<u32> {
556         self.0.ttl()
557     }
558
559     /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
560     ///
561     /// This function specifies a new multicast group for this socket to join.
562     /// The address must be a valid multicast address, and `interface` is the
563     /// address of the local interface with which the system should join the
564     /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
565     /// interface is chosen by the system.
566     #[stable(feature = "net2_mutators", since = "1.9.0")]
567     pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
568         self.0.join_multicast_v4(multiaddr, interface)
569     }
570
571     /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
572     ///
573     /// This function specifies a new multicast group for this socket to join.
574     /// The address must be a valid multicast address, and `interface` is the
575     /// index of the interface to join/leave (or 0 to indicate any interface).
576     #[stable(feature = "net2_mutators", since = "1.9.0")]
577     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
578         self.0.join_multicast_v6(multiaddr, interface)
579     }
580
581     /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
582     ///
583     /// For more information about this option, see
584     /// [`join_multicast_v4`][link].
585     ///
586     /// [link]: #method.join_multicast_v4
587     #[stable(feature = "net2_mutators", since = "1.9.0")]
588     pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
589         self.0.leave_multicast_v4(multiaddr, interface)
590     }
591
592     /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
593     ///
594     /// For more information about this option, see
595     /// [`join_multicast_v6`][link].
596     ///
597     /// [link]: #method.join_multicast_v6
598     #[stable(feature = "net2_mutators", since = "1.9.0")]
599     pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
600         self.0.leave_multicast_v6(multiaddr, interface)
601     }
602
603     /// Get the value of the `SO_ERROR` option on this socket.
604     ///
605     /// This will retrieve the stored error in the underlying socket, clearing
606     /// the field in the process. This can be useful for checking errors between
607     /// calls.
608     ///
609     /// # Examples
610     ///
611     /// ```no_run
612     /// use std::net::UdpSocket;
613     ///
614     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
615     /// match socket.take_error() {
616     ///     Ok(Some(error)) => println!("UdpSocket error: {:?}", error),
617     ///     Ok(None) => println!("No error"),
618     ///     Err(error) => println!("UdpSocket.take_error failed: {:?}", error),
619     /// }
620     /// ```
621     #[stable(feature = "net2_mutators", since = "1.9.0")]
622     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
623         self.0.take_error()
624     }
625
626     /// Connects this UDP socket to a remote address, allowing the `send` and
627     /// `recv` syscalls to be used to send data and also applies filters to only
628     /// receive data from the specified address.
629     ///
630     /// If `addr` yields multiple addresses, `connect` will be attempted with
631     /// each of the addresses until the underlying OS function returns no
632     /// error. Note that usually, a successful `connect` call does not specify
633     /// that there is a remote server listening on the port, rather, such an
634     /// error would only be detected after the first send. If the OS returns an
635     /// error for each of the specified addresses, the error returned from the
636     /// last connection attempt (the last address) is returned.
637     ///
638     /// # Examples
639     ///
640     /// Create a UDP socket bound to `127.0.0.1:3400` and connect the socket to
641     /// `127.0.0.1:8080`:
642     ///
643     /// ```no_run
644     /// use std::net::UdpSocket;
645     ///
646     /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
647     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
648     /// ```
649     ///
650     /// Unlike in the TCP case, passing an array of addresses to the `connect`
651     /// function of a UDP socket is not a useful thing to do: The OS will be
652     /// unable to determine whether something is listening on the remote
653     /// address without the application sending data.
654     #[stable(feature = "net2_mutators", since = "1.9.0")]
655     pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
656         super::each_addr(addr, |addr| self.0.connect(addr))
657     }
658
659     /// Sends data on the socket to the remote address to which it is connected.
660     ///
661     /// The [`connect`] method will connect this socket to a remote address. This
662     /// method will fail if the socket is not connected.
663     ///
664     /// [`connect`]: #method.connect
665     ///
666     /// # Examples
667     ///
668     /// ```no_run
669     /// use std::net::UdpSocket;
670     ///
671     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
672     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
673     /// socket.send(&[0, 1, 2]).expect("couldn't send message");
674     /// ```
675     #[stable(feature = "net2_mutators", since = "1.9.0")]
676     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
677         self.0.send(buf)
678     }
679
680     /// Receives a single datagram message on the socket from the remote address to
681     /// which it is connected. On success, returns the number of bytes read.
682     ///
683     /// The function must be called with valid byte array `buf` of sufficient size to
684     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
685     /// excess bytes may be discarded.
686     ///
687     /// The [`connect`] method will connect this socket to a remote address. This
688     /// method will fail if the socket is not connected.
689     ///
690     /// [`connect`]: #method.connect
691     ///
692     /// # Examples
693     ///
694     /// ```no_run
695     /// use std::net::UdpSocket;
696     ///
697     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
698     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
699     /// let mut buf = [0; 10];
700     /// match socket.recv(&mut buf) {
701     ///     Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]),
702     ///     Err(e) => println!("recv function failed: {:?}", e),
703     /// }
704     /// ```
705     #[stable(feature = "net2_mutators", since = "1.9.0")]
706     pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
707         self.0.recv(buf)
708     }
709
710     /// Receives single datagram on the socket from the remote address to which it is
711     /// connected, without removing the message from input queue. On success, returns
712     /// the number of bytes peeked.
713     ///
714     /// The function must be called with valid byte array `buf` of sufficient size to
715     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
716     /// excess bytes may be discarded.
717     ///
718     /// Successive calls return the same data. This is accomplished by passing
719     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
720     ///
721     /// Do not use this function to implement busy waiting, instead use `libc::poll` to
722     /// synchronize IO events on one or more sockets.
723     ///
724     /// The [`connect`] method will connect this socket to a remote address. This
725     /// method will fail if the socket is not connected.
726     ///
727     /// [`connect`]: #method.connect
728     ///
729     /// # Errors
730     ///
731     /// This method will fail if the socket is not connected. The `connect` method
732     /// will connect this socket to a remote address.
733     ///
734     /// # Examples
735     ///
736     /// ```no_run
737     /// use std::net::UdpSocket;
738     ///
739     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
740     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
741     /// let mut buf = [0; 10];
742     /// match socket.peek(&mut buf) {
743     ///     Ok(received) => println!("received {} bytes", received),
744     ///     Err(e) => println!("peek function failed: {:?}", e),
745     /// }
746     /// ```
747     #[stable(feature = "peek", since = "1.18.0")]
748     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
749         self.0.peek(buf)
750     }
751
752     /// Moves this UDP socket into or out of nonblocking mode.
753     ///
754     /// This will result in `recv`, `recv_from`, `send`, and `send_to`
755     /// operations becoming nonblocking, i.e. immediately returning from their
756     /// calls. If the IO operation is successful, `Ok` is returned and no
757     /// further action is required. If the IO operation could not be completed
758     /// and needs to be retried, an error with kind
759     /// [`io::ErrorKind::WouldBlock`] is returned.
760     ///
761     /// On Unix platforms, calling this method corresponds to calling `fcntl`
762     /// `FIONBIO`. On Windows calling this method corresponds to calling
763     /// `ioctlsocket` `FIONBIO`.
764     ///
765     /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
766     ///
767     /// # Examples
768     ///
769     /// Create a UDP socket bound to `127.0.0.1:7878` and read bytes in
770     /// nonblocking mode:
771     ///
772     /// ```no_run
773     /// use std::io;
774     /// use std::net::UdpSocket;
775     ///
776     /// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
777     /// socket.set_nonblocking(true).unwrap();
778     ///
779     /// # fn wait_for_fd() { unimplemented!() }
780     /// let mut buf = [0; 10];
781     /// let (num_bytes_read, _) = loop {
782     ///     match socket.recv_from(&mut buf) {
783     ///         Ok(n) => break n,
784     ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
785     ///             // wait until network socket is ready, typically implemented
786     ///             // via platform-specific APIs such as epoll or IOCP
787     ///             wait_for_fd();
788     ///         }
789     ///         Err(e) => panic!("encountered IO error: {}", e),
790     ///     }
791     /// };
792     /// println!("bytes: {:?}", &buf[..num_bytes_read]);
793     /// ```
794     #[stable(feature = "net2_mutators", since = "1.9.0")]
795     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
796         self.0.set_nonblocking(nonblocking)
797     }
798 }
799
800 impl AsInner<net_imp::UdpSocket> for UdpSocket {
801     fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 }
802 }
803
804 impl FromInner<net_imp::UdpSocket> for UdpSocket {
805     fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) }
806 }
807
808 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
809     fn into_inner(self) -> net_imp::UdpSocket { self.0 }
810 }
811
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl fmt::Debug for UdpSocket {
814     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
815         self.0.fmt(f)
816     }
817 }
818
819 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
820 mod tests {
821     use io::ErrorKind;
822     use net::*;
823     use net::test::{next_test_ip4, next_test_ip6};
824     use sync::mpsc::channel;
825     use sys_common::AsInner;
826     use time::{Instant, Duration};
827     use thread;
828
829     fn each_ip(f: &mut FnMut(SocketAddr, SocketAddr)) {
830         f(next_test_ip4(), next_test_ip4());
831         f(next_test_ip6(), next_test_ip6());
832     }
833
834     macro_rules! t {
835         ($e:expr) => {
836             match $e {
837                 Ok(t) => t,
838                 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
839             }
840         }
841     }
842
843     #[test]
844     fn bind_error() {
845         match UdpSocket::bind("1.1.1.1:9999") {
846             Ok(..) => panic!(),
847             Err(e) => {
848                 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable)
849             }
850         }
851     }
852
853     #[test]
854     fn socket_smoke_test_ip4() {
855         each_ip(&mut |server_ip, client_ip| {
856             let (tx1, rx1) = channel();
857             let (tx2, rx2) = channel();
858
859             let _t = thread::spawn(move|| {
860                 let client = t!(UdpSocket::bind(&client_ip));
861                 rx1.recv().unwrap();
862                 t!(client.send_to(&[99], &server_ip));
863                 tx2.send(()).unwrap();
864             });
865
866             let server = t!(UdpSocket::bind(&server_ip));
867             tx1.send(()).unwrap();
868             let mut buf = [0];
869             let (nread, src) = t!(server.recv_from(&mut buf));
870             assert_eq!(nread, 1);
871             assert_eq!(buf[0], 99);
872             assert_eq!(src, client_ip);
873             rx2.recv().unwrap();
874         })
875     }
876
877     #[test]
878     fn socket_name_ip4() {
879         each_ip(&mut |addr, _| {
880             let server = t!(UdpSocket::bind(&addr));
881             assert_eq!(addr, t!(server.local_addr()));
882         })
883     }
884
885     #[test]
886     fn udp_clone_smoke() {
887         each_ip(&mut |addr1, addr2| {
888             let sock1 = t!(UdpSocket::bind(&addr1));
889             let sock2 = t!(UdpSocket::bind(&addr2));
890
891             let _t = thread::spawn(move|| {
892                 let mut buf = [0, 0];
893                 assert_eq!(sock2.recv_from(&mut buf).unwrap(), (1, addr1));
894                 assert_eq!(buf[0], 1);
895                 t!(sock2.send_to(&[2], &addr1));
896             });
897
898             let sock3 = t!(sock1.try_clone());
899
900             let (tx1, rx1) = channel();
901             let (tx2, rx2) = channel();
902             let _t = thread::spawn(move|| {
903                 rx1.recv().unwrap();
904                 t!(sock3.send_to(&[1], &addr2));
905                 tx2.send(()).unwrap();
906             });
907             tx1.send(()).unwrap();
908             let mut buf = [0, 0];
909             assert_eq!(sock1.recv_from(&mut buf).unwrap(), (1, addr2));
910             rx2.recv().unwrap();
911         })
912     }
913
914     #[test]
915     fn udp_clone_two_read() {
916         each_ip(&mut |addr1, addr2| {
917             let sock1 = t!(UdpSocket::bind(&addr1));
918             let sock2 = t!(UdpSocket::bind(&addr2));
919             let (tx1, rx) = channel();
920             let tx2 = tx1.clone();
921
922             let _t = thread::spawn(move|| {
923                 t!(sock2.send_to(&[1], &addr1));
924                 rx.recv().unwrap();
925                 t!(sock2.send_to(&[2], &addr1));
926                 rx.recv().unwrap();
927             });
928
929             let sock3 = t!(sock1.try_clone());
930
931             let (done, rx) = channel();
932             let _t = thread::spawn(move|| {
933                 let mut buf = [0, 0];
934                 t!(sock3.recv_from(&mut buf));
935                 tx2.send(()).unwrap();
936                 done.send(()).unwrap();
937             });
938             let mut buf = [0, 0];
939             t!(sock1.recv_from(&mut buf));
940             tx1.send(()).unwrap();
941
942             rx.recv().unwrap();
943         })
944     }
945
946     #[test]
947     fn udp_clone_two_write() {
948         each_ip(&mut |addr1, addr2| {
949             let sock1 = t!(UdpSocket::bind(&addr1));
950             let sock2 = t!(UdpSocket::bind(&addr2));
951
952             let (tx, rx) = channel();
953             let (serv_tx, serv_rx) = channel();
954
955             let _t = thread::spawn(move|| {
956                 let mut buf = [0, 1];
957                 rx.recv().unwrap();
958                 t!(sock2.recv_from(&mut buf));
959                 serv_tx.send(()).unwrap();
960             });
961
962             let sock3 = t!(sock1.try_clone());
963
964             let (done, rx) = channel();
965             let tx2 = tx.clone();
966             let _t = thread::spawn(move|| {
967                 match sock3.send_to(&[1], &addr2) {
968                     Ok(..) => { let _ = tx2.send(()); }
969                     Err(..) => {}
970                 }
971                 done.send(()).unwrap();
972             });
973             match sock1.send_to(&[2], &addr2) {
974                 Ok(..) => { let _ = tx.send(()); }
975                 Err(..) => {}
976             }
977             drop(tx);
978
979             rx.recv().unwrap();
980             serv_rx.recv().unwrap();
981         })
982     }
983
984     #[test]
985     fn debug() {
986         let name = if cfg!(windows) {"socket"} else {"fd"};
987         let socket_addr = next_test_ip4();
988
989         let udpsock = t!(UdpSocket::bind(&socket_addr));
990         let udpsock_inner = udpsock.0.socket().as_inner();
991         let compare = format!("UdpSocket {{ addr: {:?}, {}: {:?} }}",
992                               socket_addr, name, udpsock_inner);
993         assert_eq!(format!("{:?}", udpsock), compare);
994     }
995
996     // FIXME: re-enabled bitrig/openbsd/netbsd tests once their socket timeout code
997     //        no longer has rounding errors.
998     #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
999     #[test]
1000     fn timeouts() {
1001         let addr = next_test_ip4();
1002
1003         let stream = t!(UdpSocket::bind(&addr));
1004         let dur = Duration::new(15410, 0);
1005
1006         assert_eq!(None, t!(stream.read_timeout()));
1007
1008         t!(stream.set_read_timeout(Some(dur)));
1009         assert_eq!(Some(dur), t!(stream.read_timeout()));
1010
1011         assert_eq!(None, t!(stream.write_timeout()));
1012
1013         t!(stream.set_write_timeout(Some(dur)));
1014         assert_eq!(Some(dur), t!(stream.write_timeout()));
1015
1016         t!(stream.set_read_timeout(None));
1017         assert_eq!(None, t!(stream.read_timeout()));
1018
1019         t!(stream.set_write_timeout(None));
1020         assert_eq!(None, t!(stream.write_timeout()));
1021     }
1022
1023     #[test]
1024     fn test_read_timeout() {
1025         let addr = next_test_ip4();
1026
1027         let stream = t!(UdpSocket::bind(&addr));
1028         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1029
1030         let mut buf = [0; 10];
1031
1032         let start = Instant::now();
1033         let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
1034         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1035         assert!(start.elapsed() > Duration::from_millis(400));
1036     }
1037
1038     #[test]
1039     fn test_read_with_timeout() {
1040         let addr = next_test_ip4();
1041
1042         let stream = t!(UdpSocket::bind(&addr));
1043         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1044
1045         t!(stream.send_to(b"hello world", &addr));
1046
1047         let mut buf = [0; 11];
1048         t!(stream.recv_from(&mut buf));
1049         assert_eq!(b"hello world", &buf[..]);
1050
1051         let start = Instant::now();
1052         let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
1053         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1054         assert!(start.elapsed() > Duration::from_millis(400));
1055     }
1056
1057     // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1058     // when passed zero Durations
1059     #[test]
1060     fn test_timeout_zero_duration() {
1061         let addr = next_test_ip4();
1062
1063         let socket = t!(UdpSocket::bind(&addr));
1064
1065         let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
1066         let err = result.unwrap_err();
1067         assert_eq!(err.kind(), ErrorKind::InvalidInput);
1068
1069         let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
1070         let err = result.unwrap_err();
1071         assert_eq!(err.kind(), ErrorKind::InvalidInput);
1072     }
1073
1074     #[test]
1075     fn connect_send_recv() {
1076         let addr = next_test_ip4();
1077
1078         let socket = t!(UdpSocket::bind(&addr));
1079         t!(socket.connect(addr));
1080
1081         t!(socket.send(b"hello world"));
1082
1083         let mut buf = [0; 11];
1084         t!(socket.recv(&mut buf));
1085         assert_eq!(b"hello world", &buf[..]);
1086     }
1087
1088     #[test]
1089     fn connect_send_peek_recv() {
1090         each_ip(&mut |addr, _| {
1091             let socket = t!(UdpSocket::bind(&addr));
1092             t!(socket.connect(addr));
1093
1094             t!(socket.send(b"hello world"));
1095
1096             for _ in 1..3 {
1097                 let mut buf = [0; 11];
1098                 let size = t!(socket.peek(&mut buf));
1099                 assert_eq!(b"hello world", &buf[..]);
1100                 assert_eq!(size, 11);
1101             }
1102
1103             let mut buf = [0; 11];
1104             let size = t!(socket.recv(&mut buf));
1105             assert_eq!(b"hello world", &buf[..]);
1106             assert_eq!(size, 11);
1107         })
1108     }
1109
1110     #[test]
1111     fn peek_from() {
1112         each_ip(&mut |addr, _| {
1113             let socket = t!(UdpSocket::bind(&addr));
1114             t!(socket.send_to(b"hello world", &addr));
1115
1116             for _ in 1..3 {
1117                 let mut buf = [0; 11];
1118                 let (size, _) = t!(socket.peek_from(&mut buf));
1119                 assert_eq!(b"hello world", &buf[..]);
1120                 assert_eq!(size, 11);
1121             }
1122
1123             let mut buf = [0; 11];
1124             let (size, _) = t!(socket.recv_from(&mut buf));
1125             assert_eq!(b"hello world", &buf[..]);
1126             assert_eq!(size, 11);
1127         })
1128     }
1129
1130     #[test]
1131     fn ttl() {
1132         let ttl = 100;
1133
1134         let addr = next_test_ip4();
1135
1136         let stream = t!(UdpSocket::bind(&addr));
1137
1138         t!(stream.set_ttl(ttl));
1139         assert_eq!(ttl, t!(stream.ttl()));
1140     }
1141
1142     #[test]
1143     fn set_nonblocking() {
1144         each_ip(&mut |addr, _| {
1145             let socket = t!(UdpSocket::bind(&addr));
1146
1147             t!(socket.set_nonblocking(true));
1148             t!(socket.set_nonblocking(false));
1149
1150             t!(socket.connect(addr));
1151
1152             t!(socket.set_nonblocking(false));
1153             t!(socket.set_nonblocking(true));
1154
1155             let mut buf = [0];
1156             match socket.recv(&mut buf) {
1157                 Ok(_) => panic!("expected error"),
1158                 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1159                 Err(e) => panic!("unexpected error {}", e),
1160             }
1161         })
1162     }
1163 }