2 use crate::io::{self, Error, ErrorKind};
3 use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
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) -> io::Result<usize> {
175 match addr.to_socket_addrs()?.next() {
176 Some(addr) => self.0.send_to(buf, &addr),
177 None => Err(Error::new(ErrorKind::InvalidInput, "no addresses to send data to")),
181 /// Returns the socket address of the remote peer this socket was connected to.
186 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
188 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
189 /// socket.connect("192.168.0.1:41203").expect("couldn't connect to address");
190 /// assert_eq!(socket.peer_addr().unwrap(),
191 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 41203)));
194 /// If the socket isn't connected, it will return a [`NotConnected`] error.
196 /// [`NotConnected`]: ../../std/io/enum.ErrorKind.html#variant.NotConnected
199 /// use std::net::UdpSocket;
201 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
202 /// assert_eq!(socket.peer_addr().unwrap_err().kind(),
203 /// std::io::ErrorKind::NotConnected);
205 #[stable(feature = "udp_peer_addr", since = "1.40.0")]
206 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
210 /// Returns the socket address that this socket was created from.
215 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
217 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
218 /// assert_eq!(socket.local_addr().unwrap(),
219 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)));
221 #[stable(feature = "rust1", since = "1.0.0")]
222 pub fn local_addr(&self) -> io::Result<SocketAddr> {
226 /// Creates a new independently owned handle to the underlying socket.
228 /// The returned `UdpSocket` is a reference to the same socket that this
229 /// object references. Both handles will read and write the same port, and
230 /// options set on one socket will be propagated to the other.
235 /// use std::net::UdpSocket;
237 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
238 /// let socket_clone = socket.try_clone().expect("couldn't clone the socket");
240 #[stable(feature = "rust1", since = "1.0.0")]
241 pub fn try_clone(&self) -> io::Result<UdpSocket> {
242 self.0.duplicate().map(UdpSocket)
245 /// Sets the read timeout to the timeout specified.
247 /// If the value specified is [`None`], then [`read`] calls will block
248 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
249 /// passed to this method.
251 /// # Platform-specific behavior
253 /// Platforms may return a different error code whenever a read times out as
254 /// a result of setting this option. For example Unix typically returns an
255 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
257 /// [`None`]: ../../std/option/enum.Option.html#variant.None
258 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
259 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
260 /// [`Duration`]: ../../std/time/struct.Duration.html
261 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
262 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
267 /// use std::net::UdpSocket;
269 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
270 /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
273 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
278 /// use std::net::UdpSocket;
279 /// use std::time::Duration;
281 /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
282 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
283 /// let err = result.unwrap_err();
284 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
286 #[stable(feature = "socket_timeout", since = "1.4.0")]
287 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
288 self.0.set_read_timeout(dur)
291 /// Sets the write timeout to the timeout specified.
293 /// If the value specified is [`None`], then [`write`] calls will block
294 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
295 /// passed to this method.
297 /// # Platform-specific behavior
299 /// Platforms may return a different error code whenever a write times out
300 /// as a result of setting this option. For example Unix typically returns
301 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
303 /// [`None`]: ../../std/option/enum.Option.html#variant.None
304 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
305 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
306 /// [`Duration`]: ../../std/time/struct.Duration.html
307 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
308 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
313 /// use std::net::UdpSocket;
315 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
316 /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
319 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
324 /// use std::net::UdpSocket;
325 /// use std::time::Duration;
327 /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
328 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
329 /// let err = result.unwrap_err();
330 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
332 #[stable(feature = "socket_timeout", since = "1.4.0")]
333 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
334 self.0.set_write_timeout(dur)
337 /// Returns the read timeout of this socket.
339 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
341 /// [`None`]: ../../std/option/enum.Option.html#variant.None
342 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
347 /// use std::net::UdpSocket;
349 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
350 /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
351 /// assert_eq!(socket.read_timeout().unwrap(), None);
353 #[stable(feature = "socket_timeout", since = "1.4.0")]
354 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
355 self.0.read_timeout()
358 /// Returns the write timeout of this socket.
360 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
362 /// [`None`]: ../../std/option/enum.Option.html#variant.None
363 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
368 /// use std::net::UdpSocket;
370 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
371 /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
372 /// assert_eq!(socket.write_timeout().unwrap(), None);
374 #[stable(feature = "socket_timeout", since = "1.4.0")]
375 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
376 self.0.write_timeout()
379 /// Sets the value of the `SO_BROADCAST` option for this socket.
381 /// When enabled, this socket is allowed to send packets to a broadcast
387 /// use std::net::UdpSocket;
389 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
390 /// socket.set_broadcast(false).expect("set_broadcast call failed");
392 #[stable(feature = "net2_mutators", since = "1.9.0")]
393 pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
394 self.0.set_broadcast(broadcast)
397 /// Gets the value of the `SO_BROADCAST` option for this socket.
399 /// For more information about this option, see
400 /// [`set_broadcast`][link].
402 /// [link]: #method.set_broadcast
407 /// use std::net::UdpSocket;
409 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
410 /// socket.set_broadcast(false).expect("set_broadcast call failed");
411 /// assert_eq!(socket.broadcast().unwrap(), false);
413 #[stable(feature = "net2_mutators", since = "1.9.0")]
414 pub fn broadcast(&self) -> io::Result<bool> {
418 /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
420 /// If enabled, multicast packets will be looped back to the local socket.
421 /// Note that this may not have any effect on IPv6 sockets.
426 /// use std::net::UdpSocket;
428 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
429 /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
431 #[stable(feature = "net2_mutators", since = "1.9.0")]
432 pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
433 self.0.set_multicast_loop_v4(multicast_loop_v4)
436 /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
438 /// For more information about this option, see
439 /// [`set_multicast_loop_v4`][link].
441 /// [link]: #method.set_multicast_loop_v4
446 /// use std::net::UdpSocket;
448 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
449 /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
450 /// assert_eq!(socket.multicast_loop_v4().unwrap(), false);
452 #[stable(feature = "net2_mutators", since = "1.9.0")]
453 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
454 self.0.multicast_loop_v4()
457 /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
459 /// Indicates the time-to-live value of outgoing multicast packets for
460 /// this socket. The default value is 1 which means that multicast packets
461 /// don't leave the local network unless explicitly requested.
463 /// Note that this may not have any effect on IPv6 sockets.
468 /// use std::net::UdpSocket;
470 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
471 /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
473 #[stable(feature = "net2_mutators", since = "1.9.0")]
474 pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
475 self.0.set_multicast_ttl_v4(multicast_ttl_v4)
478 /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
480 /// For more information about this option, see
481 /// [`set_multicast_ttl_v4`][link].
483 /// [link]: #method.set_multicast_ttl_v4
488 /// use std::net::UdpSocket;
490 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
491 /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
492 /// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
494 #[stable(feature = "net2_mutators", since = "1.9.0")]
495 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
496 self.0.multicast_ttl_v4()
499 /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
501 /// Controls whether this socket sees the multicast packets it sends itself.
502 /// Note that this may not have any affect on IPv4 sockets.
507 /// use std::net::UdpSocket;
509 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
510 /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
512 #[stable(feature = "net2_mutators", since = "1.9.0")]
513 pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
514 self.0.set_multicast_loop_v6(multicast_loop_v6)
517 /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
519 /// For more information about this option, see
520 /// [`set_multicast_loop_v6`][link].
522 /// [link]: #method.set_multicast_loop_v6
527 /// use std::net::UdpSocket;
529 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
530 /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
531 /// assert_eq!(socket.multicast_loop_v6().unwrap(), false);
533 #[stable(feature = "net2_mutators", since = "1.9.0")]
534 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
535 self.0.multicast_loop_v6()
538 /// Sets the value for the `IP_TTL` option on this socket.
540 /// This value sets the time-to-live field that is used in every packet sent
541 /// from this socket.
546 /// use std::net::UdpSocket;
548 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
549 /// socket.set_ttl(42).expect("set_ttl call failed");
551 #[stable(feature = "net2_mutators", since = "1.9.0")]
552 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
556 /// Gets the value of the `IP_TTL` option for this socket.
558 /// For more information about this option, see [`set_ttl`][link].
560 /// [link]: #method.set_ttl
565 /// use std::net::UdpSocket;
567 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
568 /// socket.set_ttl(42).expect("set_ttl call failed");
569 /// assert_eq!(socket.ttl().unwrap(), 42);
571 #[stable(feature = "net2_mutators", since = "1.9.0")]
572 pub fn ttl(&self) -> io::Result<u32> {
576 /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
578 /// This function specifies a new multicast group for this socket to join.
579 /// The address must be a valid multicast address, and `interface` is the
580 /// address of the local interface with which the system should join the
581 /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
582 /// interface is chosen by the system.
583 #[stable(feature = "net2_mutators", since = "1.9.0")]
584 pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
585 self.0.join_multicast_v4(multiaddr, interface)
588 /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
590 /// This function specifies a new multicast group for this socket to join.
591 /// The address must be a valid multicast address, and `interface` is the
592 /// index of the interface to join/leave (or 0 to indicate any interface).
593 #[stable(feature = "net2_mutators", since = "1.9.0")]
594 pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
595 self.0.join_multicast_v6(multiaddr, interface)
598 /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
600 /// For more information about this option, see
601 /// [`join_multicast_v4`][link].
603 /// [link]: #method.join_multicast_v4
604 #[stable(feature = "net2_mutators", since = "1.9.0")]
605 pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
606 self.0.leave_multicast_v4(multiaddr, interface)
609 /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
611 /// For more information about this option, see
612 /// [`join_multicast_v6`][link].
614 /// [link]: #method.join_multicast_v6
615 #[stable(feature = "net2_mutators", since = "1.9.0")]
616 pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
617 self.0.leave_multicast_v6(multiaddr, interface)
620 /// Gets the value of the `SO_ERROR` option on this socket.
622 /// This will retrieve the stored error in the underlying socket, clearing
623 /// the field in the process. This can be useful for checking errors between
629 /// use std::net::UdpSocket;
631 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
632 /// match socket.take_error() {
633 /// Ok(Some(error)) => println!("UdpSocket error: {:?}", error),
634 /// Ok(None) => println!("No error"),
635 /// Err(error) => println!("UdpSocket.take_error failed: {:?}", error),
638 #[stable(feature = "net2_mutators", since = "1.9.0")]
639 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
643 /// Connects this UDP socket to a remote address, allowing the `send` and
644 /// `recv` syscalls to be used to send data and also applies filters to only
645 /// receive data from the specified address.
647 /// If `addr` yields multiple addresses, `connect` will be attempted with
648 /// each of the addresses until the underlying OS function returns no
649 /// error. Note that usually, a successful `connect` call does not specify
650 /// that there is a remote server listening on the port, rather, such an
651 /// error would only be detected after the first send. If the OS returns an
652 /// error for each of the specified addresses, the error returned from the
653 /// last connection attempt (the last address) is returned.
657 /// Creates a UDP socket bound to `127.0.0.1:3400` and connect the socket to
658 /// `127.0.0.1:8080`:
661 /// use std::net::UdpSocket;
663 /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
664 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
667 /// Unlike in the TCP case, passing an array of addresses to the `connect`
668 /// function of a UDP socket is not a useful thing to do: The OS will be
669 /// unable to determine whether something is listening on the remote
670 /// address without the application sending data.
671 #[stable(feature = "net2_mutators", since = "1.9.0")]
672 pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
673 super::each_addr(addr, |addr| self.0.connect(addr))
676 /// Sends data on the socket to the remote address to which it is connected.
678 /// The [`connect`] method will connect this socket to a remote address. This
679 /// method will fail if the socket is not connected.
681 /// [`connect`]: #method.connect
686 /// use std::net::UdpSocket;
688 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
689 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
690 /// socket.send(&[0, 1, 2]).expect("couldn't send message");
692 #[stable(feature = "net2_mutators", since = "1.9.0")]
693 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
697 /// Receives a single datagram message on the socket from the remote address to
698 /// which it is connected. On success, returns the number of bytes read.
700 /// The function must be called with valid byte array `buf` of sufficient size to
701 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
702 /// excess bytes may be discarded.
704 /// The [`connect`] method will connect this socket to a remote address. This
705 /// method will fail if the socket is not connected.
707 /// [`connect`]: #method.connect
712 /// use std::net::UdpSocket;
714 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
715 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
716 /// let mut buf = [0; 10];
717 /// match socket.recv(&mut buf) {
718 /// Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]),
719 /// Err(e) => println!("recv function failed: {:?}", e),
722 #[stable(feature = "net2_mutators", since = "1.9.0")]
723 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
727 /// Receives single datagram on the socket from the remote address to which it is
728 /// connected, without removing the message from input queue. On success, returns
729 /// the number of bytes peeked.
731 /// The function must be called with valid byte array `buf` of sufficient size to
732 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
733 /// excess bytes may be discarded.
735 /// Successive calls return the same data. This is accomplished by passing
736 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
738 /// Do not use this function to implement busy waiting, instead use `libc::poll` to
739 /// synchronize IO events on one or more sockets.
741 /// The [`connect`] method will connect this socket to a remote address. This
742 /// method will fail if the socket is not connected.
744 /// [`connect`]: #method.connect
748 /// This method will fail if the socket is not connected. The `connect` method
749 /// will connect this socket to a remote address.
754 /// use std::net::UdpSocket;
756 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
757 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
758 /// let mut buf = [0; 10];
759 /// match socket.peek(&mut buf) {
760 /// Ok(received) => println!("received {} bytes", received),
761 /// Err(e) => println!("peek function failed: {:?}", e),
764 #[stable(feature = "peek", since = "1.18.0")]
765 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
769 /// Moves this UDP socket into or out of nonblocking mode.
771 /// This will result in `recv`, `recv_from`, `send`, and `send_to`
772 /// operations becoming nonblocking, i.e., immediately returning from their
773 /// calls. If the IO operation is successful, `Ok` is returned and no
774 /// further action is required. If the IO operation could not be completed
775 /// and needs to be retried, an error with kind
776 /// [`io::ErrorKind::WouldBlock`] is returned.
778 /// On Unix platforms, calling this method corresponds to calling `fcntl`
779 /// `FIONBIO`. On Windows calling this method corresponds to calling
780 /// `ioctlsocket` `FIONBIO`.
782 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
786 /// Creates a UDP socket bound to `127.0.0.1:7878` and read bytes in
787 /// nonblocking mode:
791 /// use std::net::UdpSocket;
793 /// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
794 /// socket.set_nonblocking(true).unwrap();
796 /// # fn wait_for_fd() { unimplemented!() }
797 /// let mut buf = [0; 10];
798 /// let (num_bytes_read, _) = loop {
799 /// match socket.recv_from(&mut buf) {
800 /// Ok(n) => break n,
801 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
802 /// // wait until network socket is ready, typically implemented
803 /// // via platform-specific APIs such as epoll or IOCP
806 /// Err(e) => panic!("encountered IO error: {}", e),
809 /// println!("bytes: {:?}", &buf[..num_bytes_read]);
811 #[stable(feature = "net2_mutators", since = "1.9.0")]
812 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
813 self.0.set_nonblocking(nonblocking)
817 impl AsInner<net_imp::UdpSocket> for UdpSocket {
818 fn as_inner(&self) -> &net_imp::UdpSocket {
823 impl FromInner<net_imp::UdpSocket> for UdpSocket {
824 fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket {
829 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
830 fn into_inner(self) -> net_imp::UdpSocket {
835 #[stable(feature = "rust1", since = "1.0.0")]
836 impl fmt::Debug for UdpSocket {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
842 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten", target_env = "sgx"))))]
844 use crate::io::ErrorKind;
845 use crate::net::test::{next_test_ip4, next_test_ip6};
847 use crate::sync::mpsc::channel;
848 use crate::sys_common::AsInner;
850 use crate::time::{Duration, Instant};
852 fn each_ip(f: &mut dyn FnMut(SocketAddr, SocketAddr)) {
853 f(next_test_ip4(), next_test_ip4());
854 f(next_test_ip6(), next_test_ip6());
861 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
868 match UdpSocket::bind("1.1.1.1:9999") {
870 Err(e) => assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
875 fn socket_smoke_test_ip4() {
876 each_ip(&mut |server_ip, client_ip| {
877 let (tx1, rx1) = channel();
878 let (tx2, rx2) = channel();
880 let _t = thread::spawn(move || {
881 let client = t!(UdpSocket::bind(&client_ip));
883 t!(client.send_to(&[99], &server_ip));
884 tx2.send(()).unwrap();
887 let server = t!(UdpSocket::bind(&server_ip));
888 tx1.send(()).unwrap();
890 let (nread, src) = t!(server.recv_from(&mut buf));
891 assert_eq!(nread, 1);
892 assert_eq!(buf[0], 99);
893 assert_eq!(src, client_ip);
900 each_ip(&mut |addr, _| {
901 let server = t!(UdpSocket::bind(&addr));
902 assert_eq!(addr, t!(server.local_addr()));
908 each_ip(&mut |addr1, addr2| {
909 let server = t!(UdpSocket::bind(&addr1));
910 assert_eq!(server.peer_addr().unwrap_err().kind(), ErrorKind::NotConnected);
911 t!(server.connect(&addr2));
912 assert_eq!(addr2, t!(server.peer_addr()));
917 fn udp_clone_smoke() {
918 each_ip(&mut |addr1, addr2| {
919 let sock1 = t!(UdpSocket::bind(&addr1));
920 let sock2 = t!(UdpSocket::bind(&addr2));
922 let _t = thread::spawn(move || {
923 let mut buf = [0, 0];
924 assert_eq!(sock2.recv_from(&mut buf).unwrap(), (1, addr1));
925 assert_eq!(buf[0], 1);
926 t!(sock2.send_to(&[2], &addr1));
929 let sock3 = t!(sock1.try_clone());
931 let (tx1, rx1) = channel();
932 let (tx2, rx2) = channel();
933 let _t = thread::spawn(move || {
935 t!(sock3.send_to(&[1], &addr2));
936 tx2.send(()).unwrap();
938 tx1.send(()).unwrap();
939 let mut buf = [0, 0];
940 assert_eq!(sock1.recv_from(&mut buf).unwrap(), (1, addr2));
946 fn udp_clone_two_read() {
947 each_ip(&mut |addr1, addr2| {
948 let sock1 = t!(UdpSocket::bind(&addr1));
949 let sock2 = t!(UdpSocket::bind(&addr2));
950 let (tx1, rx) = channel();
951 let tx2 = tx1.clone();
953 let _t = thread::spawn(move || {
954 t!(sock2.send_to(&[1], &addr1));
956 t!(sock2.send_to(&[2], &addr1));
960 let sock3 = t!(sock1.try_clone());
962 let (done, rx) = channel();
963 let _t = thread::spawn(move || {
964 let mut buf = [0, 0];
965 t!(sock3.recv_from(&mut buf));
966 tx2.send(()).unwrap();
967 done.send(()).unwrap();
969 let mut buf = [0, 0];
970 t!(sock1.recv_from(&mut buf));
971 tx1.send(()).unwrap();
978 fn udp_clone_two_write() {
979 each_ip(&mut |addr1, addr2| {
980 let sock1 = t!(UdpSocket::bind(&addr1));
981 let sock2 = t!(UdpSocket::bind(&addr2));
983 let (tx, rx) = channel();
984 let (serv_tx, serv_rx) = channel();
986 let _t = thread::spawn(move || {
987 let mut buf = [0, 1];
989 t!(sock2.recv_from(&mut buf));
990 serv_tx.send(()).unwrap();
993 let sock3 = t!(sock1.try_clone());
995 let (done, rx) = channel();
996 let tx2 = tx.clone();
997 let _t = thread::spawn(move || {
998 match sock3.send_to(&[1], &addr2) {
1000 let _ = tx2.send(());
1004 done.send(()).unwrap();
1006 match sock1.send_to(&[2], &addr2) {
1008 let _ = tx.send(());
1015 serv_rx.recv().unwrap();
1021 let name = if cfg!(windows) { "socket" } else { "fd" };
1022 let socket_addr = next_test_ip4();
1024 let udpsock = t!(UdpSocket::bind(&socket_addr));
1025 let udpsock_inner = udpsock.0.socket().as_inner();
1027 format!("UdpSocket {{ addr: {:?}, {}: {:?} }}", socket_addr, name, udpsock_inner);
1028 assert_eq!(format!("{:?}", udpsock), compare);
1031 // FIXME: re-enabled openbsd/netbsd tests once their socket timeout code
1032 // no longer has rounding errors.
1033 // VxWorks ignores SO_SNDTIMEO.
1034 #[cfg_attr(any(target_os = "netbsd", target_os = "openbsd", target_os = "vxworks"), ignore)]
1037 let addr = next_test_ip4();
1039 let stream = t!(UdpSocket::bind(&addr));
1040 let dur = Duration::new(15410, 0);
1042 assert_eq!(None, t!(stream.read_timeout()));
1044 t!(stream.set_read_timeout(Some(dur)));
1045 assert_eq!(Some(dur), t!(stream.read_timeout()));
1047 assert_eq!(None, t!(stream.write_timeout()));
1049 t!(stream.set_write_timeout(Some(dur)));
1050 assert_eq!(Some(dur), t!(stream.write_timeout()));
1052 t!(stream.set_read_timeout(None));
1053 assert_eq!(None, t!(stream.read_timeout()));
1055 t!(stream.set_write_timeout(None));
1056 assert_eq!(None, t!(stream.write_timeout()));
1060 fn test_read_timeout() {
1061 let addr = next_test_ip4();
1063 let stream = t!(UdpSocket::bind(&addr));
1064 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1066 let mut buf = [0; 10];
1068 let start = Instant::now();
1070 let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
1071 if kind != ErrorKind::Interrupted {
1073 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1074 "unexpected_error: {:?}",
1080 assert!(start.elapsed() > Duration::from_millis(400));
1084 fn test_read_with_timeout() {
1085 let addr = next_test_ip4();
1087 let stream = t!(UdpSocket::bind(&addr));
1088 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1090 t!(stream.send_to(b"hello world", &addr));
1092 let mut buf = [0; 11];
1093 t!(stream.recv_from(&mut buf));
1094 assert_eq!(b"hello world", &buf[..]);
1096 let start = Instant::now();
1098 let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
1099 if kind != ErrorKind::Interrupted {
1101 kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1102 "unexpected_error: {:?}",
1108 assert!(start.elapsed() > Duration::from_millis(400));
1111 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1112 // when passed zero Durations
1114 fn test_timeout_zero_duration() {
1115 let addr = next_test_ip4();
1117 let socket = t!(UdpSocket::bind(&addr));
1119 let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
1120 let err = result.unwrap_err();
1121 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1123 let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
1124 let err = result.unwrap_err();
1125 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1129 fn connect_send_recv() {
1130 let addr = next_test_ip4();
1132 let socket = t!(UdpSocket::bind(&addr));
1133 t!(socket.connect(addr));
1135 t!(socket.send(b"hello world"));
1137 let mut buf = [0; 11];
1138 t!(socket.recv(&mut buf));
1139 assert_eq!(b"hello world", &buf[..]);
1143 fn connect_send_peek_recv() {
1144 each_ip(&mut |addr, _| {
1145 let socket = t!(UdpSocket::bind(&addr));
1146 t!(socket.connect(addr));
1148 t!(socket.send(b"hello world"));
1151 let mut buf = [0; 11];
1152 let size = t!(socket.peek(&mut buf));
1153 assert_eq!(b"hello world", &buf[..]);
1154 assert_eq!(size, 11);
1157 let mut buf = [0; 11];
1158 let size = t!(socket.recv(&mut buf));
1159 assert_eq!(b"hello world", &buf[..]);
1160 assert_eq!(size, 11);
1166 each_ip(&mut |addr, _| {
1167 let socket = t!(UdpSocket::bind(&addr));
1168 t!(socket.send_to(b"hello world", &addr));
1171 let mut buf = [0; 11];
1172 let (size, _) = t!(socket.peek_from(&mut buf));
1173 assert_eq!(b"hello world", &buf[..]);
1174 assert_eq!(size, 11);
1177 let mut buf = [0; 11];
1178 let (size, _) = t!(socket.recv_from(&mut buf));
1179 assert_eq!(b"hello world", &buf[..]);
1180 assert_eq!(size, 11);
1188 let addr = next_test_ip4();
1190 let stream = t!(UdpSocket::bind(&addr));
1192 t!(stream.set_ttl(ttl));
1193 assert_eq!(ttl, t!(stream.ttl()));
1197 fn set_nonblocking() {
1198 each_ip(&mut |addr, _| {
1199 let socket = t!(UdpSocket::bind(&addr));
1201 t!(socket.set_nonblocking(true));
1202 t!(socket.set_nonblocking(false));
1204 t!(socket.connect(addr));
1206 t!(socket.set_nonblocking(false));
1207 t!(socket.set_nonblocking(true));
1210 match socket.recv(&mut buf) {
1211 Ok(_) => panic!("expected error"),
1212 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1213 Err(e) => panic!("unexpected error {}", e),