Skip to main content

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