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