forked from ITAnt/SecondProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path流量采集C语言版
More file actions
101 lines (87 loc) · 2.18 KB
/
流量采集C语言版
File metadata and controls
101 lines (87 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <net/if.h>
#include <net/ethernet.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <linux/if_ether.h>
// 运行程序(./mypacket),再浏览网页。程序会自动监控本机网卡,抓取链路层的数据包,简单分析数据包内容。
int promisc(const char *nif, int sock)
{
struct ifreq ifr;
strncpy(ifr.ifr_name, nif, strlen(nif)+1);
if(ioctl(sock, SIOCGIFFLAGS, &ifr) == -1)
{
perror("ioctl error!\n");
exit(1);
}
ifr.ifr_flags |= IFF_PROMISC;
if(ioctl(sock, SIOCSIFFLAGS, &ifr) == -1)
{
perror("ioctl error!\n");
exit(2);
}
}
void main()
{
struct sockaddr_in addr;
struct ether_header *peth;
struct iphdr *pip;
struct tcphdr *ptcp;
struct udphdr *pudp;
char *ptemp;
char buf[40960];
int sock, len;
int num;
printf("%ld, %ld, %ld, %ld\n", sizeof(struct ether_header), sizeof(struct iphdr), sizeof(struct tcphdr), sizeof(struct udphdr));
sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if(sock == -1)
{
perror("socket error!\n");
exit(3);
}
promisc("eth6", sock);
len = sizeof(addr);
while(1)
{
num = recvfrom(sock, (char *)buf, sizeof(buf), 0, (struct sockaddr *)&addr, &len);
buf[num] = '\0';
ptemp = buf;
printf("\nCatch a packet!\n");
peth = (struct ether_header*) ptemp;
ptemp += sizeof(struct ether_header);
pip = (struct iphdr *) ptemp;
ptemp += sizeof(struct iphdr);
switch(pip->protocol)
{
case IPPROTO_TCP:
ptcp = (struct tcphdr*)ptemp;
printf("TCP pkt : FROM : [%s]:[%d] ", inet_ntoa(*(struct in_addr *)&(pip->saddr)), ntohs(ptcp->source));
printf("TO : [%s]:[%d] \n", inet_ntoa(*(struct in_addr*)&(pip->daddr)), ntohs(ptcp->dest));
ptemp += sizeof(struct tcphdr);
puts("The datas:\n");
puts(ptemp);
break;
case IPPROTO_UDP:
break;
case IPPROTO_ICMP:
break;
case IPPROTO_IGMP:
break;
default:
printf("Unknown pkt, protocl:%d ", pip->protocol);
break;
}
}
}