Sfoglia il codice sorgente

Add a TCP client example.

whitequark 8 anni fa
parent
commit
a0f2c62ac9
4 ha cambiato i file con 99 aggiunte e 6 eliminazioni
  1. 3 0
      Cargo.toml
  2. 86 0
      examples/client.rs
  3. 1 1
      examples/server.rs
  4. 9 5
      examples/utils.rs

+ 3 - 0
Cargo.toml

@@ -34,3 +34,6 @@ name = "tcpdump"
 
 
 [[example]]
 [[example]]
 name = "server"
 name = "server"
+
+[[example]]
+name = "client"

+ 86 - 0
examples/client.rs

@@ -0,0 +1,86 @@
+#[macro_use]
+extern crate log;
+extern crate env_logger;
+extern crate getopts;
+extern crate smoltcp;
+
+mod utils;
+
+use std::str::{self, FromStr};
+use std::time::Instant;
+use smoltcp::wire::{EthernetAddress, IpAddress};
+use smoltcp::iface::{ArpCache, SliceArpCache, EthernetInterface};
+use smoltcp::socket::{AsSocket, SocketSet};
+use smoltcp::socket::{TcpSocket, TcpSocketBuffer};
+
+fn main() {
+    utils::setup_logging();
+    let (device, args) = utils::setup_device(&["ADDRESS", "PORT"]);
+    let address = IpAddress::from_str(&args[0]).expect("invalid address format");
+    let port = u16::from_str(&args[1]).expect("invalid port format");
+
+    let startup_time = Instant::now();
+
+    let arp_cache = SliceArpCache::new(vec![Default::default(); 8]);
+
+    let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; 64]);
+    let tcp_tx_buffer = TcpSocketBuffer::new(vec![0; 128]);
+    let tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer);
+
+    let hardware_addr  = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
+    let protocol_addr  = IpAddress::v4(192, 168, 69, 1);
+    let mut iface      = EthernetInterface::new(
+        Box::new(device), Box::new(arp_cache) as Box<ArpCache>,
+        hardware_addr, [protocol_addr]);
+
+    let mut sockets = SocketSet::new(vec![]);
+    let tcp_handle = sockets.add(tcp_socket);
+
+    {
+        let socket: &mut TcpSocket = sockets.get_mut(tcp_handle).as_socket();
+        socket.connect((address, port), (protocol_addr, 49500)).unwrap();
+    }
+
+    let mut tcp_active = false;
+    loop {
+        {
+            let socket: &mut TcpSocket = sockets.get_mut(tcp_handle).as_socket();
+            if socket.is_active() && !tcp_active {
+                debug!("connected");
+            } else if !socket.is_active() && tcp_active {
+                debug!("disconnected");
+            }
+            tcp_active = socket.is_active();
+
+            if socket.may_recv() {
+                let data = {
+                    let mut data = socket.recv(128).unwrap().to_owned();
+                    if data.len() > 0 {
+                        debug!("recv data: {:?}",
+                               str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)"));
+                        data = data.split(|&b| b == b'\n').collect::<Vec<_>>().concat();
+                        data.reverse();
+                        data.extend(b"\n");
+                    }
+                    data
+                };
+                if socket.can_send() && data.len() > 0 {
+                    debug!("send data: {:?}",
+                           str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)"));
+                    socket.send_slice(&data[..]).unwrap();
+                }
+            } else if socket.may_send() {
+                debug!("close");
+                socket.close();
+            }
+        }
+
+        let timestamp = Instant::now().duration_since(startup_time);
+        let timestamp_ms = (timestamp.as_secs() * 1000) +
+                           (timestamp.subsec_nanos() / 1000000) as u64;
+        match iface.poll(&mut sockets, timestamp_ms) {
+            Ok(()) => (),
+            Err(e) => debug!("poll error: {}", e)
+        }
+    }
+}

+ 1 - 1
examples/server.rs

@@ -16,7 +16,7 @@ use smoltcp::socket::{TcpSocket, TcpSocketBuffer};
 
 
 fn main() {
 fn main() {
     utils::setup_logging();
     utils::setup_logging();
-    let device = utils::setup_device();
+    let (device, _args) = utils::setup_device(&[]);
 
 
     let startup_time = Instant::now();
     let startup_time = Instant::now();
 
 

+ 9 - 5
examples/utils.rs

@@ -30,17 +30,21 @@ pub fn setup_logging() {
         .unwrap();
         .unwrap();
 }
 }
 
 
-pub fn setup_device() -> Tracer<FaultInjector<TapInterface>, EthernetFrame<&'static [u8]>> {
+pub fn setup_device(more_args: &[&str])
+        -> (Tracer<FaultInjector<TapInterface>, EthernetFrame<&'static [u8]>>,
+            Vec<String>) {
     let mut opts = getopts::Options::new();
     let mut opts = getopts::Options::new();
     opts.optopt("", "drop-chance", "Chance of dropping a packet (%)", "CHANCE");
     opts.optopt("", "drop-chance", "Chance of dropping a packet (%)", "CHANCE");
     opts.optopt("", "corrupt-chance", "Chance of corrupting a packet (%)", "CHANCE");
     opts.optopt("", "corrupt-chance", "Chance of corrupting a packet (%)", "CHANCE");
     opts.optflag("h", "help", "print this help menu");
     opts.optflag("h", "help", "print this help menu");
 
 
     let matches = opts.parse(env::args().skip(1)).unwrap();
     let matches = opts.parse(env::args().skip(1)).unwrap();
-    if matches.opt_present("h") || matches.free.len() != 1 {
-        let brief = format!("Usage: {} INTERFACE [options]", env::args().nth(0).unwrap());
+    if matches.opt_present("h") || matches.free.len() != more_args.len() + 1 {
+        let brief = format!("Usage: {} INTERFACE {} [options]",
+                            env::args().nth(0).unwrap(),
+                            more_args.join(" "));
         print!("{}", opts.usage(&brief));
         print!("{}", opts.usage(&brief));
-        process::exit(if matches.free.len() != 1 { 1 } else { 0 });
+        process::exit(if matches.free.len() != more_args.len() + 1 { 1 } else { 0 });
     }
     }
     let drop_chance    = u8::from_str(&matches.opt_str("drop-chance")
     let drop_chance    = u8::from_str(&matches.opt_str("drop-chance")
                                              .unwrap_or("0".to_string())).unwrap();
                                              .unwrap_or("0".to_string())).unwrap();
@@ -59,5 +63,5 @@ pub fn setup_device() -> Tracer<FaultInjector<TapInterface>, EthernetFrame<&'sta
     device.set_corrupt_chance(corrupt_chance);
     device.set_corrupt_chance(corrupt_chance);
     let device = Tracer::<_, EthernetFrame<&'static [u8]>>::new(device, trace_writer);
     let device = Tracer::<_, EthernetFrame<&'static [u8]>>::new(device, trace_writer);
 
 
-    device
+    (device, matches.free[1..].to_owned())
 }
 }