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};
18 /// A User Datagram Protocol socket.
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.
27 /// use std::net::UdpSocket;
29 /// # fn foo() -> std::io::Result<()> {
31 /// let mut socket = try!(UdpSocket::bind("127.0.0.1:34254"));
33 /// // read from the socket
34 /// let mut buf = [0; 10];
35 /// let (amt, src) = try!(socket.recv_from(&mut buf));
37 /// // send a reply to the socket we received data from
38 /// let buf = &mut buf[..amt];
40 /// try!(socket.send_to(buf, &src));
42 /// } // the socket is closed here
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct UdpSocket(net_imp::UdpSocket);
49 /// Creates a UDP socket from the given address.
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)
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)> {
65 /// Sends data on the socket to the given address. On success, returns the
66 /// number of bytes written.
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")),
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> {
86 /// Creates a new independently owned handle to the underlying socket.
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)
96 /// Sets the read timeout to the timeout specified.
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
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)
112 /// Sets the write timeout to the timeout specified.
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
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)
128 /// Returns the read timeout of this socket.
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()
136 /// Returns the write timeout of this socket.
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()
144 /// Sets the value of the `SO_BROADCAST` option for this socket.
146 /// When enabled, this socket is allowed to send packets to a broadcast
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)
153 /// Gets the value of the `SO_BROADCAST` option for this socket.
155 /// For more information about this option, see
156 /// [`set_broadcast`][link].
158 /// [link]: #tymethod.set_broadcast
159 #[stable(feature = "net2_mutators", since = "1.9.0")]
160 pub fn broadcast(&self) -> io::Result<bool> {
164 /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
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)
173 /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
175 /// For more information about this option, see
176 /// [`set_multicast_loop_v4`][link].
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()
184 /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
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.
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)
196 /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
198 /// For more information about this option, see
199 /// [`set_multicast_ttl_v4`][link].
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()
207 /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
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)
216 /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
218 /// For more information about this option, see
219 /// [`set_multicast_loop_v6`][link].
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()
227 /// Sets the value for the `IP_TTL` option on this socket.
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<()> {
236 /// Gets the value of the `IP_TTL` option for this socket.
238 /// For more information about this option, see [`set_ttl`][link].
240 /// [link]: #tymethod.set_ttl
241 #[stable(feature = "net2_mutators", since = "1.9.0")]
242 pub fn ttl(&self) -> io::Result<u32> {
246 /// Sets the value for the `IPV6_V6ONLY` option on this socket.
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.
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)
259 /// Gets the value of the `IPV6_V6ONLY` option for this socket.
261 /// For more information about this option, see [`set_only_v6`][link].
263 /// [link]: #tymethod.set_only_v6
264 #[stable(feature = "net2_mutators", since = "1.9.0")]
265 pub fn only_v6(&self) -> io::Result<bool> {
269 /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
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)
281 /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
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)
291 /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
293 /// For more information about this option, see
294 /// [`join_multicast_v4`][link].
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)
302 /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
304 /// For more information about this option, see
305 /// [`join_multicast_v6`][link].
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)
313 /// Get the value of the `SO_ERROR` option on this socket.
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
318 #[stable(feature = "net2_mutators", since = "1.9.0")]
319 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
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))
331 /// Sends data on the socket to the remote address to which it is connected.
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> {
340 /// Receives data on the socket from the remote address to which it is
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> {
350 /// Moves this TCP stream into or out of nonblocking mode.
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)
360 impl AsInner<net_imp::UdpSocket> for UdpSocket {
361 fn as_inner(&self) -> &net_imp::UdpSocket { &self.0 }
364 impl FromInner<net_imp::UdpSocket> for UdpSocket {
365 fn from_inner(inner: net_imp::UdpSocket) -> UdpSocket { UdpSocket(inner) }
368 impl IntoInner<net_imp::UdpSocket> for UdpSocket {
369 fn into_inner(self) -> net_imp::UdpSocket { self.0 }
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl fmt::Debug for UdpSocket {
374 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
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};
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());
400 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
407 match UdpSocket::bind("1.1.1.1:9999") {
410 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable)
416 fn socket_smoke_test_ip4() {
417 each_ip(&mut |server_ip, client_ip| {
418 let (tx1, rx1) = channel();
419 let (tx2, rx2) = channel();
421 let _t = thread::spawn(move|| {
422 let client = t!(UdpSocket::bind(&client_ip));
424 t!(client.send_to(&[99], &server_ip));
425 tx2.send(()).unwrap();
428 let server = t!(UdpSocket::bind(&server_ip));
429 tx1.send(()).unwrap();
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);
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()));
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));
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));
460 let sock3 = t!(sock1.try_clone());
462 let (tx1, rx1) = channel();
463 let (tx2, rx2) = channel();
464 let _t = thread::spawn(move|| {
466 t!(sock3.send_to(&[1], &addr2));
467 tx2.send(()).unwrap();
469 tx1.send(()).unwrap();
470 let mut buf = [0, 0];
471 assert_eq!(sock1.recv_from(&mut buf).unwrap(), (1, addr2));
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();
484 let _t = thread::spawn(move|| {
485 t!(sock2.send_to(&[1], &addr1));
487 t!(sock2.send_to(&[2], &addr1));
491 let sock3 = t!(sock1.try_clone());
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();
500 let mut buf = [0, 0];
501 t!(sock1.recv_from(&mut buf));
502 tx1.send(()).unwrap();
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));
514 let (tx, rx) = channel();
515 let (serv_tx, serv_rx) = channel();
517 let _t = thread::spawn(move|| {
518 let mut buf = [0, 1];
520 t!(sock2.recv_from(&mut buf));
521 serv_tx.send(()).unwrap();
524 let sock3 = t!(sock1.try_clone());
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(()); }
533 done.send(()).unwrap();
535 match sock1.send_to(&[2], &addr2) {
536 Ok(..) => { let _ = tx.send(()); }
542 serv_rx.recv().unwrap();
548 let name = if cfg!(windows) {"socket"} else {"fd"};
549 let socket_addr = next_test_ip4();
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);
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)]
563 let addr = next_test_ip4();
565 let stream = t!(UdpSocket::bind(&addr));
566 let dur = Duration::new(15410, 0);
568 assert_eq!(None, t!(stream.read_timeout()));
570 t!(stream.set_read_timeout(Some(dur)));
571 assert_eq!(Some(dur), t!(stream.read_timeout()));
573 assert_eq!(None, t!(stream.write_timeout()));
575 t!(stream.set_write_timeout(Some(dur)));
576 assert_eq!(Some(dur), t!(stream.write_timeout()));
578 t!(stream.set_read_timeout(None));
579 assert_eq!(None, t!(stream.read_timeout()));
581 t!(stream.set_write_timeout(None));
582 assert_eq!(None, t!(stream.write_timeout()));
586 fn test_read_timeout() {
587 let addr = next_test_ip4();
589 let stream = t!(UdpSocket::bind(&addr));
590 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
592 let mut buf = [0; 10];
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));
601 fn test_read_with_timeout() {
602 let addr = next_test_ip4();
604 let stream = t!(UdpSocket::bind(&addr));
605 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
607 t!(stream.send_to(b"hello world", &addr));
609 let mut buf = [0; 11];
610 t!(stream.recv_from(&mut buf));
611 assert_eq!(b"hello world", &buf[..]);
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));
620 fn connect_send_recv() {
621 let addr = next_test_ip4();
623 let socket = t!(UdpSocket::bind(&addr));
624 t!(socket.connect(addr));
626 t!(socket.send(b"hello world"));
628 let mut buf = [0; 11];
629 t!(socket.recv(&mut buf));
630 assert_eq!(b"hello world", &buf[..]);
637 let addr = next_test_ip4();
639 let stream = t!(UdpSocket::bind(&addr));
641 t!(stream.set_ttl(ttl));
642 assert_eq!(ttl, t!(stream.ttl()));
646 fn set_nonblocking() {
647 let addr = next_test_ip4();
649 let stream = t!(UdpSocket::bind(&addr));
651 t!(stream.set_nonblocking(true));
652 t!(stream.set_nonblocking(false));