如何从 LIBPCAP 获取信息?

How get information from LIBPCAP?

我需要获取有关 Internet 包的信息,我正在尝试使用以下代码,但我没有使用 C++ 的经验。

我执行了本教程中的这段代码http://yuba.stanford.edu/~casado/pcap/section1.html

#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>  /* GIMME a libpcap plz! */
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char **argv)
{
  char *dev; /* name of the device to use */ 
  char *net; /* dot notation of the network address */
  char *mask;/* dot notation of the network mask    */
  int ret;   /* return code */
  char errbuf[PCAP_ERRBUF_SIZE];
  bpf_u_int32 netp; /* ip          */
  bpf_u_int32 maskp;/* subnet mask */
  struct in_addr addr;

  /* ask pcap to find a valid device for use to sniff on */
  dev = pcap_lookupdev(errbuf);

  /* error checking */
  if(dev == NULL)
  {
   printf("%s\n",errbuf);
   exit(1);
  }

  /* print out device name */
  printf("DEV: %s\n",dev);

  /* ask pcap for the network address and mask of the device */
  ret = pcap_lookupnet(dev,&netp,&maskp,errbuf);

  if(ret == -1)
  {
   printf("%s\n",errbuf);
   exit(1);
  }

  /* get the network address in a human readable form */
  addr.s_addr = netp;
  net = inet_ntoa(addr);

  if(net == NULL)/* thanks Scott :-P */
  {
    perror("inet_ntoa");
    exit(1);
  }

  printf("NET: %s\n",net);

  /* do the same as above for the device's mask */
  addr.s_addr = maskp;
  mask = inet_ntoa(addr);

  if(mask == NULL)
  {
    perror("inet_ntoa");
    exit(1);
  }

  printf("MASK: %s\n",mask);

  return 0;
}

当我执行这段代码时,我得到了一个文件 a.out 但我无法打开该文件,为什么?如何将我的信息传递给 .csv?

写入 .csv 文件与写入任何其他文件的基本操作没有太大区别。 我们需要使用库

打开文件
#include <fstream>

然后我们创建要写入的文件

std::ofstream outputFile;

我们使用

打开它
outputFile.open("random.csv");

并开始使用逗号作为分隔符书写

outputFile << "a,b,c,\n";
outputFile << mask << "\n"; // in your case

那别忘了关闭它!

outputFile.close();

I don't have experience with C++

虽然代码可能使用 C++ 编译器编译,但它看起来更像 C 代码。文件名 ldev.c 和使用的编译器也表明它是一个 C 程序。

When I execute this code, I get a file a.out but I cannot open the file, why?

本教程的最后一步告诉您如何编译程序,而不是如何执行它:

gcc ldev.c -lpcap

该步骤生成 a.out,这是您应该执行的程序。

要实际执行程序,运行 命令:

./a.out

然后,如果一切正常,输出应该类似于:

DEV: eth0
NET: 192.168.12.0
MASK: 255.255.255.0