]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/udp.rs
Rollup merge of #96129 - mattheww:2022-04_float_rounding, r=Dylan-DPC
[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, 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 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     ///
173     /// [Issue #34202]: https://github.com/rust-lang/rust/issues/34202
174     #[stable(feature = "rust1", since = "1.0.0")]
175     pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
176         match addr.to_socket_addrs()?.next() {
177             Some(addr) => self.0.send_to(buf, &addr),
178             None => {
179                 Err(io::const_io_error!(ErrorKind::InvalidInput, "no addresses to send data to"))
180             }
181         }
182     }
183
184     /// Returns the socket address of the remote peer this socket was connected to.
185     ///
186     /// # Examples
187     ///
188     /// ```no_run
189     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
190     ///
191     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
192     /// socket.connect("192.168.0.1:41203").expect("couldn't connect to address");
193     /// assert_eq!(socket.peer_addr().unwrap(),
194     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 41203)));
195     /// ```
196     ///
197     /// If the socket isn't connected, it will return a [`NotConnected`] error.
198     ///
199     /// [`NotConnected`]: io::ErrorKind::NotConnected
200     ///
201     /// ```no_run
202     /// use std::net::UdpSocket;
203     ///
204     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
205     /// assert_eq!(socket.peer_addr().unwrap_err().kind(),
206     ///            std::io::ErrorKind::NotConnected);
207     /// ```
208     #[stable(feature = "udp_peer_addr", since = "1.40.0")]
209     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
210         self.0.peer_addr()
211     }
212
213     /// Returns the socket address that this socket was created from.
214     ///
215     /// # Examples
216     ///
217     /// ```no_run
218     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
219     ///
220     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
221     /// assert_eq!(socket.local_addr().unwrap(),
222     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)));
223     /// ```
224     #[stable(feature = "rust1", since = "1.0.0")]
225     pub fn local_addr(&self) -> io::Result<SocketAddr> {
226         self.0.socket_addr()
227     }
228
229     /// Creates a new independently owned handle to the underlying socket.
230     ///
231     /// The returned `UdpSocket` is a reference to the same socket that this
232     /// object references. Both handles will read and write the same port, and
233     /// options set on one socket will be propagated to the other.
234     ///
235     /// # Examples
236     ///
237     /// ```no_run
238     /// use std::net::UdpSocket;
239     ///
240     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
241     /// let socket_clone = socket.try_clone().expect("couldn't clone the socket");
242     /// ```
243     #[stable(feature = "rust1", since = "1.0.0")]
244     pub fn try_clone(&self) -> io::Result<UdpSocket> {
245         self.0.duplicate().map(UdpSocket)
246     }
247
248     /// Sets the read timeout to the timeout specified.
249     ///
250     /// If the value specified is [`None`], then [`read`] calls will block
251     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
252     /// passed to this method.
253     ///
254     /// # Platform-specific behavior
255     ///
256     /// Platforms may return a different error code whenever a read times out as
257     /// a result of setting this option. For example Unix typically returns an
258     /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
259     ///
260     /// [`read`]: io::Read::read
261     /// [`WouldBlock`]: io::ErrorKind::WouldBlock
262     /// [`TimedOut`]: io::ErrorKind::TimedOut
263     ///
264     /// # Examples
265     ///
266     /// ```no_run
267     /// use std::net::UdpSocket;
268     ///
269     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
270     /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
271     /// ```
272     ///
273     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
274     /// method:
275     ///
276     /// ```no_run
277     /// use std::io;
278     /// use std::net::UdpSocket;
279     /// use std::time::Duration;
280     ///
281     /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
282     /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
283     /// let err = result.unwrap_err();
284     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
285     /// ```
286     #[stable(feature = "socket_timeout", since = "1.4.0")]
287     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
288         self.0.set_read_timeout(dur)
289     }
290
291     /// Sets the write timeout to the timeout specified.
292     ///
293     /// If the value specified is [`None`], then [`write`] calls will block
294     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
295     /// passed to this method.
296     ///
297     /// # Platform-specific behavior
298     ///
299     /// Platforms may return a different error code whenever a write times out
300     /// as a result of setting this option. For example Unix typically returns
301     /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
302     ///
303     /// [`write`]: io::Write::write
304     /// [`WouldBlock`]: io::ErrorKind::WouldBlock
305     /// [`TimedOut`]: io::ErrorKind::TimedOut
306     ///
307     /// # Examples
308     ///
309     /// ```no_run
310     /// use std::net::UdpSocket;
311     ///
312     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
313     /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
314     /// ```
315     ///
316     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
317     /// method:
318     ///
319     /// ```no_run
320     /// use std::io;
321     /// use std::net::UdpSocket;
322     /// use std::time::Duration;
323     ///
324     /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
325     /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
326     /// let err = result.unwrap_err();
327     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
328     /// ```
329     #[stable(feature = "socket_timeout", since = "1.4.0")]
330     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
331         self.0.set_write_timeout(dur)
332     }
333
334     /// Returns the read timeout of this socket.
335     ///
336     /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
337     ///
338     /// [`read`]: io::Read::read
339     ///
340     /// # Examples
341     ///
342     /// ```no_run
343     /// use std::net::UdpSocket;
344     ///
345     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
346     /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
347     /// assert_eq!(socket.read_timeout().unwrap(), None);
348     /// ```
349     #[stable(feature = "socket_timeout", since = "1.4.0")]
350     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
351         self.0.read_timeout()
352     }
353
354     /// Returns the write timeout of this socket.
355     ///
356     /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
357     ///
358     /// [`write`]: io::Write::write
359     ///
360     /// # Examples
361     ///
362     /// ```no_run
363     /// use std::net::UdpSocket;
364     ///
365     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
366     /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
367     /// assert_eq!(socket.write_timeout().unwrap(), None);
368     /// ```
369     #[stable(feature = "socket_timeout", since = "1.4.0")]
370     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
371         self.0.write_timeout()
372     }
373
374     /// Sets the value of the `SO_BROADCAST` option for this socket.
375     ///
376     /// When enabled, this socket is allowed to send packets to a broadcast
377     /// address.
378     ///
379     /// # Examples
380     ///
381     /// ```no_run
382     /// use std::net::UdpSocket;
383     ///
384     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
385     /// socket.set_broadcast(false).expect("set_broadcast call failed");
386     /// ```
387     #[stable(feature = "net2_mutators", since = "1.9.0")]
388     pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
389         self.0.set_broadcast(broadcast)
390     }
391
392     /// Gets the value of the `SO_BROADCAST` option for this socket.
393     ///
394     /// For more information about this option, see [`UdpSocket::set_broadcast`].
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_broadcast(false).expect("set_broadcast call failed");
403     /// assert_eq!(socket.broadcast().unwrap(), false);
404     /// ```
405     #[stable(feature = "net2_mutators", since = "1.9.0")]
406     pub fn broadcast(&self) -> io::Result<bool> {
407         self.0.broadcast()
408     }
409
410     /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
411     ///
412     /// If enabled, multicast packets will be looped back to the local socket.
413     /// Note that this might not have any effect on IPv6 sockets.
414     ///
415     /// # Examples
416     ///
417     /// ```no_run
418     /// use std::net::UdpSocket;
419     ///
420     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
421     /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
422     /// ```
423     #[stable(feature = "net2_mutators", since = "1.9.0")]
424     pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
425         self.0.set_multicast_loop_v4(multicast_loop_v4)
426     }
427
428     /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
429     ///
430     /// For more information about this option, see [`UdpSocket::set_multicast_loop_v4`].
431     ///
432     /// # Examples
433     ///
434     /// ```no_run
435     /// use std::net::UdpSocket;
436     ///
437     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
438     /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
439     /// assert_eq!(socket.multicast_loop_v4().unwrap(), false);
440     /// ```
441     #[stable(feature = "net2_mutators", since = "1.9.0")]
442     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
443         self.0.multicast_loop_v4()
444     }
445
446     /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
447     ///
448     /// Indicates the time-to-live value of outgoing multicast packets for
449     /// this socket. The default value is 1 which means that multicast packets
450     /// don't leave the local network unless explicitly requested.
451     ///
452     /// Note that this might not have any effect on IPv6 sockets.
453     ///
454     /// # Examples
455     ///
456     /// ```no_run
457     /// use std::net::UdpSocket;
458     ///
459     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
460     /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
461     /// ```
462     #[stable(feature = "net2_mutators", since = "1.9.0")]
463     pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
464         self.0.set_multicast_ttl_v4(multicast_ttl_v4)
465     }
466
467     /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
468     ///
469     /// For more information about this option, see [`UdpSocket::set_multicast_ttl_v4`].
470     ///
471     /// # Examples
472     ///
473     /// ```no_run
474     /// use std::net::UdpSocket;
475     ///
476     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
477     /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
478     /// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
479     /// ```
480     #[stable(feature = "net2_mutators", since = "1.9.0")]
481     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
482         self.0.multicast_ttl_v4()
483     }
484
485     /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
486     ///
487     /// Controls whether this socket sees the multicast packets it sends itself.
488     /// Note that this might not have any affect on IPv4 sockets.
489     ///
490     /// # Examples
491     ///
492     /// ```no_run
493     /// use std::net::UdpSocket;
494     ///
495     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
496     /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
497     /// ```
498     #[stable(feature = "net2_mutators", since = "1.9.0")]
499     pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
500         self.0.set_multicast_loop_v6(multicast_loop_v6)
501     }
502
503     /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
504     ///
505     /// For more information about this option, see [`UdpSocket::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 [`UdpSocket::set_ttl`].
542     ///
543     /// # Examples
544     ///
545     /// ```no_run
546     /// use std::net::UdpSocket;
547     ///
548     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
549     /// socket.set_ttl(42).expect("set_ttl call failed");
550     /// assert_eq!(socket.ttl().unwrap(), 42);
551     /// ```
552     #[stable(feature = "net2_mutators", since = "1.9.0")]
553     pub fn ttl(&self) -> io::Result<u32> {
554         self.0.ttl()
555     }
556
557     /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
558     ///
559     /// This function specifies a new multicast group for this socket to join.
560     /// The address must be a valid multicast address, and `interface` is the
561     /// address of the local interface with which the system should join the
562     /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
563     /// interface is chosen by the system.
564     #[stable(feature = "net2_mutators", since = "1.9.0")]
565     pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
566         self.0.join_multicast_v4(multiaddr, interface)
567     }
568
569     /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
570     ///
571     /// This function specifies a new multicast group for this socket to join.
572     /// The address must be a valid multicast address, and `interface` is the
573     /// index of the interface to join/leave (or 0 to indicate any interface).
574     #[stable(feature = "net2_mutators", since = "1.9.0")]
575     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
576         self.0.join_multicast_v6(multiaddr, interface)
577     }
578
579     /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
580     ///
581     /// For more information about this option, see [`UdpSocket::join_multicast_v4`].
582     #[stable(feature = "net2_mutators", since = "1.9.0")]
583     pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
584         self.0.leave_multicast_v4(multiaddr, interface)
585     }
586
587     /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
588     ///
589     /// For more information about this option, see [`UdpSocket::join_multicast_v6`].
590     #[stable(feature = "net2_mutators", since = "1.9.0")]
591     pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
592         self.0.leave_multicast_v6(multiaddr, interface)
593     }
594
595     /// Gets the value of the `SO_ERROR` option on this socket.
596     ///
597     /// This will retrieve the stored error in the underlying socket, clearing
598     /// the field in the process. This can be useful for checking errors between
599     /// calls.
600     ///
601     /// # Examples
602     ///
603     /// ```no_run
604     /// use std::net::UdpSocket;
605     ///
606     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
607     /// match socket.take_error() {
608     ///     Ok(Some(error)) => println!("UdpSocket error: {error:?}"),
609     ///     Ok(None) => println!("No error"),
610     ///     Err(error) => println!("UdpSocket.take_error failed: {error:?}"),
611     /// }
612     /// ```
613     #[stable(feature = "net2_mutators", since = "1.9.0")]
614     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
615         self.0.take_error()
616     }
617
618     /// Connects this UDP socket to a remote address, allowing the `send` and
619     /// `recv` syscalls to be used to send data and also applies filters to only
620     /// receive data from the specified address.
621     ///
622     /// If `addr` yields multiple addresses, `connect` will be attempted with
623     /// each of the addresses until the underlying OS function returns no
624     /// error. Note that usually, a successful `connect` call does not specify
625     /// that there is a remote server listening on the port, rather, such an
626     /// error would only be detected after the first send. If the OS returns an
627     /// error for each of the specified addresses, the error returned from the
628     /// last connection attempt (the last address) is returned.
629     ///
630     /// # Examples
631     ///
632     /// Creates a UDP socket bound to `127.0.0.1:3400` and connect the socket to
633     /// `127.0.0.1:8080`:
634     ///
635     /// ```no_run
636     /// use std::net::UdpSocket;
637     ///
638     /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
639     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
640     /// ```
641     ///
642     /// Unlike in the TCP case, passing an array of addresses to the `connect`
643     /// function of a UDP socket is not a useful thing to do: The OS will be
644     /// unable to determine whether something is listening on the remote
645     /// address without the application sending data.
646     #[stable(feature = "net2_mutators", since = "1.9.0")]
647     pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
648         super::each_addr(addr, |addr| self.0.connect(addr))
649     }
650
651     /// Sends data on the socket to the remote address to which it is connected.
652     ///
653     /// [`UdpSocket::connect`] will connect this socket to a remote address. This
654     /// method will fail if the socket is not connected.
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     /// [`UdpSocket::connect`] will connect this socket to a remote address. This
678     /// method will fail if the socket is not connected.
679     ///
680     /// # Examples
681     ///
682     /// ```no_run
683     /// use std::net::UdpSocket;
684     ///
685     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
686     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
687     /// let mut buf = [0; 10];
688     /// match socket.recv(&mut buf) {
689     ///     Ok(received) => println!("received {received} bytes {:?}", &buf[..received]),
690     ///     Err(e) => println!("recv function failed: {e:?}"),
691     /// }
692     /// ```
693     #[stable(feature = "net2_mutators", since = "1.9.0")]
694     pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
695         self.0.recv(buf)
696     }
697
698     /// Receives single datagram on the socket from the remote address to which it is
699     /// connected, without removing the message from input queue. On success, returns
700     /// the number of bytes peeked.
701     ///
702     /// The function must be called with valid byte array `buf` of sufficient size to
703     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
704     /// excess bytes may be discarded.
705     ///
706     /// Successive calls return the same data. This is accomplished by passing
707     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
708     ///
709     /// Do not use this function to implement busy waiting, instead use `libc::poll` to
710     /// synchronize IO events on one or more sockets.
711     ///
712     /// [`UdpSocket::connect`] will connect this socket to a remote address. This
713     /// method will fail if the socket is not connected.
714     ///
715     /// # Errors
716     ///
717     /// This method will fail if the socket is not connected. The `connect` method
718     /// will connect this socket to a remote address.
719     ///
720     /// # Examples
721     ///
722     /// ```no_run
723     /// use std::net::UdpSocket;
724     ///
725     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
726     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
727     /// let mut buf = [0; 10];
728     /// match socket.peek(&mut buf) {
729     ///     Ok(received) => println!("received {received} bytes"),
730     ///     Err(e) => println!("peek function failed: {e:?}"),
731     /// }
732     /// ```
733     #[stable(feature = "peek", since = "1.18.0")]
734     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
735         self.0.peek(buf)
736     }
737
738     /// Moves this UDP socket into or out of nonblocking mode.
739     ///
740     /// This will result in `recv`, `recv_from`, `send`, and `send_to`
741     /// operations becoming nonblocking, i.e., immediately returning from their
742     /// calls. If the IO operation is successful, `Ok` is returned and no
743     /// further action is required. If the IO operation could not be completed
744     /// and needs to be retried, an error with kind
745     /// [`io::ErrorKind::WouldBlock`] is returned.
746     ///
747     /// On Unix platforms, calling this method corresponds to calling `fcntl`
748     /// `FIONBIO`. On Windows calling this method corresponds to calling
749     /// `ioctlsocket` `FIONBIO`.
750     ///
751     /// # Examples
752     ///
753     /// Creates a UDP socket bound to `127.0.0.1:7878` and read bytes in
754     /// nonblocking mode:
755     ///
756     /// ```no_run
757     /// use std::io;
758     /// use std::net::UdpSocket;
759     ///
760     /// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
761     /// socket.set_nonblocking(true).unwrap();
762     ///
763     /// # fn wait_for_fd() { unimplemented!() }
764     /// let mut buf = [0; 10];
765     /// let (num_bytes_read, _) = loop {
766     ///     match socket.recv_from(&mut buf) {
767     ///         Ok(n) => break n,
768     ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
769     ///             // wait until network socket is ready, typically implemented
770     ///             // via platform-specific APIs such as epoll or IOCP
771     ///             wait_for_fd();
772     ///         }
773     ///         Err(e) => panic!("encountered IO error: {e}"),
774     ///     }
775     /// };
776     /// println!("bytes: {:?}", &buf[..num_bytes_read]);
777     /// ```
778     #[stable(feature = "net2_mutators", since = "1.9.0")]
779     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
780         self.0.set_nonblocking(nonblocking)
781     }
782 }
783
784 // In addition to the `impl`s here, `UdpSocket` also has `impl`s for
785 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
786 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
787 // `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
788 // `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
789
790 impl AsInner<net_imp::UdpSocket> for UdpSocket {
791     fn as_inner(&self) -> &net_imp::UdpSocket {
792         &self.0
793     }
794 }
795
796 impl FromInner<net_imp::UdpSocket> for UdpSocket {
797     fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket {
798         UdpSocket(inner)
799     }
800 }
801
802 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
803     fn into_inner(self) -> net_imp::UdpSocket {
804         self.0
805     }
806 }
807
808 #[stable(feature = "rust1", since = "1.0.0")]
809 impl fmt::Debug for UdpSocket {
810     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
811         self.0.fmt(f)
812     }
813 }