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