2 use crate::io::{self, Error, ErrorKind};
3 use crate::net::{ToSocketAddrs, SocketAddr, Ipv4Addr, Ipv6Addr};
4 use crate::sys_common::net as net_imp;
5 use crate::sys_common::{AsInner, FromInner, IntoInner};
6 use crate::time::Duration;
10 /// After creating a `UdpSocket` by [`bind`]ing it to a socket address, data can be
11 /// [sent to] and [received from] any other socket address.
13 /// Although UDP is a connectionless protocol, this implementation provides an interface
14 /// to set an address where data should be sent and received from. After setting a remote
15 /// address with [`connect`], data can be sent to and received from that address with
16 /// [`send`] and [`recv`].
18 /// As stated in the User Datagram Protocol's specification in [IETF RFC 768], UDP is
19 /// an unordered, unreliable protocol; refer to [`TcpListener`] and [`TcpStream`] for TCP
22 /// [`bind`]: #method.bind
23 /// [`connect`]: #method.connect
24 /// [IETF RFC 768]: https://tools.ietf.org/html/rfc768
25 /// [`recv`]: #method.recv
26 /// [received from]: #method.recv_from
27 /// [`send`]: #method.send
28 /// [sent to]: #method.send_to
29 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
30 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
35 /// use std::net::UdpSocket;
37 /// fn main() -> std::io::Result<()> {
39 /// let mut socket = UdpSocket::bind("127.0.0.1:34254")?;
41 /// // Receives a single datagram message on the socket. If `buf` is too small to hold
42 /// // the message, it will be cut off.
43 /// let mut buf = [0; 10];
44 /// let (amt, src) = socket.recv_from(&mut buf)?;
46 /// // Redeclare `buf` as slice of the received data and send reverse data back to origin.
47 /// let buf = &mut buf[..amt];
49 /// socket.send_to(buf, &src)?;
50 /// } // the socket is closed here
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub struct UdpSocket(net_imp::UdpSocket);
58 /// Creates a UDP socket from the given address.
60 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
61 /// its documentation for concrete examples.
63 /// If `addr` yields multiple addresses, `bind` will be attempted with
64 /// each of the addresses until one succeeds and returns the socket. If none
65 /// of the addresses succeed in creating a socket, the error returned from
66 /// the last attempt (the last address) is returned.
68 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
72 /// Creates a UDP socket bound to `127.0.0.1:3400`:
75 /// use std::net::UdpSocket;
77 /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
80 /// Creates a UDP socket bound to `127.0.0.1:3400`. If the socket cannot be
81 /// bound to that address, create a UDP socket bound to `127.0.0.1:3401`:
84 /// use std::net::{SocketAddr, UdpSocket};
87 /// SocketAddr::from(([127, 0, 0, 1], 3400)),
88 /// SocketAddr::from(([127, 0, 0, 1], 3401)),
90 /// let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address");
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
94 super::each_addr(addr, net_imp::UdpSocket::bind).map(UdpSocket)
97 /// Receives a single datagram message on the socket. On success, returns the number
98 /// of bytes read and the origin.
100 /// The function must be called with valid byte array `buf` of sufficient size to
101 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
102 /// excess bytes may be discarded.
107 /// use std::net::UdpSocket;
109 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
110 /// let mut buf = [0; 10];
111 /// let (number_of_bytes, src_addr) = socket.recv_from(&mut buf)
112 /// .expect("Didn't receive data");
113 /// let filled_buf = &mut buf[..number_of_bytes];
115 #[stable(feature = "rust1", since = "1.0.0")]
116 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
117 self.0.recv_from(buf)
120 /// Receives a single datagram message on the socket, without removing it from the
121 /// queue. On success, returns the number of bytes read and the origin.
123 /// The function must be called with valid byte array `buf` of sufficient size to
124 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
125 /// excess bytes may be discarded.
127 /// Successive calls return the same data. This is accomplished by passing
128 /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
130 /// Do not use this function to implement busy waiting, instead use `libc::poll` to
131 /// synchronize IO events on one or more sockets.
136 /// use std::net::UdpSocket;
138 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
139 /// let mut buf = [0; 10];
140 /// let (number_of_bytes, src_addr) = socket.peek_from(&mut buf)
141 /// .expect("Didn't receive data");
142 /// let filled_buf = &mut buf[..number_of_bytes];
144 #[stable(feature = "peek", since = "1.18.0")]
145 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
146 self.0.peek_from(buf)
149 /// Sends data on the socket to the given address. On success, returns the
150 /// number of bytes written.
152 /// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
153 /// documentation for concrete examples.
155 /// It is possible for `addr` to yield multiple addresses, but `send_to`
156 /// will only send data to the first address yielded by `addr`.
158 /// This will return an error when the IP version of the local socket
159 /// does not match that returned from [`ToSocketAddrs`].
161 /// See issue #34202 for more details.
163 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
168 /// use std::net::UdpSocket;
170 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
171 /// socket.send_to(&[0; 10], "127.0.0.1:4242").expect("couldn't send data");
173 #[stable(feature = "rust1", since = "1.0.0")]
174 pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
175 -> io::Result<usize> {
176 match addr.to_socket_addrs()?.next() {
177 Some(addr) => self.0.send_to(buf, &addr),
178 None => Err(Error::new(ErrorKind::InvalidInput,
179 "no addresses to send data to")),
183 /// Returns the socket address that this socket was created from.
188 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
190 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
191 /// assert_eq!(socket.local_addr().unwrap(),
192 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)));
194 #[stable(feature = "rust1", since = "1.0.0")]
195 pub fn local_addr(&self) -> io::Result<SocketAddr> {
199 /// Creates a new independently owned handle to the underlying socket.
201 /// The returned `UdpSocket` is a reference to the same socket that this
202 /// object references. Both handles will read and write the same port, and
203 /// options set on one socket will be propagated to the other.
208 /// use std::net::UdpSocket;
210 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
211 /// let socket_clone = socket.try_clone().expect("couldn't clone the socket");
213 #[stable(feature = "rust1", since = "1.0.0")]
214 pub fn try_clone(&self) -> io::Result<UdpSocket> {
215 self.0.duplicate().map(UdpSocket)
218 /// Sets the read timeout to the timeout specified.
220 /// If the value specified is [`None`], then [`read`] calls will block
221 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
222 /// passed to this method.
224 /// # Platform-specific behavior
226 /// Platforms may return a different error code whenever a read times out as
227 /// a result of setting this option. For example Unix typically returns an
228 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
230 /// [`None`]: ../../std/option/enum.Option.html#variant.None
231 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
232 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
233 /// [`Duration`]: ../../std/time/struct.Duration.html
234 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
235 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
240 /// use std::net::UdpSocket;
242 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
243 /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
246 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
251 /// use std::net::UdpSocket;
252 /// use std::time::Duration;
254 /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
255 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
256 /// let err = result.unwrap_err();
257 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
259 #[stable(feature = "socket_timeout", since = "1.4.0")]
260 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
261 self.0.set_read_timeout(dur)
264 /// Sets the write timeout to the timeout specified.
266 /// If the value specified is [`None`], then [`write`] calls will block
267 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
268 /// passed to this method.
270 /// # Platform-specific behavior
272 /// Platforms may return a different error code whenever a write times out
273 /// as a result of setting this option. For example Unix typically returns
274 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
276 /// [`None`]: ../../std/option/enum.Option.html#variant.None
277 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
278 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
279 /// [`Duration`]: ../../std/time/struct.Duration.html
280 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
281 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
286 /// use std::net::UdpSocket;
288 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
289 /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
292 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
297 /// use std::net::UdpSocket;
298 /// use std::time::Duration;
300 /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
301 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
302 /// let err = result.unwrap_err();
303 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
305 #[stable(feature = "socket_timeout", since = "1.4.0")]
306 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
307 self.0.set_write_timeout(dur)
310 /// Returns the read timeout of this socket.
312 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
314 /// [`None`]: ../../std/option/enum.Option.html#variant.None
315 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
320 /// use std::net::UdpSocket;
322 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
323 /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
324 /// assert_eq!(socket.read_timeout().unwrap(), None);
326 #[stable(feature = "socket_timeout", since = "1.4.0")]
327 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
328 self.0.read_timeout()
331 /// Returns the write timeout of this socket.
333 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
335 /// [`None`]: ../../std/option/enum.Option.html#variant.None
336 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
341 /// use std::net::UdpSocket;
343 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
344 /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
345 /// assert_eq!(socket.write_timeout().unwrap(), None);
347 #[stable(feature = "socket_timeout", since = "1.4.0")]
348 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
349 self.0.write_timeout()
352 /// Sets the value of the `SO_BROADCAST` option for this socket.
354 /// When enabled, this socket is allowed to send packets to a broadcast
360 /// use std::net::UdpSocket;
362 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
363 /// socket.set_broadcast(false).expect("set_broadcast call failed");
365 #[stable(feature = "net2_mutators", since = "1.9.0")]
366 pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
367 self.0.set_broadcast(broadcast)
370 /// Gets the value of the `SO_BROADCAST` option for this socket.
372 /// For more information about this option, see
373 /// [`set_broadcast`][link].
375 /// [link]: #method.set_broadcast
380 /// use std::net::UdpSocket;
382 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
383 /// socket.set_broadcast(false).expect("set_broadcast call failed");
384 /// assert_eq!(socket.broadcast().unwrap(), false);
386 #[stable(feature = "net2_mutators", since = "1.9.0")]
387 pub fn broadcast(&self) -> io::Result<bool> {
391 /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
393 /// If enabled, multicast packets will be looped back to the local socket.
394 /// Note that this may not have any affect on IPv6 sockets.
399 /// use std::net::UdpSocket;
401 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
402 /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
404 #[stable(feature = "net2_mutators", since = "1.9.0")]
405 pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
406 self.0.set_multicast_loop_v4(multicast_loop_v4)
409 /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
411 /// For more information about this option, see
412 /// [`set_multicast_loop_v4`][link].
414 /// [link]: #method.set_multicast_loop_v4
419 /// use std::net::UdpSocket;
421 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
422 /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
423 /// assert_eq!(socket.multicast_loop_v4().unwrap(), false);
425 #[stable(feature = "net2_mutators", since = "1.9.0")]
426 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
427 self.0.multicast_loop_v4()
430 /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
432 /// Indicates the time-to-live value of outgoing multicast packets for
433 /// this socket. The default value is 1 which means that multicast packets
434 /// don't leave the local network unless explicitly requested.
436 /// Note that this may not have any affect on IPv6 sockets.
441 /// use std::net::UdpSocket;
443 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
444 /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
446 #[stable(feature = "net2_mutators", since = "1.9.0")]
447 pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
448 self.0.set_multicast_ttl_v4(multicast_ttl_v4)
451 /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
453 /// For more information about this option, see
454 /// [`set_multicast_ttl_v4`][link].
456 /// [link]: #method.set_multicast_ttl_v4
461 /// use std::net::UdpSocket;
463 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
464 /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
465 /// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
467 #[stable(feature = "net2_mutators", since = "1.9.0")]
468 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
469 self.0.multicast_ttl_v4()
472 /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
474 /// Controls whether this socket sees the multicast packets it sends itself.
475 /// Note that this may not have any affect on IPv4 sockets.
480 /// use std::net::UdpSocket;
482 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
483 /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
485 #[stable(feature = "net2_mutators", since = "1.9.0")]
486 pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
487 self.0.set_multicast_loop_v6(multicast_loop_v6)
490 /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
492 /// For more information about this option, see
493 /// [`set_multicast_loop_v6`][link].
495 /// [link]: #method.set_multicast_loop_v6
500 /// use std::net::UdpSocket;
502 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
503 /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
504 /// assert_eq!(socket.multicast_loop_v6().unwrap(), false);
506 #[stable(feature = "net2_mutators", since = "1.9.0")]
507 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
508 self.0.multicast_loop_v6()
511 /// Sets the value for the `IP_TTL` option on this socket.
513 /// This value sets the time-to-live field that is used in every packet sent
514 /// from this socket.
519 /// use std::net::UdpSocket;
521 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
522 /// socket.set_ttl(42).expect("set_ttl call failed");
524 #[stable(feature = "net2_mutators", since = "1.9.0")]
525 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
529 /// Gets the value of the `IP_TTL` option for this socket.
531 /// For more information about this option, see [`set_ttl`][link].
533 /// [link]: #method.set_ttl
538 /// use std::net::UdpSocket;
540 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
541 /// socket.set_ttl(42).expect("set_ttl call failed");
542 /// assert_eq!(socket.ttl().unwrap(), 42);
544 #[stable(feature = "net2_mutators", since = "1.9.0")]
545 pub fn ttl(&self) -> io::Result<u32> {
549 /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
551 /// This function specifies a new multicast group for this socket to join.
552 /// The address must be a valid multicast address, and `interface` is the
553 /// address of the local interface with which the system should join the
554 /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
555 /// interface is chosen by the system.
556 #[stable(feature = "net2_mutators", since = "1.9.0")]
557 pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
558 self.0.join_multicast_v4(multiaddr, interface)
561 /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
563 /// This function specifies a new multicast group for this socket to join.
564 /// The address must be a valid multicast address, and `interface` is the
565 /// index of the interface to join/leave (or 0 to indicate any interface).
566 #[stable(feature = "net2_mutators", since = "1.9.0")]
567 pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
568 self.0.join_multicast_v6(multiaddr, interface)
571 /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
573 /// For more information about this option, see
574 /// [`join_multicast_v4`][link].
576 /// [link]: #method.join_multicast_v4
577 #[stable(feature = "net2_mutators", since = "1.9.0")]
578 pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
579 self.0.leave_multicast_v4(multiaddr, interface)
582 /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
584 /// For more information about this option, see
585 /// [`join_multicast_v6`][link].
587 /// [link]: #method.join_multicast_v6
588 #[stable(feature = "net2_mutators", since = "1.9.0")]
589 pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
590 self.0.leave_multicast_v6(multiaddr, interface)
593 /// Gets the value of the `SO_ERROR` option on this socket.
595 /// This will retrieve the stored error in the underlying socket, clearing
596 /// the field in the process. This can be useful for checking errors between
602 /// use std::net::UdpSocket;
604 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
605 /// match socket.take_error() {
606 /// Ok(Some(error)) => println!("UdpSocket error: {:?}", error),
607 /// Ok(None) => println!("No error"),
608 /// Err(error) => println!("UdpSocket.take_error failed: {:?}", error),
611 #[stable(feature = "net2_mutators", since = "1.9.0")]
612 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
616 /// Connects this UDP socket to a remote address, allowing the `send` and
617 /// `recv` syscalls to be used to send data and also applies filters to only
618 /// receive data from the specified address.
620 /// If `addr` yields multiple addresses, `connect` will be attempted with
621 /// each of the addresses until the underlying OS function returns no
622 /// error. Note that usually, a successful `connect` call does not specify
623 /// that there is a remote server listening on the port, rather, such an
624 /// error would only be detected after the first send. If the OS returns an
625 /// error for each of the specified addresses, the error returned from the
626 /// last connection attempt (the last address) is returned.
630 /// Creates a UDP socket bound to `127.0.0.1:3400` and connect the socket to
631 /// `127.0.0.1:8080`:
634 /// use std::net::UdpSocket;
636 /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
637 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
640 /// Unlike in the TCP case, passing an array of addresses to the `connect`
641 /// function of a UDP socket is not a useful thing to do: The OS will be
642 /// unable to determine whether something is listening on the remote
643 /// address without the application sending data.
644 #[stable(feature = "net2_mutators", since = "1.9.0")]
645 pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
646 super::each_addr(addr, |addr| self.0.connect(addr))
649 /// Sends data on the socket to the remote address to which it is connected.
651 /// The [`connect`] method will connect this socket to a remote address. This
652 /// method will fail if the socket is not connected.
654 /// [`connect`]: #method.connect
659 /// use std::net::UdpSocket;
661 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
662 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
663 /// socket.send(&[0, 1, 2]).expect("couldn't send message");
665 #[stable(feature = "net2_mutators", since = "1.9.0")]
666 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
670 /// Receives a single datagram message on the socket from the remote address to
671 /// which it is connected. On success, returns the number of bytes read.
673 /// The function must be called with valid byte array `buf` of sufficient size to
674 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
675 /// excess bytes may be discarded.
677 /// The [`connect`] method will connect this socket to a remote address. This
678 /// method will fail if the socket is not connected.
680 /// [`connect`]: #method.connect
685 /// use std::net::UdpSocket;
687 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
688 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
689 /// let mut buf = [0; 10];
690 /// match socket.recv(&mut buf) {
691 /// Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]),
692 /// Err(e) => println!("recv function failed: {:?}", e),
695 #[stable(feature = "net2_mutators", since = "1.9.0")]
696 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
700 /// Receives single datagram on the socket from the remote address to which it is
701 /// connected, without removing the message from input queue. On success, returns
702 /// the number of bytes peeked.
704 /// The function must be called with valid byte array `buf` of sufficient size to
705 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
706 /// excess bytes may be discarded.
708 /// Successive calls return the same data. This is accomplished by passing
709 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
711 /// Do not use this function to implement busy waiting, instead use `libc::poll` to
712 /// synchronize IO events on one or more sockets.
714 /// The [`connect`] method will connect this socket to a remote address. This
715 /// method will fail if the socket is not connected.
717 /// [`connect`]: #method.connect
721 /// This method will fail if the socket is not connected. The `connect` method
722 /// will connect this socket to a remote address.
727 /// use std::net::UdpSocket;
729 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
730 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
731 /// let mut buf = [0; 10];
732 /// match socket.peek(&mut buf) {
733 /// Ok(received) => println!("received {} bytes", received),
734 /// Err(e) => println!("peek function failed: {:?}", e),
737 #[stable(feature = "peek", since = "1.18.0")]
738 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
742 /// Moves this UDP socket into or out of nonblocking mode.
744 /// This will result in `recv`, `recv_from`, `send`, and `send_to`
745 /// operations becoming nonblocking, i.e., immediately returning from their
746 /// calls. If the IO operation is successful, `Ok` is returned and no
747 /// further action is required. If the IO operation could not be completed
748 /// and needs to be retried, an error with kind
749 /// [`io::ErrorKind::WouldBlock`] is returned.
751 /// On Unix platforms, calling this method corresponds to calling `fcntl`
752 /// `FIONBIO`. On Windows calling this method corresponds to calling
753 /// `ioctlsocket` `FIONBIO`.
755 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
759 /// Creates a UDP socket bound to `127.0.0.1:7878` and read bytes in
760 /// nonblocking mode:
764 /// use std::net::UdpSocket;
766 /// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
767 /// socket.set_nonblocking(true).unwrap();
769 /// # fn wait_for_fd() { unimplemented!() }
770 /// let mut buf = [0; 10];
771 /// let (num_bytes_read, _) = loop {
772 /// match socket.recv_from(&mut buf) {
773 /// Ok(n) => break n,
774 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
775 /// // wait until network socket is ready, typically implemented
776 /// // via platform-specific APIs such as epoll or IOCP
779 /// Err(e) => panic!("encountered IO error: {}", e),
782 /// println!("bytes: {:?}", &buf[..num_bytes_read]);
784 #[stable(feature = "net2_mutators", since = "1.9.0")]
785 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
786 self.0.set_nonblocking(nonblocking)
790 impl AsInner<net_imp::UdpSocket> for UdpSocket {
791 fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 }
794 impl FromInner<net_imp::UdpSocket> for UdpSocket {
795 fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) }
798 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
799 fn into_inner(self) -> net_imp::UdpSocket { self.0 }
802 #[stable(feature = "rust1", since = "1.0.0")]
803 impl fmt::Debug for UdpSocket {
804 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
809 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
811 use crate::io::ErrorKind;
813 use crate::net::test::{next_test_ip4, next_test_ip6};
814 use crate::sync::mpsc::channel;
815 use crate::sys_common::AsInner;
816 use crate::time::{Instant, Duration};
819 fn each_ip(f: &mut dyn FnMut(SocketAddr, SocketAddr)) {
820 f(next_test_ip4(), next_test_ip4());
821 f(next_test_ip6(), next_test_ip6());
828 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
835 match UdpSocket::bind("1.1.1.1:9999") {
838 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable)
844 fn socket_smoke_test_ip4() {
845 each_ip(&mut |server_ip, client_ip| {
846 let (tx1, rx1) = channel();
847 let (tx2, rx2) = channel();
849 let _t = thread::spawn(move|| {
850 let client = t!(UdpSocket::bind(&client_ip));
852 t!(client.send_to(&[99], &server_ip));
853 tx2.send(()).unwrap();
856 let server = t!(UdpSocket::bind(&server_ip));
857 tx1.send(()).unwrap();
859 let (nread, src) = t!(server.recv_from(&mut buf));
860 assert_eq!(nread, 1);
861 assert_eq!(buf[0], 99);
862 assert_eq!(src, client_ip);
868 fn socket_name_ip4() {
869 each_ip(&mut |addr, _| {
870 let server = t!(UdpSocket::bind(&addr));
871 assert_eq!(addr, t!(server.local_addr()));
876 fn udp_clone_smoke() {
877 each_ip(&mut |addr1, addr2| {
878 let sock1 = t!(UdpSocket::bind(&addr1));
879 let sock2 = t!(UdpSocket::bind(&addr2));
881 let _t = thread::spawn(move|| {
882 let mut buf = [0, 0];
883 assert_eq!(sock2.recv_from(&mut buf).unwrap(), (1, addr1));
884 assert_eq!(buf[0], 1);
885 t!(sock2.send_to(&[2], &addr1));
888 let sock3 = t!(sock1.try_clone());
890 let (tx1, rx1) = channel();
891 let (tx2, rx2) = channel();
892 let _t = thread::spawn(move|| {
894 t!(sock3.send_to(&[1], &addr2));
895 tx2.send(()).unwrap();
897 tx1.send(()).unwrap();
898 let mut buf = [0, 0];
899 assert_eq!(sock1.recv_from(&mut buf).unwrap(), (1, addr2));
905 fn udp_clone_two_read() {
906 each_ip(&mut |addr1, addr2| {
907 let sock1 = t!(UdpSocket::bind(&addr1));
908 let sock2 = t!(UdpSocket::bind(&addr2));
909 let (tx1, rx) = channel();
910 let tx2 = tx1.clone();
912 let _t = thread::spawn(move|| {
913 t!(sock2.send_to(&[1], &addr1));
915 t!(sock2.send_to(&[2], &addr1));
919 let sock3 = t!(sock1.try_clone());
921 let (done, rx) = channel();
922 let _t = thread::spawn(move|| {
923 let mut buf = [0, 0];
924 t!(sock3.recv_from(&mut buf));
925 tx2.send(()).unwrap();
926 done.send(()).unwrap();
928 let mut buf = [0, 0];
929 t!(sock1.recv_from(&mut buf));
930 tx1.send(()).unwrap();
937 fn udp_clone_two_write() {
938 each_ip(&mut |addr1, addr2| {
939 let sock1 = t!(UdpSocket::bind(&addr1));
940 let sock2 = t!(UdpSocket::bind(&addr2));
942 let (tx, rx) = channel();
943 let (serv_tx, serv_rx) = channel();
945 let _t = thread::spawn(move|| {
946 let mut buf = [0, 1];
948 t!(sock2.recv_from(&mut buf));
949 serv_tx.send(()).unwrap();
952 let sock3 = t!(sock1.try_clone());
954 let (done, rx) = channel();
955 let tx2 = tx.clone();
956 let _t = thread::spawn(move|| {
957 match sock3.send_to(&[1], &addr2) {
958 Ok(..) => { let _ = tx2.send(()); }
961 done.send(()).unwrap();
963 match sock1.send_to(&[2], &addr2) {
964 Ok(..) => { let _ = tx.send(()); }
970 serv_rx.recv().unwrap();
976 let name = if cfg!(windows) {"socket"} else {"fd"};
977 let socket_addr = next_test_ip4();
979 let udpsock = t!(UdpSocket::bind(&socket_addr));
980 let udpsock_inner = udpsock.0.socket().as_inner();
981 let compare = format!("UdpSocket {{ addr: {:?}, {}: {:?} }}",
982 socket_addr, name, udpsock_inner);
983 assert_eq!(format!("{:?}", udpsock), compare);
986 // FIXME: re-enabled bitrig/openbsd/netbsd tests once their socket timeout code
987 // no longer has rounding errors.
988 #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
991 let addr = next_test_ip4();
993 let stream = t!(UdpSocket::bind(&addr));
994 let dur = Duration::new(15410, 0);
996 assert_eq!(None, t!(stream.read_timeout()));
998 t!(stream.set_read_timeout(Some(dur)));
999 assert_eq!(Some(dur), t!(stream.read_timeout()));
1001 assert_eq!(None, t!(stream.write_timeout()));
1003 t!(stream.set_write_timeout(Some(dur)));
1004 assert_eq!(Some(dur), t!(stream.write_timeout()));
1006 t!(stream.set_read_timeout(None));
1007 assert_eq!(None, t!(stream.read_timeout()));
1009 t!(stream.set_write_timeout(None));
1010 assert_eq!(None, t!(stream.write_timeout()));
1014 fn test_read_timeout() {
1015 let addr = next_test_ip4();
1017 let stream = t!(UdpSocket::bind(&addr));
1018 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1020 let mut buf = [0; 10];
1022 let start = Instant::now();
1024 let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
1025 if kind != ErrorKind::Interrupted {
1026 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1027 "unexpected_error: {:?}", kind);
1031 assert!(start.elapsed() > Duration::from_millis(400));
1035 fn test_read_with_timeout() {
1036 let addr = next_test_ip4();
1038 let stream = t!(UdpSocket::bind(&addr));
1039 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1041 t!(stream.send_to(b"hello world", &addr));
1043 let mut buf = [0; 11];
1044 t!(stream.recv_from(&mut buf));
1045 assert_eq!(b"hello world", &buf[..]);
1047 let start = Instant::now();
1049 let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
1050 if kind != ErrorKind::Interrupted {
1051 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1052 "unexpected_error: {:?}", kind);
1056 assert!(start.elapsed() > Duration::from_millis(400));
1059 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1060 // when passed zero Durations
1062 fn test_timeout_zero_duration() {
1063 let addr = next_test_ip4();
1065 let socket = t!(UdpSocket::bind(&addr));
1067 let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
1068 let err = result.unwrap_err();
1069 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1071 let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
1072 let err = result.unwrap_err();
1073 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1077 fn connect_send_recv() {
1078 let addr = next_test_ip4();
1080 let socket = t!(UdpSocket::bind(&addr));
1081 t!(socket.connect(addr));
1083 t!(socket.send(b"hello world"));
1085 let mut buf = [0; 11];
1086 t!(socket.recv(&mut buf));
1087 assert_eq!(b"hello world", &buf[..]);
1091 fn connect_send_peek_recv() {
1092 each_ip(&mut |addr, _| {
1093 let socket = t!(UdpSocket::bind(&addr));
1094 t!(socket.connect(addr));
1096 t!(socket.send(b"hello world"));
1099 let mut buf = [0; 11];
1100 let size = t!(socket.peek(&mut buf));
1101 assert_eq!(b"hello world", &buf[..]);
1102 assert_eq!(size, 11);
1105 let mut buf = [0; 11];
1106 let size = t!(socket.recv(&mut buf));
1107 assert_eq!(b"hello world", &buf[..]);
1108 assert_eq!(size, 11);
1114 each_ip(&mut |addr, _| {
1115 let socket = t!(UdpSocket::bind(&addr));
1116 t!(socket.send_to(b"hello world", &addr));
1119 let mut buf = [0; 11];
1120 let (size, _) = t!(socket.peek_from(&mut buf));
1121 assert_eq!(b"hello world", &buf[..]);
1122 assert_eq!(size, 11);
1125 let mut buf = [0; 11];
1126 let (size, _) = t!(socket.recv_from(&mut buf));
1127 assert_eq!(b"hello world", &buf[..]);
1128 assert_eq!(size, 11);
1136 let addr = next_test_ip4();
1138 let stream = t!(UdpSocket::bind(&addr));
1140 t!(stream.set_ttl(ttl));
1141 assert_eq!(ttl, t!(stream.ttl()));
1145 fn set_nonblocking() {
1146 each_ip(&mut |addr, _| {
1147 let socket = t!(UdpSocket::bind(&addr));
1149 t!(socket.set_nonblocking(true));
1150 t!(socket.set_nonblocking(false));
1152 t!(socket.connect(addr));
1154 t!(socket.set_nonblocking(false));
1155 t!(socket.set_nonblocking(true));
1158 match socket.recv(&mut buf) {
1159 Ok(_) => panic!("expected error"),
1160 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1161 Err(e) => panic!("unexpected error {}", e),