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    /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket.
593    ///
594    /// This value sets the unicast hop limit field that is used in every packet
595    /// sent from this socket.
596    ///
597    /// # Examples
598    ///
599    /// ```no_run
600    /// #![feature(ipv6_hop_limit)]
601    /// use std::net::UdpSocket;
602    ///
603    /// let socket = UdpSocket::bind("[::1]:12345").expect("couldn't bind to address");
604    /// socket.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
605    /// ```
606    #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
607    pub fn set_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
608        self.0.set_hop_limit_v6(limit)
609    }
610
611    /// Gets the value of the `IPV6_UNICAST_HOPS` option on this socket.
612    ///
613    /// For more information about this option, see [`UdpSocket::set_hop_limit_v6`].
614    ///
615    /// # Examples
616    ///
617    /// ```no_run
618    /// #![feature(ipv6_hop_limit)]
619    /// use std::net::UdpSocket;
620    ///
621    /// let socket = UdpSocket::bind("[::1]:12345").expect("couldn't bind to address");
622    /// socket.set_hop_limit_v6(88).expect("set_hop_limit_v6 call failed");
623    /// assert_eq!(socket.hop_limit_v6().unwrap(), 88);
624    /// ```
625    #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
626    pub fn hop_limit_v6(&self) -> io::Result<u8> {
627        self.0.hop_limit_v6()
628    }
629
630    /// Sets the value for the `IPV6_MULTICAST_HOPS` option on this socket.
631    ///
632    /// This value sets the hop limit field for outgoing multicast packets
633    /// sent from this socket.
634    ///
635    /// # Examples
636    ///
637    /// ```no_run
638    /// #![feature(ipv6_hop_limit)]
639    /// use std::net::UdpSocket;
640    ///
641    /// let socket = UdpSocket::bind("[::1]:12345").expect("couldn't bind to address");
642    /// socket.set_multicast_hop_limit_v6(88).expect("set_multicast_hop_limit_v6 call failed");
643    /// ```
644    #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
645    pub fn set_multicast_hop_limit_v6(&self, limit: u8) -> io::Result<()> {
646        self.0.set_multicast_hop_limit_v6(limit)
647    }
648
649    /// Gets the value of the `IPV6_MULTICAST_HOPS` option on this socket.
650    ///
651    /// For more information about this option, see [`UdpSocket::set_multicast_hop_limit_v6`].
652    ///
653    /// # Examples
654    ///
655    /// ```no_run
656    /// #![feature(ipv6_hop_limit)]
657    /// use std::net::UdpSocket;
658    ///
659    /// let socket = UdpSocket::bind("[::1]:12345").expect("couldn't bind to address");
660    /// socket.set_multicast_hop_limit_v6(88).expect("set_multicast_hop_limit_v6 call failed");
661    /// assert_eq!(socket.multicast_hop_limit_v6().unwrap(), 88);
662    /// ```
663    #[unstable(feature = "ipv6_hop_limit", issue = "139166")]
664    pub fn multicast_hop_limit_v6(&self) -> io::Result<u8> {
665        self.0.multicast_hop_limit_v6()
666    }
667
668    /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
669    ///
670    /// This function specifies a new multicast group for this socket to join.
671    /// The address must be a valid multicast address, and `interface` is the
672    /// address of the local interface with which the system should join the
673    /// multicast group. If it's equal to [`UNSPECIFIED`](Ipv4Addr::UNSPECIFIED)
674    /// then an appropriate interface is chosen by the system.
675    #[stable(feature = "net2_mutators", since = "1.9.0")]
676    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
677        self.0.join_multicast_v4(multiaddr, interface)
678    }
679
680    /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
681    ///
682    /// This function specifies a new multicast group for this socket to join.
683    /// The address must be a valid multicast address, and `interface` is the
684    /// index of the interface to join/leave (or 0 to indicate any interface).
685    #[stable(feature = "net2_mutators", since = "1.9.0")]
686    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
687        self.0.join_multicast_v6(multiaddr, interface)
688    }
689
690    /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
691    ///
692    /// For more information about this option, see [`UdpSocket::join_multicast_v4`].
693    #[stable(feature = "net2_mutators", since = "1.9.0")]
694    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
695        self.0.leave_multicast_v4(multiaddr, interface)
696    }
697
698    /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
699    ///
700    /// For more information about this option, see [`UdpSocket::join_multicast_v6`].
701    #[stable(feature = "net2_mutators", since = "1.9.0")]
702    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
703        self.0.leave_multicast_v6(multiaddr, interface)
704    }
705
706    /// Gets the value of the `SO_ERROR` option on this socket.
707    ///
708    /// This will retrieve the stored error in the underlying socket, clearing
709    /// the field in the process. This can be useful for checking errors between
710    /// calls.
711    ///
712    /// # Examples
713    ///
714    /// ```no_run
715    /// use std::net::UdpSocket;
716    ///
717    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
718    /// match socket.take_error() {
719    ///     Ok(Some(error)) => println!("UdpSocket error: {error:?}"),
720    ///     Ok(None) => println!("No error"),
721    ///     Err(error) => println!("UdpSocket.take_error failed: {error:?}"),
722    /// }
723    /// ```
724    #[stable(feature = "net2_mutators", since = "1.9.0")]
725    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
726        self.0.take_error()
727    }
728
729    /// Connects this UDP socket to a remote address, allowing the `send` and
730    /// `recv` syscalls to be used to send data and also applies filters to only
731    /// receive data from the specified address.
732    ///
733    /// If `addr` yields multiple addresses, `connect` will be attempted with
734    /// each of the addresses until the underlying OS function returns no
735    /// error. Note that usually, a successful `connect` call does not specify
736    /// that there is a remote server listening on the port, rather, such an
737    /// error would only be detected after the first send. If the OS returns an
738    /// error for each of the specified addresses, the error returned from the
739    /// last connection attempt (the last address) is returned.
740    ///
741    /// # Examples
742    ///
743    /// Creates a UDP socket bound to `127.0.0.1:3400` and connect the socket to
744    /// `127.0.0.1:8080`:
745    ///
746    /// ```no_run
747    /// use std::net::UdpSocket;
748    ///
749    /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("bind should succeed");
750    /// socket.connect("127.0.0.1:8080").expect("connect should succeed");
751    /// ```
752    ///
753    /// Unlike in the TCP case, passing an array of addresses to the `connect`
754    /// function of a UDP socket is not a useful thing to do: The OS will be
755    /// unable to determine whether something is listening on the remote
756    /// address without the application sending data.
757    ///
758    /// If your first `connect` is to a loopback address, subsequent
759    /// `connect`s to non-loopback addresses might fail, depending
760    /// on the platform.
761    #[stable(feature = "net2_mutators", since = "1.9.0")]
762    pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
763        self.0.connect(addr)
764    }
765
766    /// Sends data on the socket to the remote address to which it is connected.
767    /// On success, returns the number of bytes written. Note that the operating
768    /// system may refuse buffers larger than 65507. However, partial writes are
769    /// not possible until buffer sizes above `i32::MAX`.
770    ///
771    /// [`UdpSocket::connect`] will connect this socket to a remote address. This
772    /// method will fail if the socket is not connected.
773    ///
774    /// # Examples
775    ///
776    /// ```no_run
777    /// use std::net::UdpSocket;
778    ///
779    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
780    /// socket.connect("127.0.0.1:8080").expect("connect should succeed");
781    /// socket.send(&[0, 1, 2]).expect("send should succeed");
782    /// ```
783    #[stable(feature = "net2_mutators", since = "1.9.0")]
784    pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
785        self.0.send(buf)
786    }
787
788    /// Receives a single datagram message on the socket from the remote address to
789    /// which it is connected. On success, returns the number of bytes read.
790    ///
791    /// The function must be called with valid byte array `buf` of sufficient size to
792    /// hold the message bytes. If a message is too long to fit in the supplied buffer,
793    /// excess bytes may be discarded.
794    ///
795    /// [`UdpSocket::connect`] will connect this socket to a remote address. This
796    /// method will fail if the socket is not connected.
797    ///
798    /// Refer to the platform-specific documentation on this function; it is considered
799    /// correct for its behavior to differ from [`UdpSocket::recv_from`] if the underlying
800    /// system call does so.
801    ///
802    /// # Examples
803    ///
804    /// ```no_run
805    /// use std::net::UdpSocket;
806    ///
807    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
808    /// socket.connect("127.0.0.1:8080").expect("connect should succeed");
809    /// let mut buf = [0; 10];
810    /// match socket.recv(&mut buf) {
811    ///     Ok(received) => println!("received {received} bytes {:?}", &buf[..received]),
812    ///     Err(e) => println!("recv function failed: {e:?}"),
813    /// }
814    /// ```
815    #[stable(feature = "net2_mutators", since = "1.9.0")]
816    pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
817        self.0.recv(buf)
818    }
819
820    /// Receives single datagram on the socket from the remote address to which it is
821    /// connected, without removing the message from input queue. On success, returns
822    /// the number of bytes peeked.
823    ///
824    /// The function must be called with valid byte array `buf` of sufficient size to
825    /// hold the message bytes. If a message is too long to fit in the supplied buffer,
826    /// excess bytes may be discarded.
827    ///
828    /// Successive calls return the same data. This is accomplished by passing
829    /// `MSG_PEEK` as a flag to the underlying `recv` system call.
830    ///
831    /// Do not use this function to implement busy waiting, instead use `libc::poll` to
832    /// synchronize IO events on one or more sockets.
833    ///
834    /// [`UdpSocket::connect`] will connect this socket to a remote address. This
835    /// method will fail if the socket is not connected.
836    ///
837    /// # Errors
838    ///
839    /// This method will fail if the socket is not connected. The `connect` method
840    /// will connect this socket to a remote address.
841    ///
842    /// # Examples
843    ///
844    /// ```no_run
845    /// use std::net::UdpSocket;
846    ///
847    /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("bind should succeed");
848    /// socket.connect("127.0.0.1:8080").expect("connect should succeed");
849    /// let mut buf = [0; 10];
850    /// match socket.peek(&mut buf) {
851    ///     Ok(received) => println!("received {received} bytes"),
852    ///     Err(e) => println!("peek function failed: {e:?}"),
853    /// }
854    /// ```
855    #[stable(feature = "peek", since = "1.18.0")]
856    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
857        self.0.peek(buf)
858    }
859
860    /// Moves this UDP socket into or out of nonblocking mode.
861    ///
862    /// This will result in `recv`, `recv_from`, `send`, and `send_to` system
863    /// operations becoming nonblocking, i.e., immediately returning from their
864    /// calls. If the IO operation is successful, `Ok` is returned and no
865    /// further action is required. If the IO operation could not be completed
866    /// and needs to be retried, an error with kind
867    /// [`io::ErrorKind::WouldBlock`] is returned.
868    ///
869    /// On most Unix platforms, calling this method corresponds to calling `ioctl`
870    /// `FIONBIO`. On Windows, calling this method corresponds to calling
871    /// `ioctlsocket` `FIONBIO`.
872    ///
873    /// # Examples
874    ///
875    /// Creates a UDP socket bound to `127.0.0.1:7878` and read bytes in
876    /// nonblocking mode:
877    ///
878    /// ```no_run
879    /// use std::io;
880    /// use std::net::UdpSocket;
881    ///
882    /// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
883    /// socket.set_nonblocking(true).unwrap();
884    ///
885    /// # fn wait_for_fd() { unimplemented!() }
886    /// let mut buf = [0; 10];
887    /// let (num_bytes_read, _) = loop {
888    ///     match socket.recv_from(&mut buf) {
889    ///         Ok(n) => break n,
890    ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
891    ///             // wait until network socket is ready, typically implemented
892    ///             // via platform-specific APIs such as epoll or IOCP
893    ///             wait_for_fd();
894    ///         }
895    ///         Err(e) => panic!("encountered IO error: {e}"),
896    ///     }
897    /// };
898    /// println!("bytes: {:?}", &buf[..num_bytes_read]);
899    /// ```
900    #[stable(feature = "net2_mutators", since = "1.9.0")]
901    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
902        self.0.set_nonblocking(nonblocking)
903    }
904}
905
906// In addition to the `impl`s here, `UdpSocket` also has `impl`s for
907// `AsFd`/`From<OwnedFd>`/`Into<OwnedFd>` and
908// `AsRawFd`/`IntoRawFd`/`FromRawFd`, on Unix and WASI, and
909// `AsSocket`/`From<OwnedSocket>`/`Into<OwnedSocket>` and
910// `AsRawSocket`/`IntoRawSocket`/`FromRawSocket` on Windows.
911
912impl AsInner<net_imp::UdpSocket> for UdpSocket {
913    #[inline]
914    fn as_inner(&self) -> &net_imp::UdpSocket {
915        &self.0
916    }
917}
918
919impl FromInner<net_imp::UdpSocket> for UdpSocket {
920    fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket {
921        UdpSocket(inner)
922    }
923}
924
925impl IntoInner<net_imp::UdpSocket> for UdpSocket {
926    fn into_inner(self) -> net_imp::UdpSocket {
927        self.0
928    }
929}
930
931#[stable(feature = "rust1", since = "1.0.0")]
932impl fmt::Debug for UdpSocket {
933    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
934        self.0.fmt(f)
935    }
936}