1 // Copyright 2013 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.
11 //! UDP (User Datagram Protocol) network connections.
13 //! This module contains the ability to open a UDP stream to a socket address.
14 //! The destination and binding addresses can either be an IPv4 or IPv6
15 //! address. There is no corresponding notion of a server because UDP is a
16 //! datagram protocol.
18 //! A UDP connection implements the `Reader` and `Writer` traits.
21 use result::{Ok, Err};
22 use io::net::ip::SocketAddr;
23 use io::{Reader, Writer, IoResult};
24 use rt::rtio::{RtioSocket, RtioUdpSocket, IoFactory, LocalIo};
26 /// A User Datagram Protocol socket.
27 pub struct UdpSocket {
28 priv obj: ~RtioUdpSocket
32 /// Creates a UDP socket from the given socket address.
33 pub fn bind(addr: SocketAddr) -> IoResult<UdpSocket> {
34 LocalIo::maybe_raise(|io| {
35 io.udp_bind(addr).map(|s| UdpSocket { obj: s })
39 /// Receives data from the socket. On success, returns the number of bytes
40 /// read and the address from whence the data came.
41 pub fn recvfrom(&mut self, buf: &mut [u8])
42 -> IoResult<(uint, SocketAddr)> {
43 self.obj.recvfrom(buf)
46 /// Sends data on the socket to the given address. Returns nothing on
48 pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> {
49 self.obj.sendto(buf, dst)
52 /// Creates a `UdpStream`, which allows use of the `Reader` and `Writer`
53 /// traits to receive and send data from the same address. This transfers
54 /// ownership of the socket to the stream.
56 /// Note that this call does not perform any actual network communication,
57 /// because UDP is a datagram protocol.
58 pub fn connect(self, other: SocketAddr) -> UdpStream {
65 /// Returns the socket address that this socket was created from.
66 pub fn socket_name(&mut self) -> IoResult<SocketAddr> {
67 self.obj.socket_name()
71 impl Clone for UdpSocket {
72 /// Creates a new handle to this UDP socket, allowing for simultaneous
73 /// reads and writes of the socket.
75 /// The underlying UDP socket will not be closed until all handles to the
76 /// socket have been deallocated. Two concurrent reads will not receive
77 /// the same data. Instead, the first read will receive the first packet
78 /// received, and the second read will receive the second packet.
79 fn clone(&self) -> UdpSocket {
81 obj: self.obj.clone(),
86 /// A type that allows convenient usage of a UDP stream connected to one
87 /// address via the `Reader` and `Writer` traits.
88 pub struct UdpStream {
89 priv socket: UdpSocket,
90 priv connected_to: SocketAddr
94 /// Allows access to the underlying UDP socket owned by this stream. This
95 /// is useful to, for example, use the socket to send data to hosts other
96 /// than the one that this stream is connected to.
97 pub fn as_socket<T>(&mut self, f: |&mut UdpSocket| -> T) -> T {
101 /// Consumes this UDP stream and returns out the underlying socket.
102 pub fn disconnect(self) -> UdpSocket {
107 impl Reader for UdpStream {
108 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
109 let peer = self.connected_to;
110 self.as_socket(|sock| {
111 match sock.recvfrom(buf) {
112 Ok((_nread, src)) if src != peer => Ok(0),
113 Ok((nread, _src)) => Ok(nread),
120 impl Writer for UdpStream {
121 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
122 let connected_to = self.connected_to;
123 self.as_socket(|sock| sock.sendto(buf, connected_to))
130 use io::net::ip::{SocketAddr};
132 // FIXME #11530 this fails on android because tests are run as root
133 iotest!(fn bind_error() {
134 let addr = SocketAddr { ip: Ipv4Addr(0, 0, 0, 0), port: 1 };
135 match UdpSocket::bind(addr) {
137 Err(e) => assert_eq!(e.kind, PermissionDenied),
139 } #[ignore(cfg(windows))] #[ignore(cfg(target_os = "android"))])
141 iotest!(fn socket_smoke_test_ip4() {
142 let server_ip = next_test_ip4();
143 let client_ip = next_test_ip4();
144 let (tx1, rx1) = channel();
145 let (tx2, rx2) = channel();
148 match UdpSocket::bind(client_ip) {
149 Ok(ref mut client) => {
151 client.sendto([99], server_ip).unwrap()
158 match UdpSocket::bind(server_ip) {
159 Ok(ref mut server) => {
162 match server.recvfrom(buf) {
163 Ok((nread, src)) => {
164 assert_eq!(nread, 1);
165 assert_eq!(buf[0], 99);
166 assert_eq!(src, client_ip);
176 iotest!(fn socket_smoke_test_ip6() {
177 let server_ip = next_test_ip6();
178 let client_ip = next_test_ip6();
179 let (tx, rx) = channel::<()>();
182 match UdpSocket::bind(client_ip) {
183 Ok(ref mut client) => {
185 client.sendto([99], server_ip).unwrap()
191 match UdpSocket::bind(server_ip) {
192 Ok(ref mut server) => {
195 match server.recvfrom(buf) {
196 Ok((nread, src)) => {
197 assert_eq!(nread, 1);
198 assert_eq!(buf[0], 99);
199 assert_eq!(src, client_ip);
208 iotest!(fn stream_smoke_test_ip4() {
209 let server_ip = next_test_ip4();
210 let client_ip = next_test_ip4();
211 let (tx1, rx1) = channel();
212 let (tx2, rx2) = channel();
215 match UdpSocket::bind(client_ip) {
217 let client = ~client;
218 let mut stream = client.connect(server_ip);
220 stream.write([99]).unwrap();
227 match UdpSocket::bind(server_ip) {
229 let server = ~server;
230 let mut stream = server.connect(client_ip);
233 match stream.read(buf) {
235 assert_eq!(nread, 1);
236 assert_eq!(buf[0], 99);
246 iotest!(fn stream_smoke_test_ip6() {
247 let server_ip = next_test_ip6();
248 let client_ip = next_test_ip6();
249 let (tx1, rx1) = channel();
250 let (tx2, rx2) = channel();
253 match UdpSocket::bind(client_ip) {
255 let client = ~client;
256 let mut stream = client.connect(server_ip);
258 stream.write([99]).unwrap();
265 match UdpSocket::bind(server_ip) {
267 let server = ~server;
268 let mut stream = server.connect(client_ip);
271 match stream.read(buf) {
273 assert_eq!(nread, 1);
274 assert_eq!(buf[0], 99);
284 pub fn socket_name(addr: SocketAddr) {
285 let server = UdpSocket::bind(addr);
287 assert!(server.is_ok());
288 let mut server = server.unwrap();
290 // Make sure socket_name gives
291 // us the socket we binded to.
292 let so_name = server.socket_name();
293 assert!(so_name.is_ok());
294 assert_eq!(addr, so_name.unwrap());
297 iotest!(fn socket_name_ip4() {
298 socket_name(next_test_ip4());
301 iotest!(fn socket_name_ip6() {
302 socket_name(next_test_ip6());
305 iotest!(fn udp_clone_smoke() {
306 let addr1 = next_test_ip4();
307 let addr2 = next_test_ip4();
308 let mut sock1 = UdpSocket::bind(addr1).unwrap();
309 let sock2 = UdpSocket::bind(addr2).unwrap();
312 let mut sock2 = sock2;
313 let mut buf = [0, 0];
314 assert_eq!(sock2.recvfrom(buf), Ok((1, addr1)));
315 assert_eq!(buf[0], 1);
316 sock2.sendto([2], addr1).unwrap();
319 let sock3 = sock1.clone();
321 let (tx1, rx1) = channel();
322 let (tx2, rx2) = channel();
324 let mut sock3 = sock3;
326 sock3.sendto([1], addr2).unwrap();
330 let mut buf = [0, 0];
331 assert_eq!(sock1.recvfrom(buf), Ok((1, addr2)));
335 iotest!(fn udp_clone_two_read() {
336 let addr1 = next_test_ip4();
337 let addr2 = next_test_ip4();
338 let mut sock1 = UdpSocket::bind(addr1).unwrap();
339 let sock2 = UdpSocket::bind(addr2).unwrap();
340 let (tx1, rx) = channel();
341 let tx2 = tx1.clone();
344 let mut sock2 = sock2;
345 sock2.sendto([1], addr1).unwrap();
347 sock2.sendto([2], addr1).unwrap();
351 let sock3 = sock1.clone();
353 let (done, rx) = channel();
355 let mut sock3 = sock3;
356 let mut buf = [0, 0];
357 sock3.recvfrom(buf).unwrap();
361 let mut buf = [0, 0];
362 sock1.recvfrom(buf).unwrap();
368 iotest!(fn udp_clone_two_write() {
369 let addr1 = next_test_ip4();
370 let addr2 = next_test_ip4();
371 let mut sock1 = UdpSocket::bind(addr1).unwrap();
372 let sock2 = UdpSocket::bind(addr2).unwrap();
374 let (tx, rx) = channel();
375 let (serv_tx, serv_rx) = channel();
378 let mut sock2 = sock2;
379 let mut buf = [0, 1];
382 match sock2.recvfrom(buf) {
384 Err(e) => fail!("failed receive: {}", e),
389 let sock3 = sock1.clone();
391 let (done, rx) = channel();
392 let tx2 = tx.clone();
394 let mut sock3 = sock3;
395 match sock3.sendto([1], addr2) {
396 Ok(..) => { let _ = tx2.try_send(()); }
401 match sock1.sendto([2], addr2) {
402 Ok(..) => { let _ = tx.try_send(()); }