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