Learn LiBPCAP with me.

zhaozj2021-02-16  64

Learn LiBPCAP with me.

-------------------------------------------------- ------------------------------

Doggy 2002-05-24 14:08:23

2.2 Current Program (C )

File name p.cxx

#ifdef __cplusplus

Extern "C" {

#ENDIF

#include

#ifdef __cplusplus

}

#ENDIF

Void Printer (u_char * user, const struct pcap_pkthdr * h, const u_char * p)

{

Printf ("I get one packet!");

/ * Haha, I want to drink a cup to celebrate! * /

}

#define default_snaplen 68

/ * Don't ask me why I am 68, I seem to appear from 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 Ethernet");

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 Ethernet

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.

#

Important: libpcap programs need root privileges

I spent half a day to display the network segment and mask, caught 10 packages, worth it?

Reprinted BBS Shuimu Tsinghua

转载请注明原文地址:https://www.9cbs.com/read-16474.html

New Post(0)