]> git.lizzy.rs Git - rust.git/blob - library/std/src/net/udp.rs
Rollup merge of #92921 - dtolnay:printernew, r=wesleywiser
[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 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 => Err(Error::new_const(ErrorKind::InvalidInput, &"no addresses to send data to")),
179         }
180     }
181
182     /// Returns the socket address of the remote peer this socket was connected to.
183     ///
184     /// # Examples
185     ///
186     /// ```no_run
187     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
188     ///
189     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
190     /// socket.connect("192.168.0.1:41203").expect("couldn't connect to address");
191     /// assert_eq!(socket.peer_addr().unwrap(),
192     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 41203)));
193     /// ```
194     ///
195     /// If the socket isn't connected, it will return a [`NotConnected`] error.
196     ///
197     /// [`NotConnected`]: io::ErrorKind::NotConnected
198     ///
199     /// ```no_run
200     /// use std::net::UdpSocket;
201     ///
202     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
203     /// assert_eq!(socket.peer_addr().unwrap_err().kind(),
204     ///            std::io::ErrorKind::NotConnected);
205     /// ```
206     #[stable(feature = "udp_peer_addr", since = "1.40.0")]
207     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
208         self.0.peer_addr()
209     }
210
211     /// Returns the socket address that this socket was created from.
212     ///
213     /// # Examples
214     ///
215     /// ```no_run
216     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
217     ///
218     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
219     /// assert_eq!(socket.local_addr().unwrap(),
220     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)));
221     /// ```
222     #[stable(feature = "rust1", since = "1.0.0")]
223     pub fn local_addr(&self) -> io::Result<SocketAddr> {
224         self.0.socket_addr()
225     }
226
227     /// Creates a new independently owned handle to the underlying socket.
228     ///
229     /// The returned `UdpSocket` is a reference to the same socket that this
230     /// object references. Both handles will read and write the same port, and
231     /// options set on one socket will be propagated to the other.
232     ///
233     /// # Examples
234     ///
235     /// ```no_run
236     /// use std::net::UdpSocket;
237     ///
238     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
239     /// let socket_clone = socket.try_clone().expect("couldn't clone the socket");
240     /// ```
241     #[stable(feature = "rust1", since = "1.0.0")]
242     pub fn try_clone(&self) -> io::Result<UdpSocket> {
243         self.0.duplicate().map(UdpSocket)
244     }
245
246     /// Sets the read timeout to the timeout specified.
247     ///
248     /// If the value specified is [`None`], then [`read`] calls will block
249     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
250     /// passed to this method.
251     ///
252     /// # Platform-specific behavior
253     ///
254     /// Platforms may return a different error code whenever a read times out as
255     /// a result of setting this option. For example Unix typically returns an
256     /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
257     ///
258     /// [`read`]: io::Read::read
259     /// [`WouldBlock`]: io::ErrorKind::WouldBlock
260     /// [`TimedOut`]: io::ErrorKind::TimedOut
261     ///
262     /// # Examples
263     ///
264     /// ```no_run
265     /// use std::net::UdpSocket;
266     ///
267     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
268     /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
269     /// ```
270     ///
271     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
272     /// method:
273     ///
274     /// ```no_run
275     /// use std::io;
276     /// use std::net::UdpSocket;
277     /// use std::time::Duration;
278     ///
279     /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
280     /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
281     /// let err = result.unwrap_err();
282     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
283     /// ```
284     #[stable(feature = "socket_timeout", since = "1.4.0")]
285     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
286         self.0.set_read_timeout(dur)
287     }
288
289     /// Sets the write timeout to the timeout specified.
290     ///
291     /// If the value specified is [`None`], then [`write`] calls will block
292     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
293     /// passed to this method.
294     ///
295     /// # Platform-specific behavior
296     ///
297     /// Platforms may return a different error code whenever a write times out
298     /// as a result of setting this option. For example Unix typically returns
299     /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
300     ///
301     /// [`write`]: io::Write::write
302     /// [`WouldBlock`]: io::ErrorKind::WouldBlock
303     /// [`TimedOut`]: io::ErrorKind::TimedOut
304     ///
305     /// # Examples
306     ///
307     /// ```no_run
308     /// use std::net::UdpSocket;
309     ///
310     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
311     /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
312     /// ```
313     ///
314     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
315     /// method:
316     ///
317     /// ```no_run
318     /// use std::io;
319     /// use std::net::UdpSocket;
320     /// use std::time::Duration;
321     ///
322     /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
323     /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
324     /// let err = result.unwrap_err();
325     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
326     /// ```
327     #[stable(feature = "socket_timeout", since = "1.4.0")]
328     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
329         self.0.set_write_timeout(dur)
330     }
331
332     /// Returns the read timeout of this socket.
333     ///
334     /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
335     ///
336     /// [`read`]: io::Read::read
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_read_timeout(None).expect("set_read_timeout call failed");
345     /// assert_eq!(socket.read_timeout().unwrap(), None);
346     /// ```
347     #[stable(feature = "socket_timeout", since = "1.4.0")]
348     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
349         self.0.read_timeout()
350     }
351
352     /// Returns the write timeout of this socket.
353     ///
354     /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
355     ///
356     /// [`write`]: io::Write::write
357     ///
358     /// # Examples
359     ///
360     /// ```no_run
361     /// use std::net::UdpSocket;
362     ///
363     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
364     /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
365     /// assert_eq!(socket.write_timeout().unwrap(), None);
366     /// ```
367     #[stable(feature = "socket_timeout", since = "1.4.0")]
368     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
369         self.0.write_timeout()
370     }
371
372     /// Sets the value of the `SO_BROADCAST` option for this socket.
373     ///
374     /// When enabled, this socket is allowed to send packets to a broadcast
375     /// address.
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     /// ```
385     #[stable(feature = "net2_mutators", since = "1.9.0")]
386     pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
387         self.0.set_broadcast(broadcast)
388     }
389
390     /// Gets the value of the `SO_BROADCAST` option for this socket.
391     ///
392     /// For more information about this option, see [`UdpSocket::set_broadcast`].
393     ///
394     /// # Examples
395     ///
396     /// ```no_run
397     /// use std::net::UdpSocket;
398     ///
399     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
400     /// socket.set_broadcast(false).expect("set_broadcast call failed");
401     /// assert_eq!(socket.broadcast().unwrap(), false);
402     /// ```
403     #[stable(feature = "net2_mutators", since = "1.9.0")]
404     pub fn broadcast(&self) -> io::Result<bool> {
405         self.0.broadcast()
406     }
407
408     /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
409     ///
410     /// If enabled, multicast packets will be looped back to the local socket.
411     /// Note that this might not have any effect on IPv6 sockets.
412     ///
413     /// # Examples
414     ///
415     /// ```no_run
416     /// use std::net::UdpSocket;
417     ///
418     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
419     /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
420     /// ```
421     #[stable(feature = "net2_mutators", since = "1.9.0")]
422     pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
423         self.0.set_multicast_loop_v4(multicast_loop_v4)
424     }
425
426     /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
427     ///
428     /// For more information about this option, see [`UdpSocket::set_multicast_loop_v4`].
429     ///
430     /// # Examples
431     ///
432     /// ```no_run
433     /// use std::net::UdpSocket;
434     ///
435     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
436     /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
437     /// assert_eq!(socket.multicast_loop_v4().unwrap(), false);
438     /// ```
439     #[stable(feature = "net2_mutators", since = "1.9.0")]
440     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
441         self.0.multicast_loop_v4()
442     }
443
444     /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
445     ///
446     /// Indicates the time-to-live value of outgoing multicast packets for
447     /// this socket. The default value is 1 which means that multicast packets
448     /// don't leave the local network unless explicitly requested.
449     ///
450     /// Note that this might not have any effect on IPv6 sockets.
451     ///
452     /// # Examples
453     ///
454     /// ```no_run
455     /// use std::net::UdpSocket;
456     ///
457     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
458     /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
459     /// ```
460     #[stable(feature = "net2_mutators", since = "1.9.0")]
461     pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
462         self.0.set_multicast_ttl_v4(multicast_ttl_v4)
463     }
464
465     /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
466     ///
467     /// For more information about this option, see [`UdpSocket::set_multicast_ttl_v4`].
468     ///
469     /// # Examples
470     ///
471     /// ```no_run
472     /// use std::net::UdpSocket;
473     ///
474     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
475     /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
476     /// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
477     /// ```
478     #[stable(feature = "net2_mutators", since = "1.9.0")]
479     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
480         self.0.multicast_ttl_v4()
481     }
482
483     /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
484     ///
485     /// Controls whether this socket sees the multicast packets it sends itself.
486     /// Note that this might not have any affect on IPv4 sockets.
487     ///
488     /// # Examples
489     ///
490     /// ```no_run
491     /// use std::net::UdpSocket;
492     ///
493     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
494     /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
495     /// ```
496     #[stable(feature = "net2_mutators", since = "1.9.0")]
497     pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
498         self.0.set_multicast_loop_v6(multicast_loop_v6)
499     }
500
501     /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
502     ///
503     /// For more information about this option, see [`UdpSocket::set_multicast_loop_v6`].
504     ///
505     /// # Examples
506     ///
507     /// ```no_run
508     /// use std::net::UdpSocket;
509     ///
510     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
511     /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
512     /// assert_eq!(socket.multicast_loop_v6().unwrap(), false);
513     /// ```
514     #[stable(feature = "net2_mutators", since = "1.9.0")]
515     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
516         self.0.multicast_loop_v6()
517     }
518
519     /// Sets the value for the `IP_TTL` option on this socket.
520     ///
521     /// This value sets the time-to-live field that is used in every packet sent
522     /// from this socket.
523     ///
524     /// # Examples
525     ///
526     /// ```no_run
527     /// use std::net::UdpSocket;
528     ///
529     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
530     /// socket.set_ttl(42).expect("set_ttl call failed");
531     /// ```
532     #[stable(feature = "net2_mutators", since = "1.9.0")]
533     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
534         self.0.set_ttl(ttl)
535     }
536
537     /// Gets the value of the `IP_TTL` option for this socket.
538     ///
539     /// For more information about this option, see [`UdpSocket::set_ttl`].
540     ///
541     /// # Examples
542     ///
543     /// ```no_run
544     /// use std::net::UdpSocket;
545     ///
546     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
547     /// socket.set_ttl(42).expect("set_ttl call failed");
548     /// assert_eq!(socket.ttl().unwrap(), 42);
549     /// ```
550     #[stable(feature = "net2_mutators", since = "1.9.0")]
551     pub fn ttl(&self) -> io::Result<u32> {
552         self.0.ttl()
553     }
554
555     /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
556     ///
557     /// This function specifies a new multicast group for this socket to join.
558     /// The address must be a valid multicast address, and `interface` is the
559     /// address of the local interface with which the system should join the
560     /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
561     /// interface is chosen by the system.
562     #[stable(feature = "net2_mutators", since = "1.9.0")]
563     pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
564         self.0.join_multicast_v4(multiaddr, interface)
565     }
566
567     /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
568     ///
569     /// This function specifies a new multicast group for this socket to join.
570     /// The address must be a valid multicast address, and `interface` is the
571     /// index of the interface to join/leave (or 0 to indicate any interface).
572     #[stable(feature = "net2_mutators", since = "1.9.0")]
573     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
574         self.0.join_multicast_v6(multiaddr, interface)
575     }
576
577     /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
578     ///
579     /// For more information about this option, see [`UdpSocket::join_multicast_v4`].
580     #[stable(feature = "net2_mutators", since = "1.9.0")]
581     pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
582         self.0.leave_multicast_v4(multiaddr, interface)
583     }
584
585     /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
586     ///
587     /// For more information about this option, see [`UdpSocket::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     /// [`UdpSocket::connect`] will connect this socket to a remote address. This
652     /// method will fail if the socket is not connected.
653     ///
654     /// # Examples
655     ///
656     /// ```no_run
657     /// use std::net::UdpSocket;
658     ///
659     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
660     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
661     /// socket.send(&[0, 1, 2]).expect("couldn't send message");
662     /// ```
663     #[stable(feature = "net2_mutators", since = "1.9.0")]
664     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
665         self.0.send(buf)
666     }
667
668     /// Receives a single datagram message on the socket from the remote address to
669     /// which it is connected. On success, returns the number of bytes read.
670     ///
671     /// The function must be called with valid byte array `buf` of sufficient size to
672     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
673     /// excess bytes may be discarded.
674     ///
675     /// [`UdpSocket::connect`] will connect this socket to a remote address. This
676     /// method will fail if the socket is not connected.
677     ///
678     /// # Examples
679     ///
680     /// ```no_run
681     /// use std::net::UdpSocket;
682     ///
683     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
684     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
685     /// let mut buf = [0; 10];
686     /// match socket.recv(&mut buf) {
687     ///     Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]),
688     ///     Err(e) => println!("recv function failed: {:?}", e),
689     /// }
690     /// ```
691     #[stable(feature = "net2_mutators", since = "1.9.0")]
692     pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
693         self.0.recv(buf)
694     }
695
696     /// Receives single datagram on the socket from the remote address to which it is
697     /// connected, without removing the message from input queue. On success, returns
698     /// the number of bytes peeked.
699     ///
700     /// The function must be called with valid byte array `buf` of sufficient size to
701     /// hold the message bytes. If a message is too long to fit in the supplied buffer,
702     /// excess bytes may be discarded.
703     ///
704     /// Successive calls return the same data. This is accomplished by passing
705     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
706     ///
707     /// Do not use this function to implement busy waiting, instead use `libc::poll` to
708     /// synchronize IO events on one or more sockets.
709     ///
710     /// [`UdpSocket::connect`] will connect this socket to a remote address. This
711     /// method will fail if the socket is not connected.
712     ///
713     /// # Errors
714     ///
715     /// This method will fail if the socket is not connected. The `connect` method
716     /// will connect this socket to a remote address.
717     ///
718     /// # Examples
719     ///
720     /// ```no_run
721     /// use std::net::UdpSocket;
722     ///
723     /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
724     /// socket.connect("127.0.0.1:8080").expect("connect function failed");
725     /// let mut buf = [0; 10];
726     /// match socket.peek(&mut buf) {
727     ///     Ok(received) => println!("received {} bytes", received),
728     ///     Err(e) => println!("peek function failed: {:?}", e),
729     /// }
730     /// ```
731     #[stable(feature = "peek", since = "1.18.0")]
732     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
733         self.0.peek(buf)
734     }
735
736     /// Moves this UDP socket into or out of nonblocking mode.
737     ///
738     /// This will result in `recv`, `recv_from`, `send`, and `send_to`
739     /// operations becoming nonblocking, i.e., immediately returning from their
740     /// calls. If the IO operation is successful, `Ok` is returned and no
741     /// further action is required. If the IO operation could not be completed
742     /// and needs to be retried, an error with kind
743     /// [`io::ErrorKind::WouldBlock`] is returned.
744     ///
745     /// On Unix platforms, calling this method corresponds to calling `fcntl`
746     /// `FIONBIO`. On Windows calling this method corresponds to calling
747     /// `ioctlsocket` `FIONBIO`.
748     ///
749     /// # Examples
750     ///
751     /// Creates a UDP socket bound to `127.0.0.1:7878` and read bytes in
752     /// nonblocking mode:
753     ///
754     /// ```no_run
755     /// use std::io;
756     /// use std::net::UdpSocket;
757     ///
758     /// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
759     /// socket.set_nonblocking(true).unwrap();
760     ///
761     /// # fn wait_for_fd() { unimplemented!() }
762     /// let mut buf = [0; 10];
763     /// let (num_bytes_read, _) = loop {
764     ///     match socket.recv_from(&mut buf) {
765     ///         Ok(n) => break n,
766     ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
767     ///             // wait until network socket is ready, typically implemented
768     ///             // via platform-specific APIs such as epoll or IOCP
769     ///             wait_for_fd();
770     ///         }
771     ///         Err(e) => panic!("encountered IO error: {}", e),
772     ///     }
773     /// };
774     /// println!("bytes: {:?}", &buf[..num_bytes_read]);
775     /// ```
776     #[stable(feature = "net2_mutators", since = "1.9.0")]
777     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
778         self.0.set_nonblocking(nonblocking)
779     }
780 }
781
782 // In addition to the `impl`s here, `UdpSocket` also has `impl`s for
783 // `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
784 // `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
785 // `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
786 // `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
787
788 impl AsInner<net_imp::UdpSocket> for UdpSocket {
789     fn as_inner(&self) -> &net_imp::UdpSocket {
790         &self.0
791     }
792 }
793
794 impl FromInner<net_imp::UdpSocket> for UdpSocket {
795     fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket {
796         UdpSocket(inner)
797     }
798 }
799
800 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
801     fn into_inner(self) -> net_imp::UdpSocket {
802         self.0
803     }
804 }
805
806 #[stable(feature = "rust1", since = "1.0.0")]
807 impl fmt::Debug for UdpSocket {
808     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
809         self.0.fmt(f)
810     }
811 }