std/net/
udp.rs

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