浏览代码

Make binding the UDP socket an explicit operation.

whitequark 8 年之前
父节点
当前提交
70a09735c9
共有 2 个文件被更改,包括 19 次插入7 次删除
  1. 6 4
      examples/server.rs
  2. 13 3
      src/socket/udp.rs

+ 6 - 4
examples/server.rs

@@ -12,7 +12,7 @@ use env_logger::{LogBuilder};
 
 use smoltcp::Error;
 use smoltcp::phy::{Tracer, FaultInjector, TapInterface};
-use smoltcp::wire::{EthernetFrame, EthernetAddress, IpAddress, IpEndpoint};
+use smoltcp::wire::{EthernetFrame, EthernetAddress, IpAddress};
 use smoltcp::wire::PrettyPrinter;
 use smoltcp::iface::{ArpCache, SliceArpCache, EthernetInterface};
 use smoltcp::socket::AsSocket;
@@ -68,11 +68,9 @@ fn main() {
 
     let arp_cache = SliceArpCache::new(vec![Default::default(); 8]);
 
-    let endpoint = IpEndpoint::new(IpAddress::default(), 6969);
-
     let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 64])]);
     let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketBuffer::new(vec![0; 128])]);
-    let udp_socket = UdpSocket::new(endpoint, udp_rx_buffer, udp_tx_buffer);
+    let udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer);
 
     let tcp1_rx_buffer = TcpSocketBuffer::new(vec![0; 64]);
     let tcp1_tx_buffer = TcpSocketBuffer::new(vec![0; 128]);
@@ -97,6 +95,10 @@ fn main() {
         // udp:6969: respond "yo dawg"
         {
             let socket: &mut UdpSocket = iface.sockets_mut().get_mut(&udp_handle).as_socket();
+            if socket.endpoint().is_unspecified() {
+                socket.bind(6969)
+            }
+
             let client = match socket.recv() {
                 Ok((endpoint, data)) => {
                     debug!("udp:6969 recv data: {:?} from {}",

+ 13 - 3
src/socket/udp.rs

@@ -113,16 +113,26 @@ pub struct UdpSocket<'a, 'b: 'a> {
 
 impl<'a, 'b> UdpSocket<'a, 'b> {
     /// Create an UDP socket with the given buffers.
-    pub fn new(endpoint: IpEndpoint,
-               rx_buffer: SocketBuffer<'a, 'b>, tx_buffer: SocketBuffer<'a, 'b>)
+    pub fn new(rx_buffer: SocketBuffer<'a, 'b>, tx_buffer: SocketBuffer<'a, 'b>)
             -> Socket<'a, 'b> {
         Socket::Udp(UdpSocket {
-            endpoint:  endpoint,
+            endpoint:  IpEndpoint::default(),
             rx_buffer: rx_buffer,
             tx_buffer: tx_buffer
         })
     }
 
+    /// Return the bound endpoint.
+    #[inline]
+    pub fn endpoint(&self) -> IpEndpoint {
+        self.endpoint
+    }
+
+    /// Bind the socket to the given endpoint.
+    pub fn bind<T: Into<IpEndpoint>>(&mut self, endpoint: T) {
+        self.endpoint = endpoint.into()
+    }
+
     /// Enqueue a packet to be sent to a given remote endpoint, and return a pointer
     /// to its payload.
     ///