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    /// # Examples
487    ///
488    /// ```no_run
489    /// use std::net::UdpSocket;
490    ///
491    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
492    /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 should succeed");
493    /// ```
494    #[stable(feature = "net2_mutators", since = "1.9.0")]
495    pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
496        self.0.set_multicast_ttl_v4(multicast_ttl_v4)
497    }
498
499    /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
500    ///
501    /// For more information about this option, see [`UdpSocket::set_multicast_ttl_v4`].
502    ///
503    /// # Examples
504    ///
505    /// ```no_run
506    /// use std::net::UdpSocket;
507    ///
508    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
509    /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 should succeed");
510    /// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
511    /// ```
512    #[stable(feature = "net2_mutators", since = "1.9.0")]
513    pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
514        self.0.multicast_ttl_v4()
515    }
516
517    /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
518    ///
519    /// Controls whether this socket sees the multicast packets it sends itself.
520    /// Note that this might not have any affect on IPv4 sockets.
521    ///
522    /// # Examples
523    ///
524    /// ```no_run
525    /// use std::net::UdpSocket;
526    ///
527    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
528    /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 should succeed");
529    /// ```
530    #[stable(feature = "net2_mutators", since = "1.9.0")]
531    pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
532        self.0.set_multicast_loop_v6(multicast_loop_v6)
533    }
534
535    /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
536    ///
537    /// For more information about this option, see [`UdpSocket::set_multicast_loop_v6`].
538    ///
539    /// # Examples
540    ///
541    /// ```no_run
542    /// use std::net::UdpSocket;
543    ///
544    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
545    /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 should succeed");
546    /// assert_eq!(socket.multicast_loop_v6().unwrap(), false);
547    /// ```
548    #[stable(feature = "net2_mutators", since = "1.9.0")]
549    pub fn multicast_loop_v6(&self) -> io::Result<bool> {
550        self.0.multicast_loop_v6()
551    }
552
553    /// Sets the value for the `IP_TTL` option on this socket.
554    ///
555    /// This value sets the time-to-live field that is used in every packet sent
556    /// from this socket.
557    ///
558    /// # Examples
559    ///
560    /// ```no_run
561    /// use std::net::UdpSocket;
562    ///
563    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
564    /// socket.set_ttl(42).expect("set_ttl should succeed");
565    /// ```
566    #[stable(feature = "net2_mutators", since = "1.9.0")]
567    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
568        self.0.set_ttl(ttl)
569    }
570
571    /// Gets the value of the `IP_TTL` option for this socket.
572    ///
573    /// For more information about this option, see [`UdpSocket::set_ttl`].
574    ///
575    /// # Examples
576    ///
577    /// ```no_run
578    /// use std::net::UdpSocket;
579    ///
580    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
581    /// socket.set_ttl(42).expect("set_ttl should succeed");
582    /// assert_eq!(socket.ttl().unwrap(), 42);
583    /// ```
584    #[stable(feature = "net2_mutators", since = "1.9.0")]
585    pub fn ttl(&self) -> io::Result<u32> {
586        self.0.ttl()
587    }
588
589    /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
590    ///
591    /// This function specifies a new multicast group for this socket to join.
592    /// The address must be a valid multicast address, and `interface` is the
593    /// address of the local interface with which the system should join the
594    /// multicast group. If it's equal to [`UNSPECIFIED`](Ipv4Addr::UNSPECIFIED)
595    /// then an appropriate interface is chosen by the system.
596    #[stable(feature = "net2_mutators", since = "1.9.0")]
597    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
598        self.0.join_multicast_v4(multiaddr, interface)
599    }
600
601    /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
602    ///
603    /// This function specifies a new multicast group for this socket to join.
604    /// The address must be a valid multicast address, and `interface` is the
605    /// index of the interface to join/leave (or 0 to indicate any interface).
606    #[stable(feature = "net2_mutators", since = "1.9.0")]
607    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
608        self.0.join_multicast_v6(multiaddr, interface)
609    }
610
611    /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
612    ///
613    /// For more information about this option, see [`UdpSocket::join_multicast_v4`].
614    #[stable(feature = "net2_mutators", since = "1.9.0")]
615    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
616        self.0.leave_multicast_v4(multiaddr, interface)
617    }
618
619    /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
620    ///
621    /// For more information about this option, see [`UdpSocket::join_multicast_v6`].
622    #[stable(feature = "net2_mutators", since = "1.9.0")]
623    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
624        self.0.leave_multicast_v6(multiaddr, interface)
625    }
626
627    /// Gets the value of the `SO_ERROR` option on this socket.
628    ///
629    /// This will retrieve the stored error in the underlying socket, clearing
630    /// the field in the process. This can be useful for checking errors between
631    /// calls.
632    ///
633    /// # Examples
634    ///
635    /// ```no_run
636    /// use std::net::UdpSocket;
637    ///
638    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
639    /// match socket.take_error() {
640    ///     Ok(Some(error)) => println!("UdpSocket error: {error:?}"),
641    ///     Ok(None) => println!("No error"),
642    ///     Err(error) => println!("UdpSocket.take_error failed: {error:?}"),
643    /// }
644    /// ```
645    #[stable(feature = "net2_mutators", since = "1.9.0")]
646    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
647        self.0.take_error()
648    }
649
650    /// Connects this UDP socket to a remote address, allowing the `send` and
651    /// `recv` syscalls to be used to send data and also applies filters to only
652    /// receive data from the specified address.
653    ///
654    /// If `addr` yields multiple addresses, `connect` will be attempted with
655    /// each of the addresses until the underlying OS function returns no
656    /// error. Note that usually, a successful `connect` call does not specify
657    /// that there is a remote server listening on the port, rather, such an
658    /// error would only be detected after the first send. If the OS returns an
659    /// error for each of the specified addresses, the error returned from the
660    /// last connection attempt (the last address) is returned.
661    ///
662    /// # Examples
663    ///
664    /// Creates a UDP socket bound to `127.0.0.1:3400` and connect the socket to
665    /// `127.0.0.1:8080`:
666    ///
667    /// ```no_run
668    /// use std::net::UdpSocket;
669    ///
670    /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("bind should succeed");
671    /// socket.connect("127.0.0.1:8080").expect("connect should succeed");
672    /// ```
673    ///
674    /// Unlike in the TCP case, passing an array of addresses to the `connect`
675    /// function of a UDP socket is not a useful thing to do: The OS will be
676    /// unable to determine whether something is listening on the remote
677    /// address without the application sending data.
678    ///
679    /// If your first `connect` is to a loopback address, subsequent
680    /// `connect`s to non-loopback addresses might fail, depending
681    /// on the platform.
682    #[stable(feature = "net2_mutators", since = "1.9.0")]
683    pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
684        self.0.connect(addr)
685    }
686
687    /// Sends data on the socket to the remote address to which it is connected.
688    /// On success, returns the number of bytes written. Note that the operating
689    /// system may refuse buffers larger than 65507. However, partial writes are
690    /// not possible until buffer sizes above `i32::MAX`.
691    ///
692    /// [`UdpSocket::connect`] will connect this socket to a remote address. This
693    /// method will fail if the socket is not connected.
694    ///
695    /// # Examples
696    ///
697    /// ```no_run
698    /// use std::net::UdpSocket;
699    ///
700    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
701    /// socket.connect("127.0.0.1:8080").expect("connect should succeed");
702    /// socket.send(&[0, 1, 2]).expect("send should succeed");
703    /// ```
704    #[stable(feature = "net2_mutators", since = "1.9.0")]
705    pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
706        self.0.send(buf)
707    }
708
709    /// Receives a single datagram message on the socket from the remote address to
710    /// which it is connected. On success, returns the number of bytes read.
711    ///
712    /// The function must be called with valid byte array `buf` of sufficient size to
713    /// hold the message bytes. If a message is too long to fit in the supplied buffer,
714    /// excess bytes may be discarded.
715    ///
716    /// [`UdpSocket::connect`] will connect this socket to a remote address. This
717    /// method will fail if the socket is not connected.
718    ///
719    /// Refer to the platform-specific documentation on this function; it is considered
720    /// correct for its behavior to differ from [`UdpSocket::recv_from`] if the underlying
721    /// system call does so.
722    ///
723    /// # Examples
724    ///
725    /// ```no_run
726    /// use std::net::UdpSocket;
727    ///
728    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
729    /// socket.connect("127.0.0.1:8080").expect("connect should succeed");
730    /// let mut buf = [0; 10];
731    /// match socket.recv(&mut buf) {
732    ///     Ok(received) => println!("received {received} bytes {:?}", &buf[..received]),
733    ///     Err(e) => println!("recv function failed: {e:?}"),
734    /// }
735    /// ```
736    #[stable(feature = "net2_mutators", since = "1.9.0")]
737    pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
738        self.0.recv(buf)
739    }
740
741    /// Receives single datagram on the socket from the remote address to which it is
742    /// connected, without removing the message from input queue. On success, returns
743    /// the number of bytes peeked.
744    ///
745    /// The function must be called with valid byte array `buf` of sufficient size to
746    /// hold the message bytes. If a message is too long to fit in the supplied buffer,
747    /// excess bytes may be discarded.
748    ///
749    /// Successive calls return the same data. This is accomplished by passing
750    /// `MSG_PEEK` as a flag to the underlying `recv` system call.
751    ///
752    /// Do not use this function to implement busy waiting, instead use `libc::poll` to
753    /// synchronize IO events on one or more sockets.
754    ///
755    /// [`UdpSocket::connect`] will connect this socket to a remote address. This
756    /// method will fail if the socket is not connected.
757    ///
758    /// # Errors
759    ///
760    /// This method will fail if the socket is not connected. The `connect` method
761    /// will connect this socket to a remote address.
762    ///
763    /// # Examples
764    ///
765    /// ```no_run
766    /// use std::net::UdpSocket;
767    ///
768    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
769    /// socket.connect("127.0.0.1:8080").expect("connect should succeed");
770    /// let mut buf = [0; 10];
771    /// match socket.peek(&mut buf) {
772    ///     Ok(received) => println!("received {received} bytes"),
773    ///     Err(e) => println!("peek function failed: {e:?}"),
774    /// }
775    /// ```
776    #[stable(feature = "peek", since = "1.18.0")]
777    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
778        self.0.peek(buf)
779    }
780
781    /// Moves this UDP socket into or out of nonblocking mode.
782    ///
783    /// This will result in `recv`, `recv_from`, `send`, and `send_to` system
784    /// operations becoming nonblocking, i.e., immediately returning from their
785    /// calls. If the IO operation is successful, `Ok` is returned and no
786    /// further action is required. If the IO operation could not be completed
787    /// and needs to be retried, an error with kind
788    /// [`io::ErrorKind::WouldBlock`] is returned.
789    ///
790    /// On most Unix platforms, calling this method corresponds to calling `ioctl`
791    /// `FIONBIO`. On Windows, calling this method corresponds to calling
792    /// `ioctlsocket` `FIONBIO`.
793    ///
794    /// # Examples
795    ///
796    /// Creates a UDP socket bound to `127.0.0.1:7878` and read bytes in
797    /// nonblocking mode:
798    ///
799    /// ```no_run
800    /// use std::io;
801    /// use std::net::UdpSocket;
802    ///
803    /// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
804    /// socket.set_nonblocking(true).unwrap();
805    ///
806    /// # fn wait_for_fd() { unimplemented!() }
807    /// let mut buf = [0; 10];
808    /// let (num_bytes_read, _) = loop {
809    ///     match socket.recv_from(&mut buf) {
810    ///         Ok(n) => break n,
811    ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
812    ///             // wait until network socket is ready, typically implemented
813    ///             // via platform-specific APIs such as epoll or IOCP
814    ///             wait_for_fd();
815    ///         }
816    ///         Err(e) => panic!("encountered IO error: {e}"),
817    ///     }
818    /// };
819    /// println!("bytes: {:?}", &buf[..num_bytes_read]);
820    /// ```
821    #[stable(feature = "net2_mutators", since = "1.9.0")]
822    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
823        self.0.set_nonblocking(nonblocking)
824    }
825}
826
827// In addition to the `impl`s here, `UdpSocket` also has `impl`s for
828// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
829// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
830// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
831// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
832
833impl AsInner<net_imp::UdpSocket> for UdpSocket {
834    #[inline]
835    fn as_inner(&self) -> &net_imp::UdpSocket {
836        &self.0
837    }
838}
839
840impl FromInner<net_imp::UdpSocket> for UdpSocket {
841    fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket {
842        UdpSocket(inner)
843    }
844}
845
846impl IntoInner<net_imp::UdpSocket> for UdpSocket {
847    fn into_inner(self) -> net_imp::UdpSocket {
848        self.0
849    }
850}
851
852#[stable(feature = "rust1", since = "1.0.0")]
853impl fmt::Debug for UdpSocket {
854    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
855        self.0.fmt(f)
856    }
857}