Linux系统有线网络抓包程序

今天心血来潮,玩一玩linux抓包。思路如下:

1、使用raw socket接收网络数据;
2、先解析以太帧头,得到是IP还是ARP包;
3、再解析IP头,知道是UDP还是TCP;
4、再解析UDP、TCP,得到IP地址、端口号等信息。

注意事项:
1、网络传输使用大端字节序,对于如端口号、数据长度等字段,要使用ntohs做转换,否则结果不正确。
2、对于创建raw socket,不同参数得到的数据包不同,如传递ETH_P_IP则不会接收ARP、RARP包。
完整代码:

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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

#include <netdb.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/in.h>
#include <netpacket/packet.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <net/ethernet.h>


#define BUFFER_SIZE 2048

int debug_level = 0;

#define _AUTHOR "Late Lee"
#define _VERSION_STR "1.0"
#define _DATE ""

// 默认打印error等级
enum
{
MSG_ERROR = 0,
MSG_WARNING,
MSG_INFO,
MSG_DEBUG,
MSG_MSGDUMP,
MSG_EXCESSIVE,
};

void ll_printf(int level, const char *fmt, ...) __attribute__ ((format (printf, 2, 3)));

void ll_printf(int level, const char *fmt, ...)
{
va_list ap;

va_start(ap, fmt);
if (debug_level >= level)
{
#ifdef CONFIG_DEBUG_SYSLOG
if (wpa_debug_syslog) {
vsyslog(syslog_priority(level), fmt, ap);
} else {
#endif /* CONFIG_DEBUG_SYSLOG */
//debug_print_timestamp();
#ifdef CONFIG_DEBUG_FILE
if (out_file) {
vfprintf(out_file, fmt, ap);
fprintf(out_file, "\n");
} else {
#endif /* CONFIG_DEBUG_FILE */
vprintf(fmt, ap);
printf("\n");
#ifdef CONFIG_DEBUG_FILE
}
#endif /* CONFIG_DEBUG_FILE */
#ifdef CONFIG_DEBUG_SYSLOG
}
#endif /* CONFIG_DEBUG_SYSLOG */
}
va_end(ap);
}

void show_version(char* name)
{
printf("%s by %s, version: %s\n", name, _AUTHOR, _VERSION_STR);
}


const char* my_opt = "hvd:i:";

void usage(char* name)
{
show_version(name);

printf(" -h, short help\n");
printf(" -v, show version\n");
printf(" -d, debug level\n");
printf(" -i, ethernet device\n");

exit(0);
}

void dump(const char *buffer, int len)
{
int i, j, n;
int line = 16;
char c;
unsigned char* buf = (unsigned char *)buffer; // 必须是unsigned char类型

n = len / line;
if (len % line)
n++;

for (i=0; i<n; i++)
{
//printf("0x%08x: ", (unsigned int)(buf+i*line)); // linux ok
printf("0x%8p: ", buf+i*line); // windows ok

for (j=0; j<line; j++)
{
if ((i*line+j) < len)
printf("%02x ", buf[i*line+j]);
else
printf(" ");
}

printf(" ");
for (j=0; j<line && (i*line+j)<len; j++)
{
if ((i*line+j) < len)
{
c = buf[i*line+j];
printf("%c", c >= ' ' && c < '~' ? c : '.');
}
else
printf(" ");
}

printf("\n");
}
}

int setPromiscMode(int socket, const char* eth, bool enable)
{
// 混杂模式
struct ifreq req;
strcpy(req.ifr_name, eth);

ioctl(socket, SIOCGIFFLAGS, &req);

if (enable)
{
req.ifr_flags |= IFF_PROMISC;
}
else
{
req.ifr_flags &= ~IFF_PROMISC;
}

int ret = ioctl(socket, SIOCSIFFLAGS, &req);
if (ret < 0)
{
perror("Set promisc mode failed:");
return -1;
}

return 0;
}

int initSocket(const char* eth)
{
int ret = 0;
int fd = -1;

if (eth == NULL)
{
return -1;
}

// 注意与下面绑定时协议一致
fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP)); // tocheck ETH_P_IP |
if (fd < 0)
{
perror("init socket failed:");
return -1;
}

// 接收buffer大小
int size = BUFFER_SIZE;
ret = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(int));
if (ret < 0)
{
goto end;
}

// 绑定网卡
struct ifreq req;
strcpy(req.ifr_name, eth);
ioctl(fd, SIOCGIFINDEX, &req);

struct sockaddr_ll addr;
addr.sll_family = PF_PACKET;
addr.sll_ifindex = req.ifr_ifindex;
addr.sll_protocol = htons(ETH_P_IP); // 取决于此处协议 ETH_P_ALL ETH_P_IP |ETH_P_ARP
ret = bind(fd, (struct sockaddr *)&addr, sizeof(sockaddr_ll));
if (ret < 0)
{
goto end;
}

// 混杂模式
//setPromiscMode(fd, eth, true);

end:
if (ret < 0)
{
close(fd);
return ret;
}
else
{
return fd;
}
}

int deintSocket(int socket)
{
close(socket);
return 0;
}

int showMacAddr(const struct ether_header *ethhead)
{
printf("mac: [%02x:%02x:%02x:%02x:%02x:%02x] --> ",
ethhead->ether_shost[0], ethhead->ether_shost[1],
ethhead->ether_shost[2], ethhead->ether_shost[3],
ethhead->ether_shost[4], ethhead->ether_shost[5]);

printf("mac: [%02x:%02x:%02x:%02x:%02x:%02x]\n",
ethhead->ether_dhost[0], ethhead->ether_dhost[1],
ethhead->ether_dhost[2], ethhead->ether_dhost[3],
ethhead->ether_dhost[4], ethhead->ether_dhost[5]);

return 0;
}

int parseTcpHeader(const char* buffer)
{
struct tcphdr* hdr = (struct tcphdr*)buffer;
printf("port: [%d] --> [%d]\n", ntohs(hdr->th_sport), ntohs(hdr->th_dport));
return 0;
}

int parseUdpHeader(const char* buffer)
{
const struct udphdr* hdr = reinterpret_cast<const struct udphdr *>(buffer); // (struct udphdr*)buffer;
// 长度字段与实际接收数据不符合,不知原因为何
printf("port: [%d] --> [%d] [%d bytes]\n", ntohs(hdr->uh_sport), ntohs(hdr->uh_dport), ntohs(hdr->uh_ulen));
return 0;
}

int parseIpHeader(const char* buffer)
{
if (NULL == buffer)
{
return -1;
}

#if 0
const struct ip* pstIP = reinterpret_cast<const struct ip *>(buffer); //(struct ip *)buffer;

/* 协议类型、源IP地址、目的IP地址 */
struct protoent* pstIpProto = getprotobynumber(pstIP->ip_p);
if(NULL != pstIpProto)
{
printf("%s(%d) ", pstIpProto->p_name, pstIP->ip_p);
}
else
{
printf("%s(%d) ", "None", pstIP->ip_p);
}
printf("ip: [%s] --> ", inet_ntoa(pstIP->ip_src));
printf("[%s]\n", inet_ntoa(pstIP->ip_dst));

struct protoent* pstIpProto = getprotobynumber(hdr->protocol);
if(NULL != pstIpProto)
{
printf("%s(%d) ", pstIpProto->p_name, hdr->protocol);
}
else
{
printf("%s(%d) ", "None", hdr->protocol);
}
#endif

const struct iphdr* hdr = (struct iphdr *)buffer;

struct in_addr saddr;
saddr.s_addr = hdr->saddr;
printf("ip: [%s] --> ", inet_ntoa(saddr));
saddr.s_addr = hdr->daddr;
printf("[%s] [%d bytes] ", inet_ntoa(saddr), ntohs(hdr->tot_len));

switch (hdr->protocol)
{
case IPPROTO_TCP:
printf("TCP\n");
parseTcpHeader(buffer+sizeof(iphdr));
break;
case IPPROTO_UDP:
printf("UDP\n");
parseUdpHeader(buffer+sizeof(iphdr));
break;
case IPPROTO_ICMP:
printf("ICMP\n");
break;
case IPPROTO_IGMP:
printf("IGMP\n");
break;
default:
break;
}
#if 0
if ( == IPPROTO_TCP)
{
printf("TCP\n");
parseTcpHeader(buffer+sizeof(iphdr));
}
if (hdr->protocol == IPPROTO_UDP)
{
printf("UDP\n");
parseUdpHeader(buffer+sizeof(iphdr));
}
if (hdr->protocol == IPPROTO_ICMP)
{
printf("ICMP\n");
}
if (hdr->protocol == IPPROTO_IGMP)
{
printf("IGMP\n");
}
#endif

return 0;
}

int parsePakcet(const char* buffer)
{
if (buffer == NULL)
{
return -1;
}

const struct ether_header *ethhead = reinterpret_cast<const struct ether_header *>(buffer); //(struct ether_header*)buffer;

///////////////////
int type = ntohs(ethhead->ether_type);

if (type == ETHERTYPE_ARP)
{
printf("ethnet type: ARP\n");
showMacAddr(ethhead);
}
if (type == ETHERTYPE_IP)
{
//printf("ethnet type: IP\n");
showMacAddr(ethhead);
parseIpHeader(buffer+sizeof(struct ether_header));
}


//printf("-------------------------------------------\n");

return 0;
}

int startCapture(int socket)
{
int ret = 0;
socklen_t len = sizeof(struct sockaddr);
char buffer[BUFFER_SIZE] = {0};

while (1)
{
memset(buffer, '\0', BUFFER_SIZE);
ret = recvfrom(socket, buffer, BUFFER_SIZE, 0, NULL, &len);
if (ret < 0)
{
continue;
}
//printf("--recv len: %d\n", ret);
if (debug_level)
dump(buffer, ret);
parsePakcet(buffer);

usleep(10*1000);
}

return 0;
}

int main(int argc, char* argv[])
{
char eth[8] = "eth0";

while(1)
{
int c = getopt(argc, argv, my_opt);
ll_printf(8, "option char: %x %c\n", c, c);
if (c < 0)
{
break;
}
switch(c)
{
case 'd':
debug_level = atoi(optarg);
//printf("debug level: %d\n", debug_level);
break;
case 'i':
strncpy(eth, optarg, 8);
break;
case '?':
case 'h':
default:
usage(argv[0]);
break;
}
}

printf("Start capture on %s\n", eth);

int socket = initSocket(eth);
if (socket < 0)
{
printf("Init socket failed.\n");
return -1;
}
startCapture(socket);
return 0;
}

注:为什么要表明“有线网络”?因为还要做无线网络抓包。

李迟 2016.9.6 周二 夜