linux下抓包程序
#include <netinet/if_ether.h>#include <net/ethernet.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <net/bpf.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <pcap.h>
#define CMD "tcp"
void capture_packet(int datalink, pcap_t *pd, struct bpf_program fcode);
char *next_pcap(int *len, pcap_t *pd);
int main(int argc, char **argv)
{
char *device = NULL;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *pd;
int datalink;
struct bpf_program fcode;
uint32_t localnet, netmask;
char str1[INET_ADDRSTRLEN], str2[INET_ADDRSTRLEN];
if ((device = pcap_lookupdev(errbuf)) == NULL) {
fprintf(stderr, "lookupdev error: %s\n", errbuf);
exit(1);
} else
printf("device = %s\n", device);
/** 没有将接口投入混杂模式 **/
if ((pd = pcap_open_live(device, 200, 0, 500, errbuf)) == NULL) {
fprintf(stderr, "pcap_open_live error: %s\n", errbuf);
exit(1);
}
if (pcap_lookupnet(device, &localnet, &netmask, errbuf) < 0) {
fprintf(stderr, "pcap_lookupnet error: %s\n", errbuf);
exit(1);
}
printf("localnet = %s, netmask = %s\n",
inet_ntop(AF_INET, &localnet, str1, sizeof(str1)),
inet_ntop(AF_INET, &netmask, str2, sizeof(str2)));
if (pcap_compile(pd, &fcode, CMD, 0, netmask) < 0) {
fprintf(stderr, "pcap_compile error: %s\n", pcap_geterr(pd));
exit(1);
}
if (pcap_setfilter(pd, &fcode) < 0) {
fprintf(stderr, "pcap_setfilter: %s\n", pcap_geterr(pd));
exit(1);
}
if ((datalink = pcap_datalink(pd)) < 0) {
fprintf(stderr, "pcap_datalink error: %s\n", pcap_geterr(pd));
exit(1);
} else
printf("datalink = %d\n", datalink);
capture_packet(datalink, pd, fcode);
exit(0);
}
void capture_packet(int datalink, pcap_t *pd, struct bpf_program fcode)
{
int len;
char *ptr;
struct ip *ip;
struct ether_header *eptr; /** ethernet header **/
char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
for (;;) {
ptr = next_pcap(&len, pd);
switch (datalink) {
case DLT_NULL:
ptr += 4;
break;
case DLT_EN10MB:
ptr += 14;
break;
case DLT_SLIP:
ptr += 24;
break;
case DLT_PPP:
ptr += 24;
break;
}
/** 打印通信双方的IP地址 **/
ip = (struct ip *) ptr;
printf("src ip: %s <===> dst ip: %s\n",
inet_ntop(AF_INET, &ip->ip_src, src, sizeof(src)),
inet_ntop(AF_INET, &ip->ip_dst, dst, sizeof(dst)));
}
}
char *next_pcap(int *len, pcap_t *pd)
{
char *ptr;
struct pcap_pkthdr hdr;
while ((ptr = (char *) pcap_next(pd, &hdr)) == NULL);
*len = hdr.caplen;
return(ptr);
}
[此贴子已经被作者于2007-7-20 15:07:10编辑过]