]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/udp.rs
Auto merge of #32239 - alexcrichton:fix-cross-to-freebsd, r=brson
[rust.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 User Datagram Protocol socket.
19 ///
20 /// This is an implementation of a bound UDP socket. This supports both IPv4 and
21 /// IPv6 addresses, and there is no corresponding notion of a server because UDP
22 /// is a datagram protocol.
23 ///
24 /// # Examples
25 ///
26 /// ```no_run
27 /// use std::net::UdpSocket;
28 ///
29 /// # fn foo() -> std::io::Result<()> {
30 /// {
31 ///     let mut socket = try!(UdpSocket::bind("127.0.0.1:34254"));
32 ///
33 ///     // read from the socket
34 ///     let mut buf = [0; 10];
35 ///     let (amt, src) = try!(socket.recv_from(&mut buf));
36 ///
37 ///     // send a reply to the socket we received data from
38 ///     let buf = &mut buf[..amt];
39 ///     buf.reverse();
40 ///     try!(socket.send_to(buf, &src));
41 ///     # Ok(())
42 /// } // the socket is closed here
43 /// # }
44 /// ```
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct UdpSocket(net_imp::UdpSocket);
47
48 impl UdpSocket {
49     /// Creates a UDP socket from the given address.
50     ///
51     /// The address type can be any implementor of `ToSocketAddr` trait. See
52     /// its documentation for concrete examples.
53     #[stable(feature = "rust1", since = "1.0.0")]
54     pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
55         super::each_addr(addr, net_imp::UdpSocket::bind).map(UdpSocket)
56     }
57
58     /// Receives data from the socket. On success, returns the number of bytes
59     /// read and the address from whence the data came.
60     #[stable(feature = "rust1", since = "1.0.0")]
61     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
62         self.0.recv_from(buf)
63     }
64
65     /// Sends data on the socket to the given address. On success, returns the
66     /// number of bytes written.
67     ///
68     /// Address type can be any implementor of `ToSocketAddrs` trait. See its
69     /// documentation for concrete examples.
70     #[stable(feature = "rust1", since = "1.0.0")]
71     pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A)
72                                      -> io::Result<usize> {
73         match try!(addr.to_socket_addrs()).next() {
74             Some(addr) => self.0.send_to(buf, &addr),
75             None => Err(Error::new(ErrorKind::InvalidInput,
76                                    "no addresses to send data to")),
77         }
78     }
79
80     /// Returns the socket address that this socket was created from.
81     #[stable(feature = "rust1", since = "1.0.0")]
82     pub fn local_addr(&self) -> io::Result<SocketAddr> {
83         self.0.socket_addr()
84     }
85
86     /// Creates a new independently owned handle to the underlying socket.
87     ///
88     /// The returned `UdpSocket` is a reference to the same socket that this
89     /// object references. Both handles will read and write the same port, and
90     /// options set on one socket will be propagated to the other.
91     #[stable(feature = "rust1", since = "1.0.0")]
92     pub fn try_clone(&self) -> io::Result<UdpSocket> {
93         self.0.duplicate().map(UdpSocket)
94     }
95
96     /// Sets the read timeout to the timeout specified.
97     ///
98     /// If the value specified is `None`, then `read` calls will block
99     /// indefinitely. It is an error to pass the zero `Duration` to this
100     /// method.
101     ///
102     /// # Note
103     ///
104     /// Platforms may return a different error code whenever a read times out as
105     /// a result of setting this option. For example Unix typically returns an
106     /// error of the kind `WouldBlock`, but Windows may return `TimedOut`.
107     #[stable(feature = "socket_timeout", since = "1.4.0")]
108     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
109         self.0.set_read_timeout(dur)
110     }
111
112     /// Sets the write timeout to the timeout specified.
113     ///
114     /// If the value specified is `None`, then `write` calls will block
115     /// indefinitely. It is an error to pass the zero `Duration` to this
116     /// method.
117     ///
118     /// # Note
119     ///
120     /// Platforms may return a different error code whenever a write times out
121     /// as a result of setting this option. For example Unix typically returns
122     /// an error of the kind `WouldBlock`, but Windows may return `TimedOut`.
123     #[stable(feature = "socket_timeout", since = "1.4.0")]
124     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
125         self.0.set_write_timeout(dur)
126     }
127
128     /// Returns the read timeout of this socket.
129     ///
130     /// If the timeout is `None`, then `read` calls will block indefinitely.
131     #[stable(feature = "socket_timeout", since = "1.4.0")]
132     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
133         self.0.read_timeout()
134     }
135
136     /// Returns the write timeout of this socket.
137     ///
138     /// If the timeout is `None`, then `write` calls will block indefinitely.
139     #[stable(feature = "socket_timeout", since = "1.4.0")]
140     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
141         self.0.write_timeout()
142     }
143
144     /// Sets the value of the `SO_BROADCAST` option for this socket.
145     ///
146     /// When enabled, this socket is allowed to send packets to a broadcast
147     /// address.
148     #[stable(feature = "net2_mutators", since = "1.9.0")]
149     pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
150         self.0.set_broadcast(broadcast)
151     }
152
153     /// Gets the value of the `SO_BROADCAST` option for this socket.
154     ///
155     /// For more information about this option, see
156     /// [`set_broadcast`][link].
157     ///
158     /// [link]: #tymethod.set_broadcast
159     #[stable(feature = "net2_mutators", since = "1.9.0")]
160     pub fn broadcast(&self) -> io::Result<bool> {
161         self.0.broadcast()
162     }
163
164     /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
165     ///
166     /// If enabled, multicast packets will be looped back to the local socket.
167     /// Note that this may not have any affect on IPv6 sockets.
168     #[stable(feature = "net2_mutators", since = "1.9.0")]
169     pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
170         self.0.set_multicast_loop_v4(multicast_loop_v4)
171     }
172
173     /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
174     ///
175     /// For more information about this option, see
176     /// [`set_multicast_loop_v4`][link].
177     ///
178     /// [link]: #tymethod.set_multicast_loop_v4
179     #[stable(feature = "net2_mutators", since = "1.9.0")]
180     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
181         self.0.multicast_loop_v4()
182     }
183
184     /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
185     ///
186     /// Indicates the time-to-live value of outgoing multicast packets for
187     /// this socket. The default value is 1 which means that multicast packets
188     /// don't leave the local network unless explicitly requested.
189     ///
190     /// Note that this may not have any affect on IPv6 sockets.
191     #[stable(feature = "net2_mutators", since = "1.9.0")]
192     pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
193         self.0.set_multicast_ttl_v4(multicast_ttl_v4)
194     }
195
196     /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
197     ///
198     /// For more information about this option, see
199     /// [`set_multicast_ttl_v4`][link].
200     ///
201     /// [link]: #tymethod.set_multicast_ttl_v4
202     #[stable(feature = "net2_mutators", since = "1.9.0")]
203     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
204         self.0.multicast_ttl_v4()
205     }
206
207     /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
208     ///
209     /// Controls whether this socket sees the multicast packets it sends itself.
210     /// Note that this may not have any affect on IPv4 sockets.
211     #[stable(feature = "net2_mutators", since = "1.9.0")]
212     pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
213         self.0.set_multicast_loop_v6(multicast_loop_v6)
214     }
215
216     /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
217     ///
218     /// For more information about this option, see
219     /// [`set_multicast_loop_v6`][link].
220     ///
221     /// [link]: #tymethod.set_multicast_loop_v6
222     #[stable(feature = "net2_mutators", since = "1.9.0")]
223     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
224         self.0.multicast_loop_v6()
225     }
226
227     /// Sets the value for the `IP_TTL` option on this socket.
228     ///
229     /// This value sets the time-to-live field that is used in every packet sent
230     /// from this socket.
231     #[stable(feature = "net2_mutators", since = "1.9.0")]
232     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
233         self.0.set_ttl(ttl)
234     }
235
236     /// Gets the value of the `IP_TTL` option for this socket.
237     ///
238     /// For more information about this option, see [`set_ttl`][link].
239     ///
240     /// [link]: #tymethod.set_ttl
241     #[stable(feature = "net2_mutators", since = "1.9.0")]
242     pub fn ttl(&self) -> io::Result<u32> {
243         self.0.ttl()
244     }
245
246     /// Sets the value for the `IPV6_V6ONLY` option on this socket.
247     ///
248     /// If this is set to `true` then the socket is restricted to sending and
249     /// receiving IPv6 packets only. If this is the case, an IPv4 and an IPv6
250     /// application can each bind the same port at the same time.
251     ///
252     /// If this is set to `false` then the socket can be used to send and
253     /// receive packets from an IPv4-mapped IPv6 address.
254     #[stable(feature = "net2_mutators", since = "1.9.0")]
255     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
256         self.0.set_only_v6(only_v6)
257     }
258
259     /// Gets the value of the `IPV6_V6ONLY` option for this socket.
260     ///
261     /// For more information about this option, see [`set_only_v6`][link].
262     ///
263     /// [link]: #tymethod.set_only_v6
264     #[stable(feature = "net2_mutators", since = "1.9.0")]
265     pub fn only_v6(&self) -> io::Result<bool> {
266         self.0.only_v6()
267     }
268
269     /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
270     ///
271     /// This function specifies a new multicast group for this socket to join.
272     /// The address must be a valid multicast address, and `interface` is the
273     /// address of the local interface with which the system should join the
274     /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
275     /// interface is chosen by the system.
276     #[stable(feature = "net2_mutators", since = "1.9.0")]
277     pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
278         self.0.join_multicast_v4(multiaddr, interface)
279     }
280
281     /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
282     ///
283     /// This function specifies a new multicast group for this socket to join.
284     /// The address must be a valid multicast address, and `interface` is the
285     /// index of the interface to join/leave (or 0 to indicate any interface).
286     #[stable(feature = "net2_mutators", since = "1.9.0")]
287     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
288         self.0.join_multicast_v6(multiaddr, interface)
289     }
290
291     /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
292     ///
293     /// For more information about this option, see
294     /// [`join_multicast_v4`][link].
295     ///
296     /// [link]: #tymethod.join_multicast_v4
297     #[stable(feature = "net2_mutators", since = "1.9.0")]
298     pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
299         self.0.leave_multicast_v4(multiaddr, interface)
300     }
301
302     /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
303     ///
304     /// For more information about this option, see
305     /// [`join_multicast_v6`][link].
306     ///
307     /// [link]: #tymethod.join_multicast_v6
308     #[stable(feature = "net2_mutators", since = "1.9.0")]
309     pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
310         self.0.leave_multicast_v6(multiaddr, interface)
311     }
312
313     /// Get the value of the `SO_ERROR` option on this socket.
314     ///
315     /// This will retrieve the stored error in the underlying socket, clearing
316     /// the field in the process. This can be useful for checking errors between
317     /// calls.
318     #[stable(feature = "net2_mutators", since = "1.9.0")]
319     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
320         self.0.take_error()
321     }
322
323     /// Connects this UDP socket to a remote address, allowing the `send` and
324     /// `recv` syscalls to be used to send data and also applies filters to only
325     /// receive data from the specified address.
326     #[stable(feature = "net2_mutators", since = "1.9.0")]
327     pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
328         super::each_addr(addr, |addr| self.0.connect(addr))
329     }
330
331     /// Sends data on the socket to the remote address to which it is connected.
332     ///
333     /// The `connect` method will connect this socket to a remote address. This
334     /// method will fail if the socket is not connected.
335     #[stable(feature = "net2_mutators", since = "1.9.0")]
336     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
337         self.0.send(buf)
338     }
339
340     /// Receives data on the socket from the remote address to which it is
341     /// connected.
342     ///
343     /// The `connect` method will connect this socket to a remote address. This
344     /// method will fail if the socket is not connected.
345     #[stable(feature = "net2_mutators", since = "1.9.0")]
346     pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
347         self.0.recv(buf)
348     }
349
350     /// Moves this TCP stream into or out of nonblocking mode.
351     ///
352     /// On Unix this corresponds to calling fcntl, and on Windows this
353     /// corresponds to calling ioctlsocket.
354     #[stable(feature = "net2_mutators", since = "1.9.0")]
355     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
356         self.0.set_nonblocking(nonblocking)
357     }
358 }
359
360 impl AsInner<net_imp::UdpSocket> for UdpSocket {
361     fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 }
362 }
363
364 impl FromInner<net_imp::UdpSocket> for UdpSocket {
365     fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) }
366 }
367
368 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
369     fn into_inner(self) -> net_imp::UdpSocket { self.0 }
370 }
371
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl fmt::Debug for UdpSocket {
374     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
375         self.0.fmt(f)
376     }
377 }
378
379 #[cfg(test)]
380 mod tests {
381     use prelude::v1::*;
382
383     use io::ErrorKind;
384     use net::*;
385     use net::test::{next_test_ip4, next_test_ip6};
386     use sync::mpsc::channel;
387     use sys_common::AsInner;
388     use time::{Instant, Duration};
389     use thread;
390
391     fn each_ip(f: &mut FnMut(SocketAddr, SocketAddr)) {
392         f(next_test_ip4(), next_test_ip4());
393         f(next_test_ip6(), next_test_ip6());
394     }
395
396     macro_rules! t {
397         ($e:expr) => {
398             match $e {
399                 Ok(t) => t,
400                 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
401             }
402         }
403     }
404
405     #[test]
406     fn bind_error() {
407         match UdpSocket::bind("1.1.1.1:9999") {
408             Ok(..) => panic!(),
409             Err(e) => {
410                 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable)
411             }
412         }
413     }
414
415     #[test]
416     fn socket_smoke_test_ip4() {
417         each_ip(&mut |server_ip, client_ip| {
418             let (tx1, rx1) = channel();
419             let (tx2, rx2) = channel();
420
421             let _t = thread::spawn(move|| {
422                 let client = t!(UdpSocket::bind(&client_ip));
423                 rx1.recv().unwrap();
424                 t!(client.send_to(&[99], &server_ip));
425                 tx2.send(()).unwrap();
426             });
427
428             let server = t!(UdpSocket::bind(&server_ip));
429             tx1.send(()).unwrap();
430             let mut buf = [0];
431             let (nread, src) = t!(server.recv_from(&mut buf));
432             assert_eq!(nread, 1);
433             assert_eq!(buf[0], 99);
434             assert_eq!(src, client_ip);
435             rx2.recv().unwrap();
436         })
437     }
438
439     #[test]
440     fn socket_name_ip4() {
441         each_ip(&mut |addr, _| {
442             let server = t!(UdpSocket::bind(&addr));
443             assert_eq!(addr, t!(server.local_addr()));
444         })
445     }
446
447     #[test]
448     fn udp_clone_smoke() {
449         each_ip(&mut |addr1, addr2| {
450             let sock1 = t!(UdpSocket::bind(&addr1));
451             let sock2 = t!(UdpSocket::bind(&addr2));
452
453             let _t = thread::spawn(move|| {
454                 let mut buf = [0, 0];
455                 assert_eq!(sock2.recv_from(&mut buf).unwrap(), (1, addr1));
456                 assert_eq!(buf[0], 1);
457                 t!(sock2.send_to(&[2], &addr1));
458             });
459
460             let sock3 = t!(sock1.try_clone());
461
462             let (tx1, rx1) = channel();
463             let (tx2, rx2) = channel();
464             let _t = thread::spawn(move|| {
465                 rx1.recv().unwrap();
466                 t!(sock3.send_to(&[1], &addr2));
467                 tx2.send(()).unwrap();
468             });
469             tx1.send(()).unwrap();
470             let mut buf = [0, 0];
471             assert_eq!(sock1.recv_from(&mut buf).unwrap(), (1, addr2));
472             rx2.recv().unwrap();
473         })
474     }
475
476     #[test]
477     fn udp_clone_two_read() {
478         each_ip(&mut |addr1, addr2| {
479             let sock1 = t!(UdpSocket::bind(&addr1));
480             let sock2 = t!(UdpSocket::bind(&addr2));
481             let (tx1, rx) = channel();
482             let tx2 = tx1.clone();
483
484             let _t = thread::spawn(move|| {
485                 t!(sock2.send_to(&[1], &addr1));
486                 rx.recv().unwrap();
487                 t!(sock2.send_to(&[2], &addr1));
488                 rx.recv().unwrap();
489             });
490
491             let sock3 = t!(sock1.try_clone());
492
493             let (done, rx) = channel();
494             let _t = thread::spawn(move|| {
495                 let mut buf = [0, 0];
496                 t!(sock3.recv_from(&mut buf));
497                 tx2.send(()).unwrap();
498                 done.send(()).unwrap();
499             });
500             let mut buf = [0, 0];
501             t!(sock1.recv_from(&mut buf));
502             tx1.send(()).unwrap();
503
504             rx.recv().unwrap();
505         })
506     }
507
508     #[test]
509     fn udp_clone_two_write() {
510         each_ip(&mut |addr1, addr2| {
511             let sock1 = t!(UdpSocket::bind(&addr1));
512             let sock2 = t!(UdpSocket::bind(&addr2));
513
514             let (tx, rx) = channel();
515             let (serv_tx, serv_rx) = channel();
516
517             let _t = thread::spawn(move|| {
518                 let mut buf = [0, 1];
519                 rx.recv().unwrap();
520                 t!(sock2.recv_from(&mut buf));
521                 serv_tx.send(()).unwrap();
522             });
523
524             let sock3 = t!(sock1.try_clone());
525
526             let (done, rx) = channel();
527             let tx2 = tx.clone();
528             let _t = thread::spawn(move|| {
529                 match sock3.send_to(&[1], &addr2) {
530                     Ok(..) => { let _ = tx2.send(()); }
531                     Err(..) => {}
532                 }
533                 done.send(()).unwrap();
534             });
535             match sock1.send_to(&[2], &addr2) {
536                 Ok(..) => { let _ = tx.send(()); }
537                 Err(..) => {}
538             }
539             drop(tx);
540
541             rx.recv().unwrap();
542             serv_rx.recv().unwrap();
543         })
544     }
545
546     #[test]
547     fn debug() {
548         let name = if cfg!(windows) {"socket"} else {"fd"};
549         let socket_addr = next_test_ip4();
550
551         let udpsock = t!(UdpSocket::bind(&socket_addr));
552         let udpsock_inner = udpsock.0.socket().as_inner();
553         let compare = format!("UdpSocket {{ addr: {:?}, {}: {:?} }}",
554                               socket_addr, name, udpsock_inner);
555         assert_eq!(format!("{:?}", udpsock), compare);
556     }
557
558     // FIXME: re-enabled bitrig/openbsd/netbsd tests once their socket timeout code
559     //        no longer has rounding errors.
560     #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
561     #[test]
562     fn timeouts() {
563         let addr = next_test_ip4();
564
565         let stream = t!(UdpSocket::bind(&addr));
566         let dur = Duration::new(15410, 0);
567
568         assert_eq!(None, t!(stream.read_timeout()));
569
570         t!(stream.set_read_timeout(Some(dur)));
571         assert_eq!(Some(dur), t!(stream.read_timeout()));
572
573         assert_eq!(None, t!(stream.write_timeout()));
574
575         t!(stream.set_write_timeout(Some(dur)));
576         assert_eq!(Some(dur), t!(stream.write_timeout()));
577
578         t!(stream.set_read_timeout(None));
579         assert_eq!(None, t!(stream.read_timeout()));
580
581         t!(stream.set_write_timeout(None));
582         assert_eq!(None, t!(stream.write_timeout()));
583     }
584
585     #[test]
586     fn test_read_timeout() {
587         let addr = next_test_ip4();
588
589         let stream = t!(UdpSocket::bind(&addr));
590         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
591
592         let mut buf = [0; 10];
593
594         let start = Instant::now();
595         let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
596         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
597         assert!(start.elapsed() > Duration::from_millis(400));
598     }
599
600     #[test]
601     fn test_read_with_timeout() {
602         let addr = next_test_ip4();
603
604         let stream = t!(UdpSocket::bind(&addr));
605         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
606
607         t!(stream.send_to(b"hello world", &addr));
608
609         let mut buf = [0; 11];
610         t!(stream.recv_from(&mut buf));
611         assert_eq!(b"hello world", &buf[..]);
612
613         let start = Instant::now();
614         let kind = stream.recv_from(&mut buf).err().expect("expected error").kind();
615         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
616         assert!(start.elapsed() > Duration::from_millis(400));
617     }
618
619     #[test]
620     fn connect_send_recv() {
621         let addr = next_test_ip4();
622
623         let socket = t!(UdpSocket::bind(&addr));
624         t!(socket.connect(addr));
625
626         t!(socket.send(b"hello world"));
627
628         let mut buf = [0; 11];
629         t!(socket.recv(&mut buf));
630         assert_eq!(b"hello world", &buf[..]);
631     }
632
633     #[test]
634     fn ttl() {
635         let ttl = 100;
636
637         let addr = next_test_ip4();
638
639         let stream = t!(UdpSocket::bind(&addr));
640
641         t!(stream.set_ttl(ttl));
642         assert_eq!(ttl, t!(stream.ttl()));
643     }
644
645     #[test]
646     fn set_nonblocking() {
647         let addr = next_test_ip4();
648
649         let stream = t!(UdpSocket::bind(&addr));
650
651         t!(stream.set_nonblocking(true));
652         t!(stream.set_nonblocking(false));
653     }
654 }