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