如何从 LIBPCAP 获取信息?

How get information from LIBPCAP?

本文关键字:信息 获取 LIBPCAP      更新时间:2023-10-16

我需要获取有关互联网包的信息,我正在尝试使用以下代码,但我没有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("%sn",errbuf);
exit(1);
}
/* print out device name */
printf("DEV: %sn",dev);
/* ask pcap for the network address and mask of the device */
ret = pcap_lookupnet(dev,&netp,&maskp,errbuf);
if(ret == -1)
{
printf("%sn",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: %sn",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: %sn",mask);
return 0;
}

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

我没有C++的经验

尽管代码可以使用C++编译器进行编译,但它看起来更像是 C 代码。文件的名称、ldev.c和使用的编译器也表明它是一个C程序。

当我执行此代码时,我得到一个文件a.out但我无法打开该文件,为什么?

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

gcc ldev.c -lpcap

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

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

./a.out

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

DEV: eth0
NET: 192.168.12.0
MASK: 255.255.255.0

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

#include <fstream>

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

std::ofstream outputFile;

我们打开它使用

outputFile.open("random.csv");

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

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

然后不要忘记关闭它!

outputFile.close();