]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/udp.rs
Rollup merge of #84320 - jsha:details-implementors, r=Manishearth,Nemo157,GuillaumeGomez
[rust.git] / library / std / src / net / udp.rs
1 #[cfg(all(test, not(any(target_os = "emscripten", target_env = "sgx"))))]
2 mod tests;
3
4 use crate::fmt;
5 use crate::io::{self, Error, ErrorKind};
6 use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
7 use crate::sys_common::net as net_imp;
8 use crate::sys_common::{AsInner, FromInner, IntoInner};
9 use crate::time::Duration;
10
11 /// A UDP socket.
12 ///
13 /// After creating a `UdpSocket` by [`bind`]ing it to a socket address, data can be
14 /// [sent to] and [received from] any other socket address.
15 ///
16 /// Although UDP is a connectionless protocol, this implementation provides an interface
17 /// to set an address where data should be sent and received from. After setting a remote
18 /// address with [`connect`], data can be sent to and received from that address with
19 /// [`send`] and [`recv`].
20 ///
21 /// As stated in the User Datagram Protocol's specification in [IETF RFC 768], UDP is
22 /// an unordered, unreliable protocol; refer to [`TcpListener`] and [`TcpStream`] for TCP
23 /// primitives.
24 ///
25 /// [`bind`]: UdpSocket::bind
26 /// [`connect`]: UdpSocket::connect
27 /// [IETF RFC 768]: https://tools.ietf.org/html/rfc768
28 /// [`recv`]: UdpSocket::recv
29 /// [received from]: UdpSocket::recv_from
30 /// [`send`]: UdpSocket::send
31 /// [sent to]: UdpSocket::send_to
32 /// [`TcpListener`]: crate::net::TcpListener
33 /// [`TcpStream`]: crate::net::TcpStream
34 ///
35 /// # Examples
36 ///
37 /// ```no_run
38 /// use std::net::UdpSocket;
39 ///
40 /// fn main() -> std::io::Result<()> {
41 ///     {
42 ///         let mut socket = UdpSocket::bind("127.0.0.1:34254")?;
43 ///
44 ///         // Receives a single datagram message on the socket. If `buf` is too small to hold
45 ///         // the message, it will be cut off.
46 ///         let mut buf = [0; 10];
47 ///         let (amt, src) = socket.recv_from(&mut buf)?;
48 ///
49 ///         // Redeclare `buf` as slice of the received data and send reverse data back to origin.
50 ///         let buf = &mut buf[..amt];
51 ///         buf.reverse();
52 ///         socket.send_to(buf, &src)?;
53 ///     } // the socket is closed here
54 ///     Ok(())
55 /// }
56 /// ```
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub struct UdpSocket(net_imp::UdpSocket);
59
60 impl UdpSocket {
61     /// Creates a UDP socket from the given address.
62     ///
63     /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
64     /// its documentation for concrete examples.
65     ///
66     /// If `addr` yields multiple addresses, `bind` will be attempted with
67     /// each of the addresses until one succeeds and returns the socket. If none
68     /// of the addresses succeed in creating a socket, the error returned from
69     /// the last attempt (the last address) is returned.
70     ///
71     /// # Examples
72     ///
73     /// Creates a UDP socket bound to `127.0.0.1:3400`:
74     ///
75     /// ```no_run
76     /// use std::net::UdpSocket;
77     ///
78     /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
79     /// ```
80     ///
81     /// Creates a UDP socket bound to `127.0.0.1:3400`. If the socket cannot be
82     /// bound to that address, create a UDP socket bound to `127.0.0.1:3401`:
83     ///
84     /// ```no_run
85     /// use std::net::{SocketAddr, UdpSocket};
86     ///
87     /// let addrs = [
88     ///     SocketAddr::from(([127, 0, 0, 1], 3400)),
89     ///     SocketAddr::from(([127, 0, 0, 1], 3401)),
90     /// ];
91     /// let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address");
92     /// ```
93     #[stable(feature = "rust1", since = "1.0.0")]
94     pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
95         super::each_addr(addr, net_imp::UdpSocket::bind).map(UdpSocket)
96     }
97
98     /// Receives a single datagram message on the socket. On success, returns the number
99     /// of bytes read and the origin.
100     ///
101     /// The function must be called with valid byte array `buf` of sufficient size to
102     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
103     /// excess bytes may be discarded.
104     ///
105     /// # Examples
106     ///
107     /// ```no_run
108     /// use std::net::UdpSocket;
109     ///
110     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
111     /// let mut buf = [0; 10];
112     /// let (number_of_bytes, src_addr) = socket.recv_from(&mut buf)
113     ///                                         .expect("Didn't receive data");
114     /// let filled_buf = &mut buf[..number_of_bytes];
115     /// ```
116     #[stable(feature = "rust1", since = "1.0.0")]
117     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
118         self.0.recv_from(buf)
119     }
120
121     /// Receives a single datagram message on the socket, without removing it from the
122     /// queue. On success, returns the number of bytes read and the origin.
123     ///
124     /// The function must be called with valid byte array `buf` of sufficient size to
125     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
126     /// excess bytes may be discarded.
127     ///
128     /// Successive calls return the same data. This is accomplished by passing
129     /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
130     ///
131     /// Do not use this function to implement busy waiting, instead use `libc::poll` to
132     /// synchronize IO events on one or more sockets.
133     ///
134     /// # Examples
135     ///
136     /// ```no_run
137     /// use std::net::UdpSocket;
138     ///
139     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
140     /// let mut buf = [0; 10];
141     /// let (number_of_bytes, src_addr) = socket.peek_from(&mut buf)
142     ///                                         .expect("Didn't receive data");
143     /// let filled_buf = &mut buf[..number_of_bytes];
144     /// ```
145     #[stable(feature = "peek", since = "1.18.0")]
146     pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
147         self.0.peek_from(buf)
148     }
149
150     /// Sends data on the socket to the given address. On success, returns the
151     /// number of bytes written.
152     ///
153     /// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
154     /// documentation for concrete examples.
155     ///
156     /// It is possible for `addr` to yield multiple addresses, but `send_to`
157     /// will only send data to the first address yielded by `addr`.
158     ///
159     /// This will return an error when the IP version of the local socket
160     /// does not match that returned from [`ToSocketAddrs`].
161     ///
162     /// See issue #34202 for more details.
163     ///
164     /// # Examples
165     ///
166     /// ```no_run
167     /// use std::net::UdpSocket;
168     ///
169     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
170     /// socket.send_to(&[0; 10], "127.0.0.1:4242").expect("couldn't send data");
171     /// ```
172     #[stable(feature = "rust1", since = "1.0.0")]
173     pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
174         match addr.to_socket_addrs()?.next() {
175             Some(addr) => self.0.send_to(buf, &addr),
176             None => Err(Error::new_const(ErrorKind::InvalidInput, &"no addresses to send data to")),
177         }
178     }
179
180     /// Returns the socket address of the remote peer this socket was connected to.
181     ///
182     /// # Examples
183     ///
184     /// ```no_run
185     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
186     ///
187     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
188     /// socket.connect("192.168.0.1:41203").expect("couldn't connect to address");
189     /// assert_eq!(socket.peer_addr().unwrap(),
190     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 41203)));
191     /// ```
192     ///
193     /// If the socket isn't connected, it will return a [`NotConnected`] error.
194     ///
195     /// [`NotConnected`]: io::ErrorKind::NotConnected
196     ///
197     /// ```no_run
198     /// use std::net::UdpSocket;
199     ///
200     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
201     /// assert_eq!(socket.peer_addr().unwrap_err().kind(),
202     ///            std::io::ErrorKind::NotConnected);
203     /// ```
204     #[stable(feature = "udp_peer_addr", since = "1.40.0")]
205     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
206         self.0.peer_addr()
207     }
208
209     /// Returns the socket address that this socket was created from.
210     ///
211     /// # Examples
212     ///
213     /// ```no_run
214     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
215     ///
216     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
217     /// assert_eq!(socket.local_addr().unwrap(),
218     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)));
219     /// ```
220     #[stable(feature = "rust1", since = "1.0.0")]
221     pub fn local_addr(&self) -> io::Result<SocketAddr> {
222         self.0.socket_addr()
223     }
224
225     /// Creates a new independently owned handle to the underlying socket.
226     ///
227     /// The returned `UdpSocket` is a reference to the same socket that this
228     /// object references. Both handles will read and write the same port, and
229     /// options set on one socket will be propagated to the other.
230     ///
231     /// # Examples
232     ///
233     /// ```no_run
234     /// use std::net::UdpSocket;
235     ///
236     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
237     /// let socket_clone = socket.try_clone().expect("couldn't clone the socket");
238     /// ```
239     #[stable(feature = "rust1", since = "1.0.0")]
240     pub fn try_clone(&self) -> io::Result<UdpSocket> {
241         self.0.duplicate().map(UdpSocket)
242     }
243
244     /// Sets the read timeout to the timeout specified.
245     ///
246     /// If the value specified is [`None`], then [`read`] calls will block
247     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
248     /// passed to this method.
249     ///
250     /// # Platform-specific behavior
251     ///
252     /// Platforms may return a different error code whenever a read times out as
253     /// a result of setting this option. For example Unix typically returns an
254     /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
255     ///
256     /// [`read`]: io::Read::read
257     /// [`WouldBlock`]: io::ErrorKind::WouldBlock
258     /// [`TimedOut`]: io::ErrorKind::TimedOut
259     ///
260     /// # Examples
261     ///
262     /// ```no_run
263     /// use std::net::UdpSocket;
264     ///
265     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
266     /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
267     /// ```
268     ///
269     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
270     /// method:
271     ///
272     /// ```no_run
273     /// use std::io;
274     /// use std::net::UdpSocket;
275     /// use std::time::Duration;
276     ///
277     /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
278     /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
279     /// let err = result.unwrap_err();
280     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
281     /// ```
282     #[stable(feature = "socket_timeout", since = "1.4.0")]
283     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
284         self.0.set_read_timeout(dur)
285     }
286
287     /// Sets the write timeout to the timeout specified.
288     ///
289     /// If the value specified is [`None`], then [`write`] calls will block
290     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
291     /// passed to this method.
292     ///
293     /// # Platform-specific behavior
294     ///
295     /// Platforms may return a different error code whenever a write times out
296     /// as a result of setting this option. For example Unix typically returns
297     /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
298     ///
299     /// [`write`]: io::Write::write
300     /// [`WouldBlock`]: io::ErrorKind::WouldBlock
301     /// [`TimedOut`]: io::ErrorKind::TimedOut
302     ///
303     /// # Examples
304     ///
305     /// ```no_run
306     /// use std::net::UdpSocket;
307     ///
308     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
309     /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
310     /// ```
311     ///
312     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
313     /// method:
314     ///
315     /// ```no_run
316     /// use std::io;
317     /// use std::net::UdpSocket;
318     /// use std::time::Duration;
319     ///
320     /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
321     /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
322     /// let err = result.unwrap_err();
323     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
324     /// ```
325     #[stable(feature = "socket_timeout", since = "1.4.0")]
326     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
327         self.0.set_write_timeout(dur)
328     }
329
330     /// Returns the read timeout of this socket.
331     ///
332     /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
333     ///
334     /// [`read`]: io::Read::read
335     ///
336     /// # Examples
337     ///
338     /// ```no_run
339     /// use std::net::UdpSocket;
340     ///
341     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
342     /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
343     /// assert_eq!(socket.read_timeout().unwrap(), None);
344     /// ```
345     #[stable(feature = "socket_timeout", since = "1.4.0")]
346     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
347         self.0.read_timeout()
348     }
349
350     /// Returns the write timeout of this socket.
351     ///
352     /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
353     ///
354     /// [`write`]: io::Write::write
355     ///
356     /// # Examples
357     ///
358     /// ```no_run
359     /// use std::net::UdpSocket;
360     ///
361     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
362     /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
363     /// assert_eq!(socket.write_timeout().unwrap(), None);
364     /// ```
365     #[stable(feature = "socket_timeout", since = "1.4.0")]
366     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
367         self.0.write_timeout()
368     }
369
370     /// Sets the value of the `SO_BROADCAST` option for this socket.
371     ///
372     /// When enabled, this socket is allowed to send packets to a broadcast
373     /// address.
374     ///
375     /// # Examples
376     ///
377     /// ```no_run
378     /// use std::net::UdpSocket;
379     ///
380     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
381     /// socket.set_broadcast(false).expect("set_broadcast call failed");
382     /// ```
383     #[stable(feature = "net2_mutators", since = "1.9.0")]
384     pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
385         self.0.set_broadcast(broadcast)
386     }
387
388     /// Gets the value of the `SO_BROADCAST` option for this socket.
389     ///
390     /// For more information about this option, see [`UdpSocket::set_broadcast`].
391     ///
392     /// # Examples
393     ///
394     /// ```no_run
395     /// use std::net::UdpSocket;
396     ///
397     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
398     /// socket.set_broadcast(false).expect("set_broadcast call failed");
399     /// assert_eq!(socket.broadcast().unwrap(), false);
400     /// ```
401     #[stable(feature = "net2_mutators", since = "1.9.0")]
402     pub fn broadcast(&self) -> io::Result<bool> {
403         self.0.broadcast()
404     }
405
406     /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
407     ///
408     /// If enabled, multicast packets will be looped back to the local socket.
409     /// Note that this may not have any effect on IPv6 sockets.
410     ///
411     /// # Examples
412     ///
413     /// ```no_run
414     /// use std::net::UdpSocket;
415     ///
416     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
417     /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
418     /// ```
419     #[stable(feature = "net2_mutators", since = "1.9.0")]
420     pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
421         self.0.set_multicast_loop_v4(multicast_loop_v4)
422     }
423
424     /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
425     ///
426     /// For more information about this option, see [`UdpSocket::set_multicast_loop_v4`].
427     ///
428     /// # Examples
429     ///
430     /// ```no_run
431     /// use std::net::UdpSocket;
432     ///
433     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
434     /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
435     /// assert_eq!(socket.multicast_loop_v4().unwrap(), false);
436     /// ```
437     #[stable(feature = "net2_mutators", since = "1.9.0")]
438     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
439         self.0.multicast_loop_v4()
440     }
441
442     /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
443     ///
444     /// Indicates the time-to-live value of outgoing multicast packets for
445     /// this socket. The default value is 1 which means that multicast packets
446     /// don't leave the local network unless explicitly requested.
447     ///
448     /// Note that this may not have any effect on IPv6 sockets.
449     ///
450     /// # Examples
451     ///
452     /// ```no_run
453     /// use std::net::UdpSocket;
454     ///
455     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
456     /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
457     /// ```
458     #[stable(feature = "net2_mutators", since = "1.9.0")]
459     pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
460         self.0.set_multicast_ttl_v4(multicast_ttl_v4)
461     }
462
463     /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
464     ///
465     /// For more information about this option, see [`UdpSocket::set_multicast_ttl_v4`].
466     ///
467     /// # Examples
468     ///
469     /// ```no_run
470     /// use std::net::UdpSocket;
471     ///
472     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
473     /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
474     /// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
475     /// ```
476     #[stable(feature = "net2_mutators", since = "1.9.0")]
477     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
478         self.0.multicast_ttl_v4()
479     }
480
481     /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
482     ///
483     /// Controls whether this socket sees the multicast packets it sends itself.
484     /// Note that this may not have any affect on IPv4 sockets.
485     ///
486     /// # Examples
487     ///
488     /// ```no_run
489     /// use std::net::UdpSocket;
490     ///
491     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
492     /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
493     /// ```
494     #[stable(feature = "net2_mutators", since = "1.9.0")]
495     pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
496         self.0.set_multicast_loop_v6(multicast_loop_v6)
497     }
498
499     /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
500     ///
501     /// For more information about this option, see [`UdpSocket::set_multicast_loop_v6`].
502     ///
503     /// # Examples
504     ///
505     /// ```no_run
506     /// use std::net::UdpSocket;
507     ///
508     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
509     /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
510     /// assert_eq!(socket.multicast_loop_v6().unwrap(), false);
511     /// ```
512     #[stable(feature = "net2_mutators", since = "1.9.0")]
513     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
514         self.0.multicast_loop_v6()
515     }
516
517     /// Sets the value for the `IP_TTL` option on this socket.
518     ///
519     /// This value sets the time-to-live field that is used in every packet sent
520     /// from this socket.
521     ///
522     /// # Examples
523     ///
524     /// ```no_run
525     /// use std::net::UdpSocket;
526     ///
527     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
528     /// socket.set_ttl(42).expect("set_ttl call failed");
529     /// ```
530     #[stable(feature = "net2_mutators", since = "1.9.0")]
531     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
532         self.0.set_ttl(ttl)
533     }
534
535     /// Gets the value of the `IP_TTL` option for this socket.
536     ///
537     /// For more information about this option, see [`UdpSocket::set_ttl`].
538     ///
539     /// # Examples
540     ///
541     /// ```no_run
542     /// use std::net::UdpSocket;
543     ///
544     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
545     /// socket.set_ttl(42).expect("set_ttl call failed");
546     /// assert_eq!(socket.ttl().unwrap(), 42);
547     /// ```
548     #[stable(feature = "net2_mutators", since = "1.9.0")]
549     pub fn ttl(&self) -> io::Result<u32> {
550         self.0.ttl()
551     }
552
553     /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
554     ///
555     /// This function specifies a new multicast group for this socket to join.
556     /// The address must be a valid multicast address, and `interface` is the
557     /// address of the local interface with which the system should join the
558     /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
559     /// interface is chosen by the system.
560     #[stable(feature = "net2_mutators", since = "1.9.0")]
561     pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
562         self.0.join_multicast_v4(multiaddr, interface)
563     }
564
565     /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
566     ///
567     /// This function specifies a new multicast group for this socket to join.
568     /// The address must be a valid multicast address, and `interface` is the
569     /// index of the interface to join/leave (or 0 to indicate any interface).
570     #[stable(feature = "net2_mutators", since = "1.9.0")]
571     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
572         self.0.join_multicast_v6(multiaddr, interface)
573     }
574
575     /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
576     ///
577     /// For more information about this option, see [`UdpSocket::join_multicast_v4`].
578     #[stable(feature = "net2_mutators", since = "1.9.0")]
579     pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
580         self.0.leave_multicast_v4(multiaddr, interface)
581     }
582
583     /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
584     ///
585     /// For more information about this option, see [`UdpSocket::join_multicast_v6`].
586     #[stable(feature = "net2_mutators", since = "1.9.0")]
587     pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
588         self.0.leave_multicast_v6(multiaddr, interface)
589     }
590
591     /// Gets the value of the `SO_ERROR` option on this socket.
592     ///
593     /// This will retrieve the stored error in the underlying socket, clearing
594     /// the field in the process. This can be useful for checking errors between
595     /// calls.
596     ///
597     /// # Examples
598     ///
599     /// ```no_run
600     /// use std::net::UdpSocket;
601     ///
602     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
603     /// match socket.take_error() {
604     ///     Ok(Some(error)) => println!("UdpSocket error: {:?}", error),
605     ///     Ok(None) => println!("No error"),
606     ///     Err(error) => println!("UdpSocket.take_error failed: {:?}", error),
607     /// }
608     /// ```
609     #[stable(feature = "net2_mutators", since = "1.9.0")]
610     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
611         self.0.take_error()
612     }
613
614     /// Connects this UDP socket to a remote address, allowing the `send` and
615     /// `recv` syscalls to be used to send data and also applies filters to only
616     /// receive data from the specified address.
617     ///
618     /// If `addr` yields multiple addresses, `connect` will be attempted with
619     /// each of the addresses until the underlying OS function returns no
620     /// error. Note that usually, a successful `connect` call does not specify
621     /// that there is a remote server listening on the port, rather, such an
622     /// error would only be detected after the first send. If the OS returns an
623     /// error for each of the specified addresses, the error returned from the
624     /// last connection attempt (the last address) is returned.
625     ///
626     /// # Examples
627     ///
628     /// Creates a UDP socket bound to `127.0.0.1:3400` and connect the socket to
629     /// `127.0.0.1:8080`:
630     ///
631     /// ```no_run
632     /// use std::net::UdpSocket;
633     ///
634     /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
635     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
636     /// ```
637     ///
638     /// Unlike in the TCP case, passing an array of addresses to the `connect`
639     /// function of a UDP socket is not a useful thing to do: The OS will be
640     /// unable to determine whether something is listening on the remote
641     /// address without the application sending data.
642     #[stable(feature = "net2_mutators", since = "1.9.0")]
643     pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
644         super::each_addr(addr, |addr| self.0.connect(addr))
645     }
646
647     /// Sends data on the socket to the remote address to which it is connected.
648     ///
649     /// [`UdpSocket::connect`] will connect this socket to a remote address. This
650     /// method will fail if the socket is not connected.
651     ///
652     /// # Examples
653     ///
654     /// ```no_run
655     /// use std::net::UdpSocket;
656     ///
657     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
658     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
659     /// socket.send(&[0, 1, 2]).expect("couldn't send message");
660     /// ```
661     #[stable(feature = "net2_mutators", since = "1.9.0")]
662     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
663         self.0.send(buf)
664     }
665
666     /// Receives a single datagram message on the socket from the remote address to
667     /// which it is connected. On success, returns the number of bytes read.
668     ///
669     /// The function must be called with valid byte array `buf` of sufficient size to
670     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
671     /// excess bytes may be discarded.
672     ///
673     /// [`UdpSocket::connect`] will connect this socket to a remote address. This
674     /// method will fail if the socket is not connected.
675     ///
676     /// # Examples
677     ///
678     /// ```no_run
679     /// use std::net::UdpSocket;
680     ///
681     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
682     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
683     /// let mut buf = [0; 10];
684     /// match socket.recv(&mut buf) {
685     ///     Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]),
686     ///     Err(e) => println!("recv function failed: {:?}", e),
687     /// }
688     /// ```
689     #[stable(feature = "net2_mutators", since = "1.9.0")]
690     pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
691         self.0.recv(buf)
692     }
693
694     /// Receives single datagram on the socket from the remote address to which it is
695     /// connected, without removing the message from input queue. On success, returns
696     /// the number of bytes peeked.
697     ///
698     /// The function must be called with valid byte array `buf` of sufficient size to
699     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
700     /// excess bytes may be discarded.
701     ///
702     /// Successive calls return the same data. This is accomplished by passing
703     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
704     ///
705     /// Do not use this function to implement busy waiting, instead use `libc::poll` to
706     /// synchronize IO events on one or more sockets.
707     ///
708     /// [`UdpSocket::connect`] will connect this socket to a remote address. This
709     /// method will fail if the socket is not connected.
710     ///
711     /// # Errors
712     ///
713     /// This method will fail if the socket is not connected. The `connect` method
714     /// will connect this socket to a remote address.
715     ///
716     /// # Examples
717     ///
718     /// ```no_run
719     /// use std::net::UdpSocket;
720     ///
721     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
722     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
723     /// let mut buf = [0; 10];
724     /// match socket.peek(&mut buf) {
725     ///     Ok(received) => println!("received {} bytes", received),
726     ///     Err(e) => println!("peek function failed: {:?}", e),
727     /// }
728     /// ```
729     #[stable(feature = "peek", since = "1.18.0")]
730     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
731         self.0.peek(buf)
732     }
733
734     /// Moves this UDP socket into or out of nonblocking mode.
735     ///
736     /// This will result in `recv`, `recv_from`, `send`, and `send_to`
737     /// operations becoming nonblocking, i.e., immediately returning from their
738     /// calls. If the IO operation is successful, `Ok` is returned and no
739     /// further action is required. If the IO operation could not be completed
740     /// and needs to be retried, an error with kind
741     /// [`io::ErrorKind::WouldBlock`] is returned.
742     ///
743     /// On Unix platforms, calling this method corresponds to calling `fcntl`
744     /// `FIONBIO`. On Windows calling this method corresponds to calling
745     /// `ioctlsocket` `FIONBIO`.
746     ///
747     /// # Examples
748     ///
749     /// Creates a UDP socket bound to `127.0.0.1:7878` and read bytes in
750     /// nonblocking mode:
751     ///
752     /// ```no_run
753     /// use std::io;
754     /// use std::net::UdpSocket;
755     ///
756     /// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
757     /// socket.set_nonblocking(true).unwrap();
758     ///
759     /// # fn wait_for_fd() { unimplemented!() }
760     /// let mut buf = [0; 10];
761     /// let (num_bytes_read, _) = loop {
762     ///     match socket.recv_from(&mut buf) {
763     ///         Ok(n) => break n,
764     ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
765     ///             // wait until network socket is ready, typically implemented
766     ///             // via platform-specific APIs such as epoll or IOCP
767     ///             wait_for_fd();
768     ///         }
769     ///         Err(e) => panic!("encountered IO error: {}", e),
770     ///     }
771     /// };
772     /// println!("bytes: {:?}", &buf[..num_bytes_read]);
773     /// ```
774     #[stable(feature = "net2_mutators", since = "1.9.0")]
775     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
776         self.0.set_nonblocking(nonblocking)
777     }
778 }
779
780 impl AsInner<net_imp::UdpSocket> for UdpSocket {
781     fn as_inner(&self) -> &net_imp::UdpSocket {
782         &self.0
783     }
784 }
785
786 impl FromInner<net_imp::UdpSocket> for UdpSocket {
787     fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket {
788         UdpSocket(inner)
789     }
790 }
791
792 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
793     fn into_inner(self) -> net_imp::UdpSocket {
794         self.0
795     }
796 }
797
798 #[stable(feature = "rust1", since = "1.0.0")]
799 impl fmt::Debug for UdpSocket {
800     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801         self.0.fmt(f)
802     }
803 }