我需要获取有关互联网包的信息,我正在尝试使用以下代码,但我没有 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?
我没有 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();