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 foo() -> 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)?;
61 /// } // 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. It is an error to pass the zero [`Duration`] to this
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 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
242 /// [`Duration`]: ../../std/time/struct.Duration.html
243 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
244 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
249 /// use std::net::UdpSocket;
251 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
252 /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
254 #[stable(feature = "socket_timeout", since = "1.4.0")]
255 pub fn set_read_timeout(&self, dur
: Option
<Duration
>) -> io
::Result
<()> {
256 self.0.set_read_timeout(dur
)
259 /// Sets the write timeout to the timeout specified.
261 /// If the value specified is [`None`], then [`write`] calls will block
262 /// indefinitely. It is an error to pass the zero [`Duration`] to this
267 /// Platforms may return a different error code whenever a write times out
268 /// as a result of setting this option. For example Unix typically returns
269 /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
271 /// [`None`]: ../../std/option/enum.Option.html#variant.None
272 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
273 /// [`Duration`]: ../../std/time/struct.Duration.html
274 /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
275 /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
280 /// use std::net::UdpSocket;
282 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
283 /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
285 #[stable(feature = "socket_timeout", since = "1.4.0")]
286 pub fn set_write_timeout(&self, dur
: Option
<Duration
>) -> io
::Result
<()> {
287 self.0.set_write_timeout(dur
)
290 /// Returns the read timeout of this socket.
292 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
294 /// [`None`]: ../../std/option/enum.Option.html#variant.None
295 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
300 /// use std::net::UdpSocket;
302 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
303 /// socket.set_read_timeout(None).expect("set_read_timeout call failed");
304 /// assert_eq!(socket.read_timeout().unwrap(), None);
306 #[stable(feature = "socket_timeout", since = "1.4.0")]
307 pub fn read_timeout(&self) -> io
::Result
<Option
<Duration
>> {
308 self.0.read_timeout()
311 /// Returns the write timeout of this socket.
313 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
315 /// [`None`]: ../../std/option/enum.Option.html#variant.None
316 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
321 /// use std::net::UdpSocket;
323 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
324 /// socket.set_write_timeout(None).expect("set_write_timeout call failed");
325 /// assert_eq!(socket.write_timeout().unwrap(), None);
327 #[stable(feature = "socket_timeout", since = "1.4.0")]
328 pub fn write_timeout(&self) -> io
::Result
<Option
<Duration
>> {
329 self.0.write_timeout()
332 /// Sets the value of the `SO_BROADCAST` option for this socket.
334 /// When enabled, this socket is allowed to send packets to a broadcast
340 /// use std::net::UdpSocket;
342 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
343 /// socket.set_broadcast(false).expect("set_broadcast call failed");
345 #[stable(feature = "net2_mutators", since = "1.9.0")]
346 pub fn set_broadcast(&self, broadcast
: bool
) -> io
::Result
<()> {
347 self.0.set_broadcast(broadcast
)
350 /// Gets the value of the `SO_BROADCAST` option for this socket.
352 /// For more information about this option, see
353 /// [`set_broadcast`][link].
355 /// [link]: #method.set_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");
364 /// assert_eq!(socket.broadcast().unwrap(), false);
366 #[stable(feature = "net2_mutators", since = "1.9.0")]
367 pub fn broadcast(&self) -> io
::Result
<bool
> {
371 /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
373 /// If enabled, multicast packets will be looped back to the local socket.
374 /// Note that this may not have any affect on IPv6 sockets.
379 /// use std::net::UdpSocket;
381 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
382 /// socket.set_multicast_loop_v4(false).expect("set_multicast_loop_v4 call failed");
384 #[stable(feature = "net2_mutators", since = "1.9.0")]
385 pub fn set_multicast_loop_v4(&self, multicast_loop_v4
: bool
) -> io
::Result
<()> {
386 self.0.set_multicast_loop_v4(multicast_loop_v4
)
389 /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
391 /// For more information about this option, see
392 /// [`set_multicast_loop_v4`][link].
394 /// [link]: #method.set_multicast_loop_v4
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");
403 /// assert_eq!(socket.multicast_loop_v4().unwrap(), false);
405 #[stable(feature = "net2_mutators", since = "1.9.0")]
406 pub fn multicast_loop_v4(&self) -> io
::Result
<bool
> {
407 self.0.multicast_loop_v4()
410 /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
412 /// Indicates the time-to-live value of outgoing multicast packets for
413 /// this socket. The default value is 1 which means that multicast packets
414 /// don't leave the local network unless explicitly requested.
416 /// Note that this may not have any affect on IPv6 sockets.
421 /// use std::net::UdpSocket;
423 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
424 /// socket.set_multicast_ttl_v4(42).expect("set_multicast_ttl_v4 call failed");
426 #[stable(feature = "net2_mutators", since = "1.9.0")]
427 pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4
: u32) -> io
::Result
<()> {
428 self.0.set_multicast_ttl_v4(multicast_ttl_v4
)
431 /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
433 /// For more information about this option, see
434 /// [`set_multicast_ttl_v4`][link].
436 /// [link]: #method.set_multicast_ttl_v4
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");
445 /// assert_eq!(socket.multicast_ttl_v4().unwrap(), 42);
447 #[stable(feature = "net2_mutators", since = "1.9.0")]
448 pub fn multicast_ttl_v4(&self) -> io
::Result
<u32> {
449 self.0.multicast_ttl_v4()
452 /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
454 /// Controls whether this socket sees the multicast packets it sends itself.
455 /// Note that this may not have any affect on IPv4 sockets.
460 /// use std::net::UdpSocket;
462 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
463 /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
465 #[stable(feature = "net2_mutators", since = "1.9.0")]
466 pub fn set_multicast_loop_v6(&self, multicast_loop_v6
: bool
) -> io
::Result
<()> {
467 self.0.set_multicast_loop_v6(multicast_loop_v6
)
470 /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
472 /// For more information about this option, see
473 /// [`set_multicast_loop_v6`][link].
475 /// [link]: #method.set_multicast_loop_v6
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");
484 /// assert_eq!(socket.multicast_loop_v6().unwrap(), false);
486 #[stable(feature = "net2_mutators", since = "1.9.0")]
487 pub fn multicast_loop_v6(&self) -> io
::Result
<bool
> {
488 self.0.multicast_loop_v6()
491 /// Sets the value for the `IP_TTL` option on this socket.
493 /// This value sets the time-to-live field that is used in every packet sent
494 /// from this socket.
499 /// use std::net::UdpSocket;
501 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
502 /// socket.set_ttl(42).expect("set_ttl call failed");
504 #[stable(feature = "net2_mutators", since = "1.9.0")]
505 pub fn set_ttl(&self, ttl
: u32) -> io
::Result
<()> {
509 /// Gets the value of the `IP_TTL` option for this socket.
511 /// For more information about this option, see [`set_ttl`][link].
513 /// [link]: #method.set_ttl
518 /// use std::net::UdpSocket;
520 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
521 /// socket.set_ttl(42).expect("set_ttl call failed");
522 /// assert_eq!(socket.ttl().unwrap(), 42);
524 #[stable(feature = "net2_mutators", since = "1.9.0")]
525 pub fn ttl(&self) -> io
::Result
<u32> {
529 /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
531 /// This function specifies a new multicast group for this socket to join.
532 /// The address must be a valid multicast address, and `interface` is the
533 /// address of the local interface with which the system should join the
534 /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
535 /// interface is chosen by the system.
536 #[stable(feature = "net2_mutators", since = "1.9.0")]
537 pub fn join_multicast_v4(&self, multiaddr
: &Ipv4Addr
, interface
: &Ipv4Addr
) -> io
::Result
<()> {
538 self.0.join_multicast_v4(multiaddr
, interface
)
541 /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
543 /// This function specifies a new multicast group for this socket to join.
544 /// The address must be a valid multicast address, and `interface` is the
545 /// index of the interface to join/leave (or 0 to indicate any interface).
546 #[stable(feature = "net2_mutators", since = "1.9.0")]
547 pub fn join_multicast_v6(&self, multiaddr
: &Ipv6Addr
, interface
: u32) -> io
::Result
<()> {
548 self.0.join_multicast_v6(multiaddr
, interface
)
551 /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
553 /// For more information about this option, see
554 /// [`join_multicast_v4`][link].
556 /// [link]: #method.join_multicast_v4
557 #[stable(feature = "net2_mutators", since = "1.9.0")]
558 pub fn leave_multicast_v4(&self, multiaddr
: &Ipv4Addr
, interface
: &Ipv4Addr
) -> io
::Result
<()> {
559 self.0.leave_multicast_v4(multiaddr
, interface
)
562 /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
564 /// For more information about this option, see
565 /// [`join_multicast_v6`][link].
567 /// [link]: #method.join_multicast_v6
568 #[stable(feature = "net2_mutators", since = "1.9.0")]
569 pub fn leave_multicast_v6(&self, multiaddr
: &Ipv6Addr
, interface
: u32) -> io
::Result
<()> {
570 self.0.leave_multicast_v6(multiaddr
, interface
)
573 /// Get the value of the `SO_ERROR` option on this socket.
575 /// This will retrieve the stored error in the underlying socket, clearing
576 /// the field in the process. This can be useful for checking errors between
582 /// use std::net::UdpSocket;
584 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
585 /// match socket.take_error() {
586 /// Ok(Some(error)) => println!("UdpSocket error: {:?}", error),
587 /// Ok(None) => println!("No error"),
588 /// Err(error) => println!("UdpSocket.take_error failed: {:?}", error),
591 #[stable(feature = "net2_mutators", since = "1.9.0")]
592 pub fn take_error(&self) -> io
::Result
<Option
<io
::Error
>> {
596 /// Connects this UDP socket to a remote address, allowing the `send` and
597 /// `recv` syscalls to be used to send data and also applies filters to only
598 /// receive data from the specified address.
600 /// If `addr` yields multiple addresses, `connect` will be attempted with
601 /// each of the addresses until the underlying OS function returns no
602 /// error. Note that usually, a successful `connect` call does not specify
603 /// that there is a remote server listening on the port, rather, such an
604 /// error would only be detected after the first send. If the OS returns an
605 /// error for each of the specified addresses, the error returned from the
606 /// last connection attempt (the last address) is returned.
610 /// Create a UDP socket bound to `127.0.0.1:3400` and connect the socket to
611 /// `127.0.0.1:8080`:
614 /// use std::net::UdpSocket;
616 /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
617 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
620 /// Unlike in the TCP case, passing an array of addresses to the `connect`
621 /// function of a UDP socket is not a useful thing to do: The OS will be
622 /// unable to determine whether something is listening on the remote
623 /// address without the application sending data.
624 #[stable(feature = "net2_mutators", since = "1.9.0")]
625 pub fn connect
<A
: ToSocketAddrs
>(&self, addr
: A
) -> io
::Result
<()> {
626 super::each_addr(addr
, |addr
| self.0.connect(addr
))
629 /// Sends data on the socket to the remote address to which it is connected.
631 /// The [`connect`] method will connect this socket to a remote address. This
632 /// method will fail if the socket is not connected.
634 /// [`connect`]: #method.connect
639 /// use std::net::UdpSocket;
641 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
642 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
643 /// socket.send(&[0, 1, 2]).expect("couldn't send message");
645 #[stable(feature = "net2_mutators", since = "1.9.0")]
646 pub fn send(&self, buf
: &[u8]) -> io
::Result
<usize> {
650 /// Receives a single datagram message on the socket from the remote address to
651 /// which it is connected. On success, returns the number of bytes read.
653 /// The function must be called with valid byte array `buf` of sufficient size to
654 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
655 /// excess bytes may be discarded.
657 /// The [`connect`] method will connect this socket to a remote address. This
658 /// method will fail if the socket is not connected.
660 /// [`connect`]: #method.connect
665 /// use std::net::UdpSocket;
667 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
668 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
669 /// let mut buf = [0; 10];
670 /// match socket.recv(&mut buf) {
671 /// Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]),
672 /// Err(e) => println!("recv function failed: {:?}", e),
675 #[stable(feature = "net2_mutators", since = "1.9.0")]
676 pub fn recv(&self, buf
: &mut [u8]) -> io
::Result
<usize> {
680 /// Receives single datagram on the socket from the remote address to which it is
681 /// connected, without removing the message from input queue. On success, returns
682 /// the number of bytes peeked.
684 /// The function must be called with valid byte array `buf` of sufficient size to
685 /// hold the message bytes. If a message is too long to fit in the supplied buffer,
686 /// excess bytes may be discarded.
688 /// Successive calls return the same data. This is accomplished by passing
689 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
691 /// Do not use this function to implement busy waiting, instead use `libc::poll` to
692 /// synchronize IO events on one or more sockets.
694 /// The [`connect`] method will connect this socket to a remote address. This
695 /// method will fail if the socket is not connected.
697 /// [`connect`]: #method.connect
701 /// This method will fail if the socket is not connected. The `connect` method
702 /// will connect this socket to a remote address.
707 /// use std::net::UdpSocket;
709 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
710 /// socket.connect("127.0.0.1:8080").expect("connect function failed");
711 /// let mut buf = [0; 10];
712 /// match socket.peek(&mut buf) {
713 /// Ok(received) => println!("received {} bytes", received),
714 /// Err(e) => println!("peek function failed: {:?}", e),
717 #[stable(feature = "peek", since = "1.18.0")]
718 pub fn peek(&self, buf
: &mut [u8]) -> io
::Result
<usize> {
722 /// Moves this UDP socket into or out of nonblocking mode.
724 /// On Unix this corresponds to calling fcntl, and on Windows this
725 /// corresponds to calling ioctlsocket.
730 /// use std::net::UdpSocket;
732 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
733 /// socket.set_nonblocking(true).expect("set_nonblocking call failed");
735 #[stable(feature = "net2_mutators", since = "1.9.0")]
736 pub fn set_nonblocking(&self, nonblocking
: bool
) -> io
::Result
<()> {
737 self.0.set_nonblocking(nonblocking
)
741 impl AsInner
<net_imp
::UdpSocket
> for UdpSocket
{
742 fn as_inner(&self) -> &net_imp
::UdpSocket { &self.0 }
745 impl FromInner
<net_imp
::UdpSocket
> for UdpSocket
{
746 fn from_inner(inner
: net_imp
::UdpSocket
) -> UdpSocket { UdpSocket(inner) }
749 impl IntoInner
<net_imp
::UdpSocket
> for UdpSocket
{
750 fn into_inner(self) -> net_imp
::UdpSocket { self.0 }
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl fmt
::Debug
for UdpSocket
{
755 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
760 #[cfg(all(test, not(target_os = "emscripten")))]
764 use net
::test
::{next_test_ip4, next_test_ip6}
;
765 use sync
::mpsc
::channel
;
766 use sys_common
::AsInner
;
767 use time
::{Instant, Duration}
;
770 fn each_ip(f
: &mut FnMut(SocketAddr
, SocketAddr
)) {
771 f(next_test_ip4(), next_test_ip4());
772 f(next_test_ip6(), next_test_ip6());
779 Err(e
) => panic
!("received error for `{}`: {}", stringify
!($e
), e
),
786 match UdpSocket
::bind("1.1.1.1:9999") {
789 assert_eq
!(e
.kind(), ErrorKind
::AddrNotAvailable
)
795 fn socket_smoke_test_ip4() {
796 each_ip(&mut |server_ip
, client_ip
| {
797 let (tx1
, rx1
) = channel();
798 let (tx2
, rx2
) = channel();
800 let _t
= thread
::spawn(move|| {
801 let client
= t
!(UdpSocket
::bind(&client_ip
));
803 t
!(client
.send_to(&[99], &server_ip
));
804 tx2
.send(()).unwrap();
807 let server
= t
!(UdpSocket
::bind(&server_ip
));
808 tx1
.send(()).unwrap();
810 let (nread
, src
) = t
!(server
.recv_from(&mut buf
));
811 assert_eq
!(nread
, 1);
812 assert_eq
!(buf
[0], 99);
813 assert_eq
!(src
, client_ip
);
819 fn socket_name_ip4() {
820 each_ip(&mut |addr
, _
| {
821 let server
= t
!(UdpSocket
::bind(&addr
));
822 assert_eq
!(addr
, t
!(server
.local_addr()));
827 fn udp_clone_smoke() {
828 each_ip(&mut |addr1
, addr2
| {
829 let sock1
= t
!(UdpSocket
::bind(&addr1
));
830 let sock2
= t
!(UdpSocket
::bind(&addr2
));
832 let _t
= thread
::spawn(move|| {
833 let mut buf
= [0, 0];
834 assert_eq
!(sock2
.recv_from(&mut buf
).unwrap(), (1, addr1
));
835 assert_eq
!(buf
[0], 1);
836 t
!(sock2
.send_to(&[2], &addr1
));
839 let sock3
= t
!(sock1
.try_clone());
841 let (tx1
, rx1
) = channel();
842 let (tx2
, rx2
) = channel();
843 let _t
= thread
::spawn(move|| {
845 t
!(sock3
.send_to(&[1], &addr2
));
846 tx2
.send(()).unwrap();
848 tx1
.send(()).unwrap();
849 let mut buf
= [0, 0];
850 assert_eq
!(sock1
.recv_from(&mut buf
).unwrap(), (1, addr2
));
856 fn udp_clone_two_read() {
857 each_ip(&mut |addr1
, addr2
| {
858 let sock1
= t
!(UdpSocket
::bind(&addr1
));
859 let sock2
= t
!(UdpSocket
::bind(&addr2
));
860 let (tx1
, rx
) = channel();
861 let tx2
= tx1
.clone();
863 let _t
= thread
::spawn(move|| {
864 t
!(sock2
.send_to(&[1], &addr1
));
866 t
!(sock2
.send_to(&[2], &addr1
));
870 let sock3
= t
!(sock1
.try_clone());
872 let (done
, rx
) = channel();
873 let _t
= thread
::spawn(move|| {
874 let mut buf
= [0, 0];
875 t
!(sock3
.recv_from(&mut buf
));
876 tx2
.send(()).unwrap();
877 done
.send(()).unwrap();
879 let mut buf
= [0, 0];
880 t
!(sock1
.recv_from(&mut buf
));
881 tx1
.send(()).unwrap();
888 fn udp_clone_two_write() {
889 each_ip(&mut |addr1
, addr2
| {
890 let sock1
= t
!(UdpSocket
::bind(&addr1
));
891 let sock2
= t
!(UdpSocket
::bind(&addr2
));
893 let (tx
, rx
) = channel();
894 let (serv_tx
, serv_rx
) = channel();
896 let _t
= thread
::spawn(move|| {
897 let mut buf
= [0, 1];
899 t
!(sock2
.recv_from(&mut buf
));
900 serv_tx
.send(()).unwrap();
903 let sock3
= t
!(sock1
.try_clone());
905 let (done
, rx
) = channel();
906 let tx2
= tx
.clone();
907 let _t
= thread
::spawn(move|| {
908 match sock3
.send_to(&[1], &addr2
) {
909 Ok(..) => { let _ = tx2.send(()); }
912 done
.send(()).unwrap();
914 match sock1
.send_to(&[2], &addr2
) {
915 Ok(..) => { let _ = tx.send(()); }
921 serv_rx
.recv().unwrap();
927 let name
= if cfg
!(windows
) {"socket"}
else {"fd"}
;
928 let socket_addr
= next_test_ip4();
930 let udpsock
= t
!(UdpSocket
::bind(&socket_addr
));
931 let udpsock_inner
= udpsock
.0.socket().as_inner();
932 let compare
= format
!("UdpSocket {{ addr: {:?}, {}: {:?} }}",
933 socket_addr
, name
, udpsock_inner
);
934 assert_eq
!(format
!("{:?}", udpsock
), compare
);
937 // FIXME: re-enabled bitrig/openbsd/netbsd tests once their socket timeout code
938 // no longer has rounding errors.
939 #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
942 let addr
= next_test_ip4();
944 let stream
= t
!(UdpSocket
::bind(&addr
));
945 let dur
= Duration
::new(15410, 0);
947 assert_eq
!(None
, t
!(stream
.read_timeout()));
949 t
!(stream
.set_read_timeout(Some(dur
)));
950 assert_eq
!(Some(dur
), t
!(stream
.read_timeout()));
952 assert_eq
!(None
, t
!(stream
.write_timeout()));
954 t
!(stream
.set_write_timeout(Some(dur
)));
955 assert_eq
!(Some(dur
), t
!(stream
.write_timeout()));
957 t
!(stream
.set_read_timeout(None
));
958 assert_eq
!(None
, t
!(stream
.read_timeout()));
960 t
!(stream
.set_write_timeout(None
));
961 assert_eq
!(None
, t
!(stream
.write_timeout()));
965 fn test_read_timeout() {
966 let addr
= next_test_ip4();
968 let stream
= t
!(UdpSocket
::bind(&addr
));
969 t
!(stream
.set_read_timeout(Some(Duration
::from_millis(1000))));
971 let mut buf
= [0; 10];
973 let start
= Instant
::now();
974 let kind
= stream
.recv_from(&mut buf
).err().expect("expected error").kind();
975 assert
!(kind
== ErrorKind
::WouldBlock
|| kind
== ErrorKind
::TimedOut
);
976 assert
!(start
.elapsed() > Duration
::from_millis(400));
980 fn test_read_with_timeout() {
981 let addr
= next_test_ip4();
983 let stream
= t
!(UdpSocket
::bind(&addr
));
984 t
!(stream
.set_read_timeout(Some(Duration
::from_millis(1000))));
986 t
!(stream
.send_to(b
"hello world", &addr
));
988 let mut buf
= [0; 11];
989 t
!(stream
.recv_from(&mut buf
));
990 assert_eq
!(b
"hello world", &buf
[..]);
992 let start
= Instant
::now();
993 let kind
= stream
.recv_from(&mut buf
).err().expect("expected error").kind();
994 assert
!(kind
== ErrorKind
::WouldBlock
|| kind
== ErrorKind
::TimedOut
);
995 assert
!(start
.elapsed() > Duration
::from_millis(400));
999 fn connect_send_recv() {
1000 let addr
= next_test_ip4();
1002 let socket
= t
!(UdpSocket
::bind(&addr
));
1003 t
!(socket
.connect(addr
));
1005 t
!(socket
.send(b
"hello world"));
1007 let mut buf
= [0; 11];
1008 t
!(socket
.recv(&mut buf
));
1009 assert_eq
!(b
"hello world", &buf
[..]);
1013 fn connect_send_peek_recv() {
1014 each_ip(&mut |addr
, _
| {
1015 let socket
= t
!(UdpSocket
::bind(&addr
));
1016 t
!(socket
.connect(addr
));
1018 t
!(socket
.send(b
"hello world"));
1021 let mut buf
= [0; 11];
1022 let size
= t
!(socket
.peek(&mut buf
));
1023 assert_eq
!(b
"hello world", &buf
[..]);
1024 assert_eq
!(size
, 11);
1027 let mut buf
= [0; 11];
1028 let size
= t
!(socket
.recv(&mut buf
));
1029 assert_eq
!(b
"hello world", &buf
[..]);
1030 assert_eq
!(size
, 11);
1036 each_ip(&mut |addr
, _
| {
1037 let socket
= t
!(UdpSocket
::bind(&addr
));
1038 t
!(socket
.send_to(b
"hello world", &addr
));
1041 let mut buf
= [0; 11];
1042 let (size
, _
) = t
!(socket
.peek_from(&mut buf
));
1043 assert_eq
!(b
"hello world", &buf
[..]);
1044 assert_eq
!(size
, 11);
1047 let mut buf
= [0; 11];
1048 let (size
, _
) = t
!(socket
.recv_from(&mut buf
));
1049 assert_eq
!(b
"hello world", &buf
[..]);
1050 assert_eq
!(size
, 11);
1058 let addr
= next_test_ip4();
1060 let stream
= t
!(UdpSocket
::bind(&addr
));
1062 t
!(stream
.set_ttl(ttl
));
1063 assert_eq
!(ttl
, t
!(stream
.ttl()));
1067 fn set_nonblocking() {
1068 each_ip(&mut |addr
, _
| {
1069 let socket
= t
!(UdpSocket
::bind(&addr
));
1071 t
!(socket
.set_nonblocking(true));
1072 t
!(socket
.set_nonblocking(false));
1074 t
!(socket
.connect(addr
));
1076 t
!(socket
.set_nonblocking(false));
1077 t
!(socket
.set_nonblocking(true));
1080 match socket
.recv(&mut buf
) {
1081 Ok(_
) => panic
!("expected error"),
1082 Err(ref e
) if e
.kind() == ErrorKind
::WouldBlock
=> {}
1083 Err(e
) => panic
!("unexpected error {}", e
),