标题:linux下抓包程序
只看楼主
Skai
Rank: 1
等 级:新手上路
帖 子:69
专家分:0
注 册:2006-8-30
 问题点数:0 回复次数:1 
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编辑过]

搜索更多相关主题的帖子: linux 
2007-07-20 15:06
hackerjiang
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:地球
等 级:版主
威 望:3
帖 子:780
专家分:111
注 册:2007-4-27
得分:0 
@强@

(づ ̄ 3 ̄)づ
2007-07-20 15:07



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-156857-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.064184 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved