1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use io::{self, Error, ErrorKind};
13 use net::{ToSocketAddrs, SocketAddr, Ipv4Addr, Ipv6Addr};
14 use sys_common::net as net_imp;
15 use sys_common::{AsInner, FromInner, IntoInner};
20 /// After creating a `UdpSocket` by [`bind`]ing it to a socket address, data can be
21 /// [sent to] and [received from] any other socket address.
23 /// Although UDP is a connectionless protocol, this implementation provides an interface
24 /// to set an address where data should be sent and received from. After setting a remote
25 /// address with [`connect`], data can be sent to and received from that address with
26 /// [`send`] and [`recv`].
28 /// As stated in the User Datagram Protocol's specification in [IETF RFC 768], UDP is
29 /// an unordered, unreliable protocol; refer to [`TcpListener`] and [`TcpStream`] for TCP
32 /// [`bind`]: #method.bind
33 /// [`connect`]: #method.connect
34 /// [IETF RFC 768]: https://tools.ietf.org/html/rfc768
35 /// [`recv`]: #method.recv
36 /// [received from]: #method.recv_from
37 /// [`send`]: #method.send
38 /// [sent to]: #method.send_to
39 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
40 /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
45 /// use std::net::UdpSocket;
47 /// fn main() -> std::io::Result<()> {
49 /// let mut socket = UdpSocket::bind("127.0.0.1:34254")?;
51 /// // Receives a single datagram message on the socket. If `buf` is too small to hold
52 /// // the message, it will be cut off.
53 /// let mut buf = [0; 10];
54 /// let (amt, src) = socket.recv_from(&mut buf)?;
56 /// // Redeclare `buf` as slice of the received data and send reverse data back to origin.
57 /// let buf = &mut buf[..amt];
59 /// socket.send_to(buf, &src)?;
60 /// } // the socket is closed here
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub struct UdpSocket(net_imp::UdpSocket);
68 /// Creates a UDP socket from the given address.
70 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
71 /// its documentation for concrete examples.
73 /// If `addr` yields multiple addresses, `bind` will be attempted with
74 /// each of the addresses until one succeeds and returns the socket. If none
75 /// of the addresses succeed in creating a socket, the error returned from
76 /// the last attempt (the last address) is returned.
78 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
82 /// Create a UDP socket bound to `127.0.0.1:3400`:
85 /// use std::net::UdpSocket;
87 /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
90 /// Create a UDP socket bound to `127.0.0.1:3400`. If the socket cannot be
91 /// bound to that address, create a UDP socket bound to `127.0.0.1:3401`:
94 /// use std::net::{SocketAddr, UdpSocket};
97 /// SocketAddr::from(([127, 0, 0, 1], 3400)),
98 /// SocketAddr::from(([127, 0, 0, 1], 3401)),
100 /// let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address");
102 #[stable(feature = "rust1", since = "1.0.0")]
103 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
104 super::each_addr(addr, net_imp::UdpSocket::bind).map(UdpSocket)
107 /// Receives a single datagram message on the socket. On success, returns the number
108 /// of bytes read and the origin.
110 /// The function must be called with valid byte array `buf` of sufficient size to
111 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
112 /// excess bytes may be discarded.
117 /// use std::net::UdpSocket;
119 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
120 /// let mut buf = [0; 10];
121 /// let (number_of_bytes, src_addr) = socket.recv_from(&mut buf)
122 /// .expect("Didn't receive data");
123 /// let filled_buf = &mut buf[..number_of_bytes];
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
127 self.0.recv_from(buf)
130 /// Receives a single datagram message on the socket, without removing it from the
131 /// queue. On success, returns the number of bytes read and the origin.
133 /// The function must be called with valid byte array `buf` of sufficient size to
134 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
135 /// excess bytes may be discarded.
137 /// Successive calls return the same data. This is accomplished by passing
138 /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
140 /// Do not use this function to implement busy waiting, instead use `libc::poll` to
141 /// synchronize IO events on one or more sockets.
146 /// use std::net::UdpSocket;
148 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
149 /// let mut buf = [0; 10];
150 /// let (number_of_bytes, src_addr) = socket.peek_from(&mut buf)
151 /// .expect("Didn't receive data");
152 /// let filled_buf = &mut buf[..number_of_bytes];
154 #[stable(feature = "peek", since = "1.18.0")]
155 pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
156 self.0.peek_from(buf)
159 /// Sends data on the socket to the given address. On success, returns the
160 /// number of bytes written.
162 /// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
163 /// documentation for concrete examples.
165 /// It is possible for `addr` to yield multiple addresses, but `send_to`
166 /// will only send data to the first address yielded by `addr`.
168 /// This will return an error when the IP version of the local socket
169 /// does not match that returned from [`ToSocketAddrs`].
171 /// See <https://github.com/rust-lang/rust/issues/34202> for more details.
173 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
178 /// use std::net::UdpSocket;
180 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
181 /// socket.send_to(&[0; 10], "127.0.0.1:4242").expect("couldn't send data");
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
185 -> io::Result<usize> {
186 match addr.to_socket_addrs()?.next() {
187 Some(addr) => self.0.send_to(buf, &addr),
188 None => Err(Error::new(ErrorKind::InvalidInput,
189 "no addresses to send data to")),
193 /// Returns the socket address that this socket was created from.
198 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
200 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
201 /// assert_eq!(socket.local_addr().unwrap(),
202 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 34254)));
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn local_addr(&self) -> io::Result<SocketAddr> {
209 /// Creates a new independently owned handle to the underlying socket.
211 /// The returned `UdpSocket` is a reference to the same socket that this
212 /// object references. Both handles will read and write the same port, and
213 /// options set on one socket will be propagated to the other.
218 /// use std::net::UdpSocket;
220 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
221 /// let socket_clone = socket.try_clone().expect("couldn't clone the socket");
223 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn try_clone(&self) -> io::Result<UdpSocket> {
225 self.0.duplicate().map(UdpSocket)
228 /// Sets the read timeout to the timeout specified.
230 /// If the value specified is [`None`], then [`read`] calls will block
231 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
232 /// passed to this method.
234 /// # Platform-specific behavior
236 /// Platforms may return a different error code whenever a read times out as
237 /// a result of setting this option. For example Unix typically returns an
238 /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
240 /// [`None`]: ../../std/option/enum.Option.html#variant.None
241 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
242 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
243 /// [`Duration`]: ../../std/time/struct.Duration.html
244 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
245 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
250 /// use std::net::UdpSocket;
252 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
253 /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
256 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
261 /// use std::net::UdpSocket;
262 /// use std::time::Duration;
264 /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
265 /// let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
266 /// let err = result.unwrap_err();
267 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
269 #[stable(feature = "socket_timeout", since = "1.4.0")]
270 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
271 self.0.set_read_timeout(dur)
274 /// Sets the write timeout to the timeout specified.
276 /// If the value specified is [`None`], then [`write`] calls will block
277 /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
278 /// passed to this method.
280 /// # Platform-specific behavior
282 /// Platforms may return a different error code whenever a write times out
283 /// as a result of setting this option. For example Unix typically returns
284 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
286 /// [`None`]: ../../std/option/enum.Option.html#variant.None
287 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
288 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
289 /// [`Duration`]: ../../std/time/struct.Duration.html
290 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
291 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
296 /// use std::net::UdpSocket;
298 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
299 /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
302 /// An [`Err`] is returned if the zero [`Duration`] is passed to this
307 /// use std::net::UdpSocket;
308 /// use std::time::Duration;
310 /// let socket = UdpSocket::bind("127.0.0.1:34254").unwrap();
311 /// let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
312 /// let err = result.unwrap_err();
313 /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
315 #[stable(feature = "socket_timeout", since = "1.4.0")]
316 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
317 self.0.set_write_timeout(dur)
320 /// Returns the read timeout of this socket.
322 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
324 /// [`None`]: ../../std/option/enum.Option.html#variant.None
325 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
330 /// use std::net::UdpSocket;
332 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
333 /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
334 /// assert_eq!(socket.read_timeout().unwrap(), None);
336 #[stable(feature = "socket_timeout", since = "1.4.0")]
337 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
338 self.0.read_timeout()
341 /// Returns the write timeout of this socket.
343 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
345 /// [`None`]: ../../std/option/enum.Option.html#variant.None
346 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
351 /// use std::net::UdpSocket;
353 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
354 /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
355 /// assert_eq!(socket.write_timeout().unwrap(), None);
357 #[stable(feature = "socket_timeout", since = "1.4.0")]
358 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
359 self.0.write_timeout()
362 /// Sets the value of the `SO_BROADCAST` option for this socket.
364 /// When enabled, this socket is allowed to send packets to a broadcast
370 /// use std::net::UdpSocket;
372 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
373 /// socket.set_broadcast(false).expect("set_broadcast call failed");
375 #[stable(feature = "net2_mutators", since = "1.9.0")]
376 pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
377 self.0.set_broadcast(broadcast)
380 /// Gets the value of the `SO_BROADCAST` option for this socket.
382 /// For more information about this option, see
383 /// [`set_broadcast`][link].
385 /// [link]: #method.set_broadcast
390 /// use std::net::UdpSocket;
392 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
393 /// socket.set_broadcast(false).expect("set_broadcast call failed");
394 /// assert_eq!(socket.broadcast().unwrap(), false);
396 #[stable(feature = "net2_mutators", since = "1.9.0")]
397 pub fn broadcast(&self) -> io::Result<bool> {
401 /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
403 /// If enabled, multicast packets will be looped back to the local socket.
404 /// Note that this may not have any affect on IPv6 sockets.
409 /// use std::net::UdpSocket;
411 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
412 /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
414 #[stable(feature = "net2_mutators", since = "1.9.0")]
415 pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
416 self.0.set_multicast_loop_v4(multicast_loop_v4)
419 /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
421 /// For more information about this option, see
422 /// [`set_multicast_loop_v4`][link].
424 /// [link]: #method.set_multicast_loop_v4
429 /// use std::net::UdpSocket;
431 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
432 /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
433 /// assert_eq!(socket.multicast_loop_v4().unwrap(), false);
435 #[stable(feature = "net2_mutators", since = "1.9.0")]
436 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
437 self.0.multicast_loop_v4()
440 /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
442 /// Indicates the time-to-live value of outgoing multicast packets for
443 /// this socket. The default value is 1 which means that multicast packets
444 /// don't leave the local network unless explicitly requested.
446 /// Note that this may not have any affect on IPv6 sockets.
451 /// use std::net::UdpSocket;
453 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
454 /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
456 #[stable(feature = "net2_mutators", since = "1.9.0")]
457 pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
458 self.0.set_multicast_ttl_v4(multicast_ttl_v4)
461 /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
463 /// For more information about this option, see
464 /// [`set_multicast_ttl_v4`][link].
466 /// [link]: #method.set_multicast_ttl_v4
471 /// use std::net::UdpSocket;
473 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
474 /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
475 /// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
477 #[stable(feature = "net2_mutators", since = "1.9.0")]
478 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
479 self.0.multicast_ttl_v4()
482 /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
484 /// Controls whether this socket sees the multicast packets it sends itself.
485 /// Note that this may not have any affect on IPv4 sockets.
490 /// use std::net::UdpSocket;
492 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
493 /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
495 #[stable(feature = "net2_mutators", since = "1.9.0")]
496 pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
497 self.0.set_multicast_loop_v6(multicast_loop_v6)
500 /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
502 /// For more information about this option, see
503 /// [`set_multicast_loop_v6`][link].
505 /// [link]: #method.set_multicast_loop_v6
510 /// use std::net::UdpSocket;
512 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
513 /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
514 /// assert_eq!(socket.multicast_loop_v6().unwrap(), false);
516 #[stable(feature = "net2_mutators", since = "1.9.0")]
517 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
518 self.0.multicast_loop_v6()
521 /// Sets the value for the `IP_TTL` option on this socket.
523 /// This value sets the time-to-live field that is used in every packet sent
524 /// from this socket.
529 /// use std::net::UdpSocket;
531 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
532 /// socket.set_ttl(42).expect("set_ttl call failed");
534 #[stable(feature = "net2_mutators", since = "1.9.0")]
535 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
539 /// Gets the value of the `IP_TTL` option for this socket.
541 /// For more information about this option, see [`set_ttl`][link].
543 /// [link]: #method.set_ttl
548 /// use std::net::UdpSocket;
550 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
551 /// socket.set_ttl(42).expect("set_ttl call failed");
552 /// assert_eq!(socket.ttl().unwrap(), 42);
554 #[stable(feature = "net2_mutators", since = "1.9.0")]
555 pub fn ttl(&self) -> io::Result<u32> {
559 /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
561 /// This function specifies a new multicast group for this socket to join.
562 /// The address must be a valid multicast address, and `interface` is the
563 /// address of the local interface with which the system should join the
564 /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
565 /// interface is chosen by the system.
566 #[stable(feature = "net2_mutators", since = "1.9.0")]
567 pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
568 self.0.join_multicast_v4(multiaddr, interface)
571 /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
573 /// This function specifies a new multicast group for this socket to join.
574 /// The address must be a valid multicast address, and `interface` is the
575 /// index of the interface to join/leave (or 0 to indicate any interface).
576 #[stable(feature = "net2_mutators", since = "1.9.0")]
577 pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
578 self.0.join_multicast_v6(multiaddr, interface)
581 /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
583 /// For more information about this option, see
584 /// [`join_multicast_v4`][link].
586 /// [link]: #method.join_multicast_v4
587 #[stable(feature = "net2_mutators", since = "1.9.0")]
588 pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
589 self.0.leave_multicast_v4(multiaddr, interface)
592 /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
594 /// For more information about this option, see
595 /// [`join_multicast_v6`][link].
597 /// [link]: #method.join_multicast_v6
598 #[stable(feature = "net2_mutators", since = "1.9.0")]
599 pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
600 self.0.leave_multicast_v6(multiaddr, interface)
603 /// Get the value of the `SO_ERROR` option on this socket.
605 /// This will retrieve the stored error in the underlying socket, clearing
606 /// the field in the process. This can be useful for checking errors between
612 /// use std::net::UdpSocket;
614 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
615 /// match socket.take_error() {
616 /// Ok(Some(error)) => println!("UdpSocket error: {:?}", error),
617 /// Ok(None) => println!("No error"),
618 /// Err(error) => println!("UdpSocket.take_error failed: {:?}", error),
621 #[stable(feature = "net2_mutators", since = "1.9.0")]
622 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
626 /// Connects this UDP socket to a remote address, allowing the `send` and
627 /// `recv` syscalls to be used to send data and also applies filters to only
628 /// receive data from the specified address.
630 /// If `addr` yields multiple addresses, `connect` will be attempted with
631 /// each of the addresses until the underlying OS function returns no
632 /// error. Note that usually, a successful `connect` call does not specify
633 /// that there is a remote server listening on the port, rather, such an
634 /// error would only be detected after the first send. If the OS returns an
635 /// error for each of the specified addresses, the error returned from the
636 /// last connection attempt (the last address) is returned.
640 /// Create a UDP socket bound to `127.0.0.1:3400` and connect the socket to
641 /// `127.0.0.1:8080`:
644 /// use std::net::UdpSocket;
646 /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
647 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
650 /// Unlike in the TCP case, passing an array of addresses to the `connect`
651 /// function of a UDP socket is not a useful thing to do: The OS will be
652 /// unable to determine whether something is listening on the remote
653 /// address without the application sending data.
654 #[stable(feature = "net2_mutators", since = "1.9.0")]
655 pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
656 super::each_addr(addr, |addr| self.0.connect(addr))
659 /// Sends data on the socket to the remote address to which it is connected.
661 /// The [`connect`] method will connect this socket to a remote address. This
662 /// method will fail if the socket is not connected.
664 /// [`connect`]: #method.connect
669 /// use std::net::UdpSocket;
671 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
672 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
673 /// socket.send(&[0, 1, 2]).expect("couldn't send message");
675 #[stable(feature = "net2_mutators", since = "1.9.0")]
676 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
680 /// Receives a single datagram message on the socket from the remote address to
681 /// which it is connected. On success, returns the number of bytes read.
683 /// The function must be called with valid byte array `buf` of sufficient size to
684 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
685 /// excess bytes may be discarded.
687 /// The [`connect`] method will connect this socket to a remote address. This
688 /// method will fail if the socket is not connected.
690 /// [`connect`]: #method.connect
695 /// use std::net::UdpSocket;
697 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
698 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
699 /// let mut buf = [0; 10];
700 /// match socket.recv(&mut buf) {
701 /// Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]),
702 /// Err(e) => println!("recv function failed: {:?}", e),
705 #[stable(feature = "net2_mutators", since = "1.9.0")]
706 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
710 /// Receives single datagram on the socket from the remote address to which it is
711 /// connected, without removing the message from input queue. On success, returns
712 /// the number of bytes peeked.
714 /// The function must be called with valid byte array `buf` of sufficient size to
715 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
716 /// excess bytes may be discarded.
718 /// Successive calls return the same data. This is accomplished by passing
719 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
721 /// Do not use this function to implement busy waiting, instead use `libc::poll` to
722 /// synchronize IO events on one or more sockets.
724 /// The [`connect`] method will connect this socket to a remote address. This
725 /// method will fail if the socket is not connected.
727 /// [`connect`]: #method.connect
731 /// This method will fail if the socket is not connected. The `connect` method
732 /// will connect this socket to a remote address.
737 /// use std::net::UdpSocket;
739 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
740 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
741 /// let mut buf = [0; 10];
742 /// match socket.peek(&mut buf) {
743 /// Ok(received) => println!("received {} bytes", received),
744 /// Err(e) => println!("peek function failed: {:?}", e),
747 #[stable(feature = "peek", since = "1.18.0")]
748 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
752 /// Moves this UDP socket into or out of nonblocking mode.
754 /// This will result in `recv`, `recv_from`, `send`, and `send_to`
755 /// operations becoming nonblocking, i.e. immediately returning from their
756 /// calls. If the IO operation is successful, `Ok` is returned and no
757 /// further action is required. If the IO operation could not be completed
758 /// and needs to be retried, an error with kind
759 /// [`io::ErrorKind::WouldBlock`] is returned.
761 /// On Unix platforms, calling this method corresponds to calling `fcntl`
762 /// `FIONBIO`. On Windows calling this method corresponds to calling
763 /// `ioctlsocket` `FIONBIO`.
765 /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
769 /// Create a UDP socket bound to `127.0.0.1:7878` and read bytes in
770 /// nonblocking mode:
774 /// use std::net::UdpSocket;
776 /// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
777 /// socket.set_nonblocking(true).unwrap();
779 /// # fn wait_for_fd() { unimplemented!() }
780 /// let mut buf = [0; 10];
781 /// let (num_bytes_read, _) = loop {
782 /// match socket.recv_from(&mut buf) {
783 /// Ok(n) => break n,
784 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
785 /// // wait until network socket is ready, typically implemented
786 /// // via platform-specific APIs such as epoll or IOCP
789 /// Err(e) => panic!("encountered IO error: {}", e),
792 /// println!("bytes: {:?}", &buf[..num_bytes_read]);
794 #[stable(feature = "net2_mutators", since = "1.9.0")]
795 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
796 self.0.set_nonblocking(nonblocking)
800 impl AsInner<net_imp::UdpSocket> for UdpSocket {
801 fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 }
804 impl FromInner<net_imp::UdpSocket> for UdpSocket {
805 fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) }
808 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
809 fn into_inner(self) -> net_imp::UdpSocket { self.0 }
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl fmt::Debug for UdpSocket {
814 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
819 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
823 use net::test::{next_test_ip4, next_test_ip6};
824 use sync::mpsc::channel;
825 use sys_common::AsInner;
826 use time::{Instant, Duration};
829 fn each_ip(f: &mut FnMut(SocketAddr, SocketAddr)) {
830 f(next_test_ip4(), next_test_ip4());
831 f(next_test_ip6(), next_test_ip6());
838 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
845 match UdpSocket::bind("1.1.1.1:9999") {
848 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable)
854 fn socket_smoke_test_ip4() {
855 each_ip(&mut |server_ip, client_ip| {
856 let (tx1, rx1) = channel();
857 let (tx2, rx2) = channel();
859 let _t = thread::spawn(move|| {
860 let client = t!(UdpSocket::bind(&client_ip));
862 t!(client.send_to(&[99], &server_ip));
863 tx2.send(()).unwrap();
866 let server = t!(UdpSocket::bind(&server_ip));
867 tx1.send(()).unwrap();
869 let (nread, src) = t!(server.recv_from(&mut buf));
870 assert_eq!(nread, 1);
871 assert_eq!(buf[0], 99);
872 assert_eq!(src, client_ip);
878 fn socket_name_ip4() {
879 each_ip(&mut |addr, _| {
880 let server = t!(UdpSocket::bind(&addr));
881 assert_eq!(addr, t!(server.local_addr()));
886 fn udp_clone_smoke() {
887 each_ip(&mut |addr1, addr2| {
888 let sock1 = t!(UdpSocket::bind(&addr1));
889 let sock2 = t!(UdpSocket::bind(&addr2));
891 let _t = thread::spawn(move|| {
892 let mut buf = [0, 0];
893 assert_eq!(sock2.recv_from(&mut buf).unwrap(), (1, addr1));
894 assert_eq!(buf[0], 1);
895 t!(sock2.send_to(&[2], &addr1));
898 let sock3 = t!(sock1.try_clone());
900 let (tx1, rx1) = channel();
901 let (tx2, rx2) = channel();
902 let _t = thread::spawn(move|| {
904 t!(sock3.send_to(&[1], &addr2));
905 tx2.send(()).unwrap();
907 tx1.send(()).unwrap();
908 let mut buf = [0, 0];
909 assert_eq!(sock1.recv_from(&mut buf).unwrap(), (1, addr2));
915 fn udp_clone_two_read() {
916 each_ip(&mut |addr1, addr2| {
917 let sock1 = t!(UdpSocket::bind(&addr1));
918 let sock2 = t!(UdpSocket::bind(&addr2));
919 let (tx1, rx) = channel();
920 let tx2 = tx1.clone();
922 let _t = thread::spawn(move|| {
923 t!(sock2.send_to(&[1], &addr1));
925 t!(sock2.send_to(&[2], &addr1));
929 let sock3 = t!(sock1.try_clone());
931 let (done, rx) = channel();
932 let _t = thread::spawn(move|| {
933 let mut buf = [0, 0];
934 t!(sock3.recv_from(&mut buf));
935 tx2.send(()).unwrap();
936 done.send(()).unwrap();
938 let mut buf = [0, 0];
939 t!(sock1.recv_from(&mut buf));
940 tx1.send(()).unwrap();
947 fn udp_clone_two_write() {
948 each_ip(&mut |addr1, addr2| {
949 let sock1 = t!(UdpSocket::bind(&addr1));
950 let sock2 = t!(UdpSocket::bind(&addr2));
952 let (tx, rx) = channel();
953 let (serv_tx, serv_rx) = channel();
955 let _t = thread::spawn(move|| {
956 let mut buf = [0, 1];
958 t!(sock2.recv_from(&mut buf));
959 serv_tx.send(()).unwrap();
962 let sock3 = t!(sock1.try_clone());
964 let (done, rx) = channel();
965 let tx2 = tx.clone();
966 let _t = thread::spawn(move|| {
967 match sock3.send_to(&[1], &addr2) {
968 Ok(..) => { let _ = tx2.send(()); }
971 done.send(()).unwrap();
973 match sock1.send_to(&[2], &addr2) {
974 Ok(..) => { let _ = tx.send(()); }
980 serv_rx.recv().unwrap();
986 let name = if cfg!(windows) {"socket"} else {"fd"};
987 let socket_addr = next_test_ip4();
989 let udpsock = t!(UdpSocket::bind(&socket_addr));
990 let udpsock_inner = udpsock.0.socket().as_inner();
991 let compare = format!("UdpSocket {{ addr: {:?}, {}: {:?} }}",
992 socket_addr, name, udpsock_inner);
993 assert_eq!(format!("{:?}", udpsock), compare);
996 // FIXME: re-enabled bitrig/openbsd/netbsd tests once their socket timeout code
997 // no longer has rounding errors.
998 #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1001 let addr = next_test_ip4();
1003 let stream = t!(UdpSocket::bind(&addr));
1004 let dur = Duration::new(15410, 0);
1006 assert_eq!(None, t!(stream.read_timeout()));
1008 t!(stream.set_read_timeout(Some(dur)));
1009 assert_eq!(Some(dur), t!(stream.read_timeout()));
1011 assert_eq!(None, t!(stream.write_timeout()));
1013 t!(stream.set_write_timeout(Some(dur)));
1014 assert_eq!(Some(dur), t!(stream.write_timeout()));
1016 t!(stream.set_read_timeout(None));
1017 assert_eq!(None, t!(stream.read_timeout()));
1019 t!(stream.set_write_timeout(None));
1020 assert_eq!(None, t!(stream.write_timeout()));
1024 fn test_read_timeout() {
1025 let addr = next_test_ip4();
1027 let stream = t!(UdpSocket::bind(&addr));
1028 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1030 let mut buf = [0; 10];
1032 let start = Instant::now();
1033 let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
1034 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1035 assert!(start.elapsed() > Duration::from_millis(400));
1039 fn test_read_with_timeout() {
1040 let addr = next_test_ip4();
1042 let stream = t!(UdpSocket::bind(&addr));
1043 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1045 t!(stream.send_to(b"hello world", &addr));
1047 let mut buf = [0; 11];
1048 t!(stream.recv_from(&mut buf));
1049 assert_eq!(b"hello world", &buf[..]);
1051 let start = Instant::now();
1052 let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
1053 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
1054 assert!(start.elapsed() > Duration::from_millis(400));
1057 // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1058 // when passed zero Durations
1060 fn test_timeout_zero_duration() {
1061 let addr = next_test_ip4();
1063 let socket = t!(UdpSocket::bind(&addr));
1065 let result = socket.set_write_timeout(Some(Duration::new(0, 0)));
1066 let err = result.unwrap_err();
1067 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1069 let result = socket.set_read_timeout(Some(Duration::new(0, 0)));
1070 let err = result.unwrap_err();
1071 assert_eq!(err.kind(), ErrorKind::InvalidInput);
1075 fn connect_send_recv() {
1076 let addr = next_test_ip4();
1078 let socket = t!(UdpSocket::bind(&addr));
1079 t!(socket.connect(addr));
1081 t!(socket.send(b"hello world"));
1083 let mut buf = [0; 11];
1084 t!(socket.recv(&mut buf));
1085 assert_eq!(b"hello world", &buf[..]);
1089 fn connect_send_peek_recv() {
1090 each_ip(&mut |addr, _| {
1091 let socket = t!(UdpSocket::bind(&addr));
1092 t!(socket.connect(addr));
1094 t!(socket.send(b"hello world"));
1097 let mut buf = [0; 11];
1098 let size = t!(socket.peek(&mut buf));
1099 assert_eq!(b"hello world", &buf[..]);
1100 assert_eq!(size, 11);
1103 let mut buf = [0; 11];
1104 let size = t!(socket.recv(&mut buf));
1105 assert_eq!(b"hello world", &buf[..]);
1106 assert_eq!(size, 11);
1112 each_ip(&mut |addr, _| {
1113 let socket = t!(UdpSocket::bind(&addr));
1114 t!(socket.send_to(b"hello world", &addr));
1117 let mut buf = [0; 11];
1118 let (size, _) = t!(socket.peek_from(&mut buf));
1119 assert_eq!(b"hello world", &buf[..]);
1120 assert_eq!(size, 11);
1123 let mut buf = [0; 11];
1124 let (size, _) = t!(socket.recv_from(&mut buf));
1125 assert_eq!(b"hello world", &buf[..]);
1126 assert_eq!(size, 11);
1134 let addr = next_test_ip4();
1136 let stream = t!(UdpSocket::bind(&addr));
1138 t!(stream.set_ttl(ttl));
1139 assert_eq!(ttl, t!(stream.ttl()));
1143 fn set_nonblocking() {
1144 each_ip(&mut |addr, _| {
1145 let socket = t!(UdpSocket::bind(&addr));
1147 t!(socket.set_nonblocking(true));
1148 t!(socket.set_nonblocking(false));
1150 t!(socket.connect(addr));
1152 t!(socket.set_nonblocking(false));
1153 t!(socket.set_nonblocking(true));
1156 match socket.recv(&mut buf) {
1157 Ok(_) => panic!("expected error"),
1158 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1159 Err(e) => panic!("unexpected error {}", e),