Skip to content

Commit 3190b9f

Browse files
committed
增加 pcap 示例代码
1 parent 2d069c2 commit 3190b9f

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

libs/cpp.wiki

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1177,6 +1177,63 @@ Wikipedia:[https://en.wikipedia.org/wiki/Pcap 英文]
11771177

11781178
很著名的 Sniffer 抓包库,基于 C 语言开发。
11791179

1180+
代码示例——一个简单的抓包示例
1181+
<source lang="cpp">
1182+
&#35;include <stdio.h>
1183+
&#35;include <pcap.h>
1184+
1185+
int main(int argc, char* argv[])
1186+
{
1187+
pcap_t* handle; /* Session handle */
1188+
char* dev; /* The device to sniff on */
1189+
char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */
1190+
struct bpf_program fp; /* The compiled filter */
1191+
char filter_exp[] = "port 23"; /* The filter expression */
1192+
bpf_u_int32 mask; /* Our netmask */
1193+
bpf_u_int32 net; /* Our IP */
1194+
struct pcap_pkthdr header; /* The header that pcap gives us */
1195+
const u_char* packet; /* The actual packet */
1196+
1197+
/* Define the device */
1198+
dev = pcap_lookupdev(errbuf);
1199+
if(dev == NULL)
1200+
{
1201+
fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
1202+
return 2;
1203+
}
1204+
/* Find the properties for the device */
1205+
if(pcap_lookupnet(dev, &net, &mask, errbuf) == -1)
1206+
{
1207+
fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
1208+
net = 0;
1209+
mask = 0;
1210+
}
1211+
/* Open the session in promiscuous mode */
1212+
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
1213+
if(handle == NULL)
1214+
{
1215+
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
1216+
return 2;
1217+
}
1218+
/* Compile and apply the filter */
1219+
if(pcap_compile(handle, &fp, filter_exp, 0, net) == -1)
1220+
{
1221+
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
1222+
return 2;
1223+
}
1224+
if(pcap_setfilter(handle, &fp) == -1)
1225+
{
1226+
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
1227+
return 2;
1228+
}
1229+
1230+
packet = pcap_next(handle, &header); /* Grab a packet */
1231+
printf("Jacked a packet with length of [%d]\n", header.len);
1232+
pcap_close(handle); /* Close the session */
1233+
return 0;
1234+
}
1235+
</source>
1236+
11801237
<h4>WinPcap</h4>
11811238

11821239
Home:[http://www.winpcap.org/]

0 commit comments

Comments
 (0)