packet2pcap.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. use getopts::Options;
  2. use smoltcp::phy::{PcapLinkType, PcapSink};
  3. use smoltcp::time::Instant;
  4. use std::env;
  5. use std::fs::File;
  6. use std::io::{self, Read};
  7. use std::path::Path;
  8. use std::process::exit;
  9. fn convert(
  10. packet_filename: &Path,
  11. pcap_filename: &Path,
  12. link_type: PcapLinkType,
  13. ) -> io::Result<()> {
  14. let mut packet_file = File::open(packet_filename)?;
  15. let mut packet = Vec::new();
  16. packet_file.read_to_end(&mut packet)?;
  17. let mut pcap_file = File::create(pcap_filename)?;
  18. PcapSink::global_header(&mut pcap_file, link_type);
  19. PcapSink::packet(&mut pcap_file, Instant::from_millis(0), &packet[..]);
  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(
  32. "t",
  33. "link-type",
  34. "set link type (one of: ethernet ip)",
  35. "TYPE",
  36. );
  37. let matches = match opts.parse(&args[1..]) {
  38. Ok(m) => m,
  39. Err(e) => {
  40. eprintln!("{}", e);
  41. return;
  42. }
  43. };
  44. let link_type = match matches.opt_str("t").as_ref().map(|s| &s[..]) {
  45. Some("ethernet") => Some(PcapLinkType::Ethernet),
  46. Some("ip") => Some(PcapLinkType::Ip),
  47. _ => None,
  48. };
  49. if matches.opt_present("h") || matches.free.len() != 2 || link_type.is_none() {
  50. print_usage(&program, opts);
  51. return;
  52. }
  53. match convert(
  54. Path::new(&matches.free[0]),
  55. Path::new(&matches.free[1]),
  56. link_type.unwrap(),
  57. ) {
  58. Ok(()) => (),
  59. Err(e) => {
  60. eprintln!("Cannot convert packet to pcap: {}", e);
  61. exit(1);
  62. }
  63. }
  64. }