libpcap - 入门
原创
©著作权归作者所有:来自51CTO博客作者qq635f6f89e5645的原创作品,请联系作者获取转载授权,否则将追究法律责任
loopupdev
#include <pcap.h>
#include <stdio.h>
int main()
{
char err_buf[PCAP_ERRBUF_SIZE], *device;
device = pcap_lookupdev(err_buf);
if (device)
printf("success: device: %s\n", device);
else
printf("error: %s\n", err_buf);
return 0;
}
pcap_lookupdev这个函数返回的是网络接口的字符串。
编译:gcc pcap_lookupdev.c -o pcap_lookupdev -lpcap
输出:success: device: eth1
pcap_next
#include <pcap.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
char err_buf[PCAP_ERRBUF_SIZE], *str_device = NULL;
pcap_t *pcap_device;
struct pcap_pkthdr packet;
const u_char *str_pkt;
str_device = pcap_lookupdev(err_buf);
if (str_device)
printf("success: device: %s\n", str_device);
else
printf("error: %s\n", err_buf);
pcap_device = pcap_open_live(str_device, 65535, 1, 0, err_buf);
if (!pcap_device) {
printf("error: pcap_open_live: %s\n", err_buf);
exit(1);
}
str_pkt = pcap_next(pcap_device, &packet);
if (!str_pkt) {
printf("did not capture a packet\n");
exit(1);
}
printf("packet length=%d\n", packet.len);
printf("number of bytes=%d\n", packet.caplen);
printf("recieved time=%s\n", ctime((const time_t *)&packet.ts.tv_sec));
for (i = 0; i < packet.len; i++) {
printf(" %02x", packet[i]);
if ((i + 1) % 16 == 0)
printf("\n");
}
printf("\n\n");
pcap_close(pcap_device);
return 0;
}
参考文章