]> git.proxmox.com Git - rustc.git/blob - src/libstd/net/udp.rs
New upstream version 1.22.1+dfsg1
[rustc.git] / src / libstd / net / udp.rs
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.
4 //
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.
10
11 use fmt;
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};
16 use time::Duration;
17
18 /// A UDP socket.
19 ///
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.
22 ///
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`].
27 ///
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
30 /// primitives.
31 ///
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
41 ///
42 /// # Examples
43 ///
44 /// ```no_run
45 /// use std::net::UdpSocket;
46 ///
47 /// # fn foo() -> std::io::Result<()> {
48 /// {
49 /// let mut socket = UdpSocket::bind("127.0.0.1:34254")?;
50 ///
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)?;
55 ///
56 /// // Redeclare `buf` as slice of the received data and send reverse data back to origin.
57 /// let buf = &mut buf[..amt];
58 /// buf.reverse();
59 /// socket.send_to(buf, &src)?;
60 /// # Ok(())
61 /// } // the socket is closed here
62 /// # }
63 /// ```
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub struct UdpSocket(net_imp::UdpSocket);
66
67 impl UdpSocket {
68 /// Creates a UDP socket from the given address.
69 ///
70 /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
71 /// its documentation for concrete examples.
72 ///
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.
77 ///
78 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
79 ///
80 /// # Examples
81 ///
82 /// Create a UDP socket bound to `127.0.0.1:3400`:
83 ///
84 /// ```no_run
85 /// use std::net::UdpSocket;
86 ///
87 /// let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
88 /// ```
89 ///
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`:
92 ///
93 /// ```no_run
94 /// use std::net::{SocketAddr, UdpSocket};
95 ///
96 /// let addrs = [
97 /// SocketAddr::from(([127, 0, 0, 1], 3400)),
98 /// SocketAddr::from(([127, 0, 0, 1], 3401)),
99 /// ];
100 /// let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address");
101 /// ```
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)
105 }
106
107 /// Receives a single datagram message on the socket. On success, returns the number
108 /// of bytes read and the origin.
109 ///
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.
113 ///
114 /// # Examples
115 ///
116 /// ```no_run
117 /// use std::net::UdpSocket;
118 ///
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];
124 /// ```
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)
128 }
129
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.
132 ///
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.
136 ///
137 /// Successive calls return the same data. This is accomplished by passing
138 /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
139 ///
140 /// Do not use this function to implement busy waiting, instead use `libc::poll` to
141 /// synchronize IO events on one or more sockets.
142 ///
143 /// # Examples
144 ///
145 /// ```no_run
146 /// use std::net::UdpSocket;
147 ///
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];
153 /// ```
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)
157 }
158
159 /// Sends data on the socket to the given address. On success, returns the
160 /// number of bytes written.
161 ///
162 /// Address type can be any implementor of [`ToSocketAddrs`] trait. See its
163 /// documentation for concrete examples.
164 ///
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`.
167 ///
168 /// This will return an error when the IP version of the local socket
169 /// does not match that returned from [`ToSocketAddrs`].
170 ///
171 /// See https://github.com/rust-lang/rust/issues/34202 for more details.
172 ///
173 /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
174 ///
175 /// # Examples
176 ///
177 /// ```no_run
178 /// use std::net::UdpSocket;
179 ///
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");
182 /// ```
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")),
190 }
191 }
192
193 /// Returns the socket address that this socket was created from.
194 ///
195 /// # Examples
196 ///
197 /// ```no_run
198 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
199 ///
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)));
203 /// ```
204 #[stable(feature = "rust1", since = "1.0.0")]
205 pub fn local_addr(&self) -> io::Result<SocketAddr> {
206 self.0.socket_addr()
207 }
208
209 /// Creates a new independently owned handle to the underlying socket.
210 ///
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.
214 ///
215 /// # Examples
216 ///
217 /// ```no_run
218 /// use std::net::UdpSocket;
219 ///
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");
222 /// ```
223 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn try_clone(&self) -> io::Result<UdpSocket> {
225 self.0.duplicate().map(UdpSocket)
226 }
227
228 /// Sets the read timeout to the timeout specified.
229 ///
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
232 /// method.
233 ///
234 /// # Note
235 ///
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`].
239 ///
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
245 ///
246 /// # Examples
247 ///
248 /// ```no_run
249 /// use std::net::UdpSocket;
250 ///
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");
253 /// ```
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)
257 }
258
259 /// Sets the write timeout to the timeout specified.
260 ///
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
263 /// method.
264 ///
265 /// # Note
266 ///
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`].
270 ///
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
276 ///
277 /// # Examples
278 ///
279 /// ```no_run
280 /// use std::net::UdpSocket;
281 ///
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");
284 /// ```
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)
288 }
289
290 /// Returns the read timeout of this socket.
291 ///
292 /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
293 ///
294 /// [`None`]: ../../std/option/enum.Option.html#variant.None
295 /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
296 ///
297 /// # Examples
298 ///
299 /// ```no_run
300 /// use std::net::UdpSocket;
301 ///
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);
305 /// ```
306 #[stable(feature = "socket_timeout", since = "1.4.0")]
307 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
308 self.0.read_timeout()
309 }
310
311 /// Returns the write timeout of this socket.
312 ///
313 /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
314 ///
315 /// [`None`]: ../../std/option/enum.Option.html#variant.None
316 /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
317 ///
318 /// # Examples
319 ///
320 /// ```no_run
321 /// use std::net::UdpSocket;
322 ///
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);
326 /// ```
327 #[stable(feature = "socket_timeout", since = "1.4.0")]
328 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
329 self.0.write_timeout()
330 }
331
332 /// Sets the value of the `SO_BROADCAST` option for this socket.
333 ///
334 /// When enabled, this socket is allowed to send packets to a broadcast
335 /// address.
336 ///
337 /// # Examples
338 ///
339 /// ```no_run
340 /// use std::net::UdpSocket;
341 ///
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");
344 /// ```
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)
348 }
349
350 /// Gets the value of the `SO_BROADCAST` option for this socket.
351 ///
352 /// For more information about this option, see
353 /// [`set_broadcast`][link].
354 ///
355 /// [link]: #method.set_broadcast
356 ///
357 /// # Examples
358 ///
359 /// ```no_run
360 /// use std::net::UdpSocket;
361 ///
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);
365 /// ```
366 #[stable(feature = "net2_mutators", since = "1.9.0")]
367 pub fn broadcast(&self) -> io::Result<bool> {
368 self.0.broadcast()
369 }
370
371 /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
372 ///
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.
375 ///
376 /// # Examples
377 ///
378 /// ```no_run
379 /// use std::net::UdpSocket;
380 ///
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");
383 /// ```
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)
387 }
388
389 /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
390 ///
391 /// For more information about this option, see
392 /// [`set_multicast_loop_v4`][link].
393 ///
394 /// [link]: #method.set_multicast_loop_v4
395 ///
396 /// # Examples
397 ///
398 /// ```no_run
399 /// use std::net::UdpSocket;
400 ///
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);
404 /// ```
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()
408 }
409
410 /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
411 ///
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.
415 ///
416 /// Note that this may not have any affect on IPv6 sockets.
417 ///
418 /// # Examples
419 ///
420 /// ```no_run
421 /// use std::net::UdpSocket;
422 ///
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");
425 /// ```
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)
429 }
430
431 /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
432 ///
433 /// For more information about this option, see
434 /// [`set_multicast_ttl_v4`][link].
435 ///
436 /// [link]: #method.set_multicast_ttl_v4
437 ///
438 /// # Examples
439 ///
440 /// ```no_run
441 /// use std::net::UdpSocket;
442 ///
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);
446 /// ```
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()
450 }
451
452 /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
453 ///
454 /// Controls whether this socket sees the multicast packets it sends itself.
455 /// Note that this may not have any affect on IPv4 sockets.
456 ///
457 /// # Examples
458 ///
459 /// ```no_run
460 /// use std::net::UdpSocket;
461 ///
462 /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
463 /// socket.set_multicast_loop_v6(false).expect("set_multicast_loop_v6 call failed");
464 /// ```
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)
468 }
469
470 /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
471 ///
472 /// For more information about this option, see
473 /// [`set_multicast_loop_v6`][link].
474 ///
475 /// [link]: #method.set_multicast_loop_v6
476 ///
477 /// # Examples
478 ///
479 /// ```no_run
480 /// use std::net::UdpSocket;
481 ///
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);
485 /// ```
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()
489 }
490
491 /// Sets the value for the `IP_TTL` option on this socket.
492 ///
493 /// This value sets the time-to-live field that is used in every packet sent
494 /// from this socket.
495 ///
496 /// # Examples
497 ///
498 /// ```no_run
499 /// use std::net::UdpSocket;
500 ///
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");
503 /// ```
504 #[stable(feature = "net2_mutators", since = "1.9.0")]
505 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
506 self.0.set_ttl(ttl)
507 }
508
509 /// Gets the value of the `IP_TTL` option for this socket.
510 ///
511 /// For more information about this option, see [`set_ttl`][link].
512 ///
513 /// [link]: #method.set_ttl
514 ///
515 /// # Examples
516 ///
517 /// ```no_run
518 /// use std::net::UdpSocket;
519 ///
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);
523 /// ```
524 #[stable(feature = "net2_mutators", since = "1.9.0")]
525 pub fn ttl(&self) -> io::Result<u32> {
526 self.0.ttl()
527 }
528
529 /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
530 ///
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)
539 }
540
541 /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
542 ///
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)
549 }
550
551 /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
552 ///
553 /// For more information about this option, see
554 /// [`join_multicast_v4`][link].
555 ///
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)
560 }
561
562 /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
563 ///
564 /// For more information about this option, see
565 /// [`join_multicast_v6`][link].
566 ///
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)
571 }
572
573 /// Get the value of the `SO_ERROR` option on this socket.
574 ///
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
577 /// calls.
578 ///
579 /// # Examples
580 ///
581 /// ```no_run
582 /// use std::net::UdpSocket;
583 ///
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),
589 /// }
590 /// ```
591 #[stable(feature = "net2_mutators", since = "1.9.0")]
592 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
593 self.0.take_error()
594 }
595
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.
599 ///
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.
607 ///
608 /// # Examples
609 ///
610 /// Create a UDP socket bound to `127.0.0.1:3400` and connect the socket to
611 /// `127.0.0.1:8080`:
612 ///
613 /// ```no_run
614 /// use std::net::UdpSocket;
615 ///
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");
618 /// ```
619 ///
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))
627 }
628
629 /// Sends data on the socket to the remote address to which it is connected.
630 ///
631 /// The [`connect`] method will connect this socket to a remote address. This
632 /// method will fail if the socket is not connected.
633 ///
634 /// [`connect`]: #method.connect
635 ///
636 /// # Examples
637 ///
638 /// ```no_run
639 /// use std::net::UdpSocket;
640 ///
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");
644 /// ```
645 #[stable(feature = "net2_mutators", since = "1.9.0")]
646 pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
647 self.0.send(buf)
648 }
649
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.
652 ///
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.
656 ///
657 /// The [`connect`] method will connect this socket to a remote address. This
658 /// method will fail if the socket is not connected.
659 ///
660 /// [`connect`]: #method.connect
661 ///
662 /// # Examples
663 ///
664 /// ```no_run
665 /// use std::net::UdpSocket;
666 ///
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),
673 /// }
674 /// ```
675 #[stable(feature = "net2_mutators", since = "1.9.0")]
676 pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
677 self.0.recv(buf)
678 }
679
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.
683 ///
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.
687 ///
688 /// Successive calls return the same data. This is accomplished by passing
689 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
690 ///
691 /// Do not use this function to implement busy waiting, instead use `libc::poll` to
692 /// synchronize IO events on one or more sockets.
693 ///
694 /// The [`connect`] method will connect this socket to a remote address. This
695 /// method will fail if the socket is not connected.
696 ///
697 /// [`connect`]: #method.connect
698 ///
699 /// # Errors
700 ///
701 /// This method will fail if the socket is not connected. The `connect` method
702 /// will connect this socket to a remote address.
703 ///
704 /// # Examples
705 ///
706 /// ```no_run
707 /// use std::net::UdpSocket;
708 ///
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),
715 /// }
716 /// ```
717 #[stable(feature = "peek", since = "1.18.0")]
718 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
719 self.0.peek(buf)
720 }
721
722 /// Moves this UDP socket into or out of nonblocking mode.
723 ///
724 /// On Unix this corresponds to calling fcntl, and on Windows this
725 /// corresponds to calling ioctlsocket.
726 ///
727 /// # Examples
728 ///
729 /// ```no_run
730 /// use std::net::UdpSocket;
731 ///
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");
734 /// ```
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)
738 }
739 }
740
741 impl AsInner<net_imp::UdpSocket> for UdpSocket {
742 fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 }
743 }
744
745 impl FromInner<net_imp::UdpSocket> for UdpSocket {
746 fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) }
747 }
748
749 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
750 fn into_inner(self) -> net_imp::UdpSocket { self.0 }
751 }
752
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl fmt::Debug for UdpSocket {
755 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
756 self.0.fmt(f)
757 }
758 }
759
760 #[cfg(all(test, not(target_os = "emscripten")))]
761 mod tests {
762 use io::ErrorKind;
763 use net::*;
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};
768 use thread;
769
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());
773 }
774
775 macro_rules! t {
776 ($e:expr) => {
777 match $e {
778 Ok(t) => t,
779 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
780 }
781 }
782 }
783
784 #[test]
785 fn bind_error() {
786 match UdpSocket::bind("1.1.1.1:9999") {
787 Ok(..) => panic!(),
788 Err(e) => {
789 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable)
790 }
791 }
792 }
793
794 #[test]
795 fn socket_smoke_test_ip4() {
796 each_ip(&mut |server_ip, client_ip| {
797 let (tx1, rx1) = channel();
798 let (tx2, rx2) = channel();
799
800 let _t = thread::spawn(move|| {
801 let client = t!(UdpSocket::bind(&client_ip));
802 rx1.recv().unwrap();
803 t!(client.send_to(&[99], &server_ip));
804 tx2.send(()).unwrap();
805 });
806
807 let server = t!(UdpSocket::bind(&server_ip));
808 tx1.send(()).unwrap();
809 let mut buf = [0];
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);
814 rx2.recv().unwrap();
815 })
816 }
817
818 #[test]
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()));
823 })
824 }
825
826 #[test]
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));
831
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));
837 });
838
839 let sock3 = t!(sock1.try_clone());
840
841 let (tx1, rx1) = channel();
842 let (tx2, rx2) = channel();
843 let _t = thread::spawn(move|| {
844 rx1.recv().unwrap();
845 t!(sock3.send_to(&[1], &addr2));
846 tx2.send(()).unwrap();
847 });
848 tx1.send(()).unwrap();
849 let mut buf = [0, 0];
850 assert_eq!(sock1.recv_from(&mut buf).unwrap(), (1, addr2));
851 rx2.recv().unwrap();
852 })
853 }
854
855 #[test]
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();
862
863 let _t = thread::spawn(move|| {
864 t!(sock2.send_to(&[1], &addr1));
865 rx.recv().unwrap();
866 t!(sock2.send_to(&[2], &addr1));
867 rx.recv().unwrap();
868 });
869
870 let sock3 = t!(sock1.try_clone());
871
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();
878 });
879 let mut buf = [0, 0];
880 t!(sock1.recv_from(&mut buf));
881 tx1.send(()).unwrap();
882
883 rx.recv().unwrap();
884 })
885 }
886
887 #[test]
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));
892
893 let (tx, rx) = channel();
894 let (serv_tx, serv_rx) = channel();
895
896 let _t = thread::spawn(move|| {
897 let mut buf = [0, 1];
898 rx.recv().unwrap();
899 t!(sock2.recv_from(&mut buf));
900 serv_tx.send(()).unwrap();
901 });
902
903 let sock3 = t!(sock1.try_clone());
904
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(()); }
910 Err(..) => {}
911 }
912 done.send(()).unwrap();
913 });
914 match sock1.send_to(&[2], &addr2) {
915 Ok(..) => { let _ = tx.send(()); }
916 Err(..) => {}
917 }
918 drop(tx);
919
920 rx.recv().unwrap();
921 serv_rx.recv().unwrap();
922 })
923 }
924
925 #[test]
926 fn debug() {
927 let name = if cfg!(windows) {"socket"} else {"fd"};
928 let socket_addr = next_test_ip4();
929
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);
935 }
936
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)]
940 #[test]
941 fn timeouts() {
942 let addr = next_test_ip4();
943
944 let stream = t!(UdpSocket::bind(&addr));
945 let dur = Duration::new(15410, 0);
946
947 assert_eq!(None, t!(stream.read_timeout()));
948
949 t!(stream.set_read_timeout(Some(dur)));
950 assert_eq!(Some(dur), t!(stream.read_timeout()));
951
952 assert_eq!(None, t!(stream.write_timeout()));
953
954 t!(stream.set_write_timeout(Some(dur)));
955 assert_eq!(Some(dur), t!(stream.write_timeout()));
956
957 t!(stream.set_read_timeout(None));
958 assert_eq!(None, t!(stream.read_timeout()));
959
960 t!(stream.set_write_timeout(None));
961 assert_eq!(None, t!(stream.write_timeout()));
962 }
963
964 #[test]
965 fn test_read_timeout() {
966 let addr = next_test_ip4();
967
968 let stream = t!(UdpSocket::bind(&addr));
969 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
970
971 let mut buf = [0; 10];
972
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));
977 }
978
979 #[test]
980 fn test_read_with_timeout() {
981 let addr = next_test_ip4();
982
983 let stream = t!(UdpSocket::bind(&addr));
984 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
985
986 t!(stream.send_to(b"hello world", &addr));
987
988 let mut buf = [0; 11];
989 t!(stream.recv_from(&mut buf));
990 assert_eq!(b"hello world", &buf[..]);
991
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));
996 }
997
998 #[test]
999 fn connect_send_recv() {
1000 let addr = next_test_ip4();
1001
1002 let socket = t!(UdpSocket::bind(&addr));
1003 t!(socket.connect(addr));
1004
1005 t!(socket.send(b"hello world"));
1006
1007 let mut buf = [0; 11];
1008 t!(socket.recv(&mut buf));
1009 assert_eq!(b"hello world", &buf[..]);
1010 }
1011
1012 #[test]
1013 fn connect_send_peek_recv() {
1014 each_ip(&mut |addr, _| {
1015 let socket = t!(UdpSocket::bind(&addr));
1016 t!(socket.connect(addr));
1017
1018 t!(socket.send(b"hello world"));
1019
1020 for _ in 1..3 {
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);
1025 }
1026
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);
1031 })
1032 }
1033
1034 #[test]
1035 fn peek_from() {
1036 each_ip(&mut |addr, _| {
1037 let socket = t!(UdpSocket::bind(&addr));
1038 t!(socket.send_to(b"hello world", &addr));
1039
1040 for _ in 1..3 {
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);
1045 }
1046
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);
1051 })
1052 }
1053
1054 #[test]
1055 fn ttl() {
1056 let ttl = 100;
1057
1058 let addr = next_test_ip4();
1059
1060 let stream = t!(UdpSocket::bind(&addr));
1061
1062 t!(stream.set_ttl(ttl));
1063 assert_eq!(ttl, t!(stream.ttl()));
1064 }
1065
1066 #[test]
1067 fn set_nonblocking() {
1068 each_ip(&mut |addr, _| {
1069 let socket = t!(UdpSocket::bind(&addr));
1070
1071 t!(socket.set_nonblocking(true));
1072 t!(socket.set_nonblocking(false));
1073
1074 t!(socket.connect(addr));
1075
1076 t!(socket.set_nonblocking(false));
1077 t!(socket.set_nonblocking(true));
1078
1079 let mut buf = [0];
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),
1084 }
1085 })
1086 }
1087 }