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