和我一起学libpcap(2)
--------------------------------------------------------------------------------
doggy 2002-05-24 14:08:23
2.2 现在的程序(C++)
文件名p.cxx
#ifdef __cplusplus
extern "C" {
#endif
#include <pcap.h>
#ifdef __cplusplus
}
#endif
void printer(u_char * user, const struct pcap_pkthdr * h, const u_char * p)
{
printf("I get one packet! ");
/* 哈哈,我都想喝一杯庆祝一下了! */
}
#define DEFAULT_SNAPLEN 68
/* 别问我为什么是68,我从tcpdump看来的 */
int main()
{
char ebuf[PCAP_ERRBUF_SIZE];
char *device = pcap_lookupdev(ebuf);
bpf_u_int32 localnet, netmask;
pcap_lookupnet(device, &localnet, &netmask, ebuf);
printf("%u.%u.%u.%u", localnet&0xff, localnet>>8&0xff,
localnet>>16&0xff, localnet>>24&0xff);
printf(":%d.%d.%d.%d ", netmask&0xff, netmask>>8&0xff,
netmask>>16&0xff, netmask>>24&0xff);
struct pcap_t *pd = pcap_open_live(device, DEFAULT_SNAPLEN, 0, 1000, ebuf);
if(pcap_datalink(pd) == DLT_EN10MB)
printf("10Mb以太网 ");
struct bpf_program fcode;
pcap_compile(pd, &fcode, NULL, 1, 0);
pcap_setfilter(pd, &fcode);
pcap_loop(pd, 10, printer, NULL);
struct pcap_stat stat;
pcap_stats(pd, &stat);
printf("recv %d, drop %d. ", stat.ps_recv, stat.ps_drop);
pcap_close(pd);
}
#gcc p.cxx -lpcap
#./a.out
166.111.168.0:255.255.252.0
10Mb以太网
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
recv 10, drop 0.
#
重要提示: libpcap 程序需要root权限
费了半天劲显示网段和掩码,抓了10个包,值得吗?
转载 bbs水木清华
--------------------------------------------------------------------------------
doggy 2002-05-24 14:08:23
2.2 现在的程序(C++)
文件名p.cxx
#ifdef __cplusplus
extern "C" {
#endif
#include <pcap.h>
#ifdef __cplusplus
}
#endif
void printer(u_char * user, const struct pcap_pkthdr * h, const u_char * p)
{
printf("I get one packet! ");
/* 哈哈,我都想喝一杯庆祝一下了! */
}
#define DEFAULT_SNAPLEN 68
/* 别问我为什么是68,我从tcpdump看来的 */
int main()
{
char ebuf[PCAP_ERRBUF_SIZE];
char *device = pcap_lookupdev(ebuf);
bpf_u_int32 localnet, netmask;
pcap_lookupnet(device, &localnet, &netmask, ebuf);
printf("%u.%u.%u.%u", localnet&0xff, localnet>>8&0xff,
localnet>>16&0xff, localnet>>24&0xff);
printf(":%d.%d.%d.%d ", netmask&0xff, netmask>>8&0xff,
netmask>>16&0xff, netmask>>24&0xff);
struct pcap_t *pd = pcap_open_live(device, DEFAULT_SNAPLEN, 0, 1000, ebuf);
if(pcap_datalink(pd) == DLT_EN10MB)
printf("10Mb以太网 ");
struct bpf_program fcode;
pcap_compile(pd, &fcode, NULL, 1, 0);
pcap_setfilter(pd, &fcode);
pcap_loop(pd, 10, printer, NULL);
struct pcap_stat stat;
pcap_stats(pd, &stat);
printf("recv %d, drop %d. ", stat.ps_recv, stat.ps_drop);
pcap_close(pd);
}
#gcc p.cxx -lpcap
#./a.out
166.111.168.0:255.255.252.0
10Mb以太网
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
I get one packet!
recv 10, drop 0.
#
重要提示: libpcap 程序需要root权限
费了半天劲显示网段和掩码,抓了10个包,值得吗?
转载 bbs水木清华