packet2pcap.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. use std::cell::RefCell;
  2. use std::io::{self, Read, Write};
  3. use std::path::Path;
  4. use std::fs::File;
  5. use std::env;
  6. use std::process::exit;
  7. use smoltcp::phy::{PcapLinkType, PcapSink};
  8. use smoltcp::time::Instant;
  9. use getopts::Options;
  10. fn convert(packet_filename: &Path, pcap_filename: &Path, link_type: PcapLinkType)
  11. -> io::Result<()> {
  12. let mut packet_file = File::open(packet_filename)?;
  13. let mut packet = Vec::new();
  14. packet_file.read_to_end(&mut packet)?;
  15. let pcap = RefCell::new(Vec::new());
  16. PcapSink::global_header(&pcap, link_type);
  17. PcapSink::packet(&pcap, Instant::from_millis(0), &packet[..]);
  18. let mut pcap_file = File::create(pcap_filename)?;
  19. pcap_file.write_all(&pcap.borrow()[..])?;
  20. Ok(())
  21. }
  22. fn print_usage(program: &str, opts: Options) {
  23. let brief = format!("Usage: {} [options] INPUT OUTPUT", program);
  24. print!("{}", opts.usage(&brief));
  25. }
  26. fn main() {
  27. let args: Vec<String> = env::args().collect();
  28. let program = args[0].clone();
  29. let mut opts = Options::new();
  30. opts.optflag("h", "help", "print this help menu");
  31. opts.optopt("t", "link-type", "set link type (one of: ethernet ip)", "TYPE");
  32. let matches = match opts.parse(&args[1..]) {
  33. Ok(m) => m,
  34. Err(e) => {
  35. eprintln!("{}", e);
  36. return
  37. }
  38. };
  39. let link_type =
  40. match matches.opt_str("t").as_ref().map(|s| &s[..]) {
  41. Some("ethernet") => Some(PcapLinkType::Ethernet),
  42. Some("ip") => Some(PcapLinkType::Ip),
  43. _ => None
  44. };
  45. if matches.opt_present("h") || matches.free.len() != 2 || link_type.is_none() {
  46. print_usage(&program, opts);
  47. return
  48. }
  49. match convert(Path::new(&matches.free[0]),
  50. Path::new(&matches.free[1]),
  51. link_type.unwrap()) {
  52. Ok(()) => (),
  53. Err(e) => {
  54. eprintln!("Cannot convert packet to pcap: {}", e);
  55. exit(1);
  56. }
  57. }
  58. }