Форум программистов, компьютерный форум, киберфорум
C++: Сети
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/18: Рейтинг темы: голосов - 18, средняя оценка - 5.00
1 / 1 / 0
Регистрация: 22.03.2011
Сообщений: 56

Определить и записать ARP пакет

04.12.2015, 00:02. Показов 3485. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Доброго времени суток всем. Пишу задачку универскую и возникла проблема - как перехватить ARP пакет?

Есть следующий код(знаю, что очень длинно, но всё же):
C++
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// ConsoleApplication3.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
 
/*
Simple Sniffer in winsock
*/
 
#include "stdio.h"
#include "winsock2.h"
 
#pragma comment(lib,"ws2_32.lib") //For winsock
 
#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1) //this removes the need of mstcpip.h
 
void StartSniffing(SOCKET Sock); //This will sniff here and there
 
void ProcessPacket(char*, int); //This will decide how to digest
void PrintIpHeader(char*);
void PrintIcmpPacket(char*, int);
void PrintUdpPacket(char*, int);
void PrintTcpPacket(char*, int);
void ConvertToHex(char*, unsigned int);
void PrintData(char*, int);
 
typedef struct ip_hdr
{
    unsigned char ip_header_len : 4; // 4-bit header length (in 32-bit words) normally=5 (Means 20 Bytes may be 24 also)
    unsigned char ip_version : 4; // 4-bit IPv4 version
    unsigned char ip_tos; // IP type of service
    unsigned short ip_total_length; // Total length
    unsigned short ip_id; // Unique identifier
 
    unsigned char ip_frag_offset : 5; // Fragment offset field
 
    unsigned char ip_more_fragment : 1;
    unsigned char ip_dont_fragment : 1;
    unsigned char ip_reserved_zero : 1;
 
    unsigned char ip_frag_offset1; //fragment offset
 
    unsigned char ip_ttl; // Time to live
    unsigned char ip_protocol; // Protocol(TCP,UDP etc)
    unsigned short ip_checksum; // IP checksum
    unsigned int ip_srcaddr; // Source address
    unsigned int ip_destaddr; // Source address
} IPV4_HDR;
 
typedef struct udp_hdr
{
    unsigned short source_port; // Source port no.
    unsigned short dest_port; // Dest. port no.
    unsigned short udp_length; // Udp packet length
    unsigned short udp_checksum; // Udp checksum (optional)
} UDP_HDR;
 
 
// TCP header
typedef struct tcp_header
{
    unsigned short source_port; // source port
    unsigned short dest_port; // destination port
    unsigned int sequence; // sequence number - 32 bits
    unsigned int acknowledge; // acknowledgement number - 32 bits
 
    unsigned char ns : 1; //Nonce Sum Flag Added in RFC 3540.
    unsigned char reserved_part1 : 3; //according to rfc
    unsigned char data_offset : 4; /*The number of 32-bit words in the TCP header.
                                   This indicates where the data begins.
                                   The length of the TCP header is always a multiple
                                   of 32 bits.*/
 
    unsigned char fin : 1; //Finish Flag
    unsigned char syn : 1; //Synchronise Flag
    unsigned char rst : 1; //Reset Flag
    unsigned char psh : 1; //Push Flag
    unsigned char ack : 1; //Acknowledgement Flag
    unsigned char urg : 1; //Urgent Flag
 
    unsigned char ecn : 1; //ECN-Echo Flag
    unsigned char cwr : 1; //Congestion Window Reduced Flag
 
    ////////////////////////////////
 
    unsigned short window; // window
    unsigned short checksum; // checksum
    unsigned short urgent_pointer; // urgent pointer
} TCP_HDR;
 
typedef struct icmp_hdr
{
    BYTE type; // ICMP Error type
    BYTE code; // Type sub code
    USHORT checksum;
    USHORT id;
    USHORT seq;
} ICMP_HDR;
 
FILE *logfile;
int tcp = 0, udp = 0, icmp = 0, others = 0, igmp = 0, total = 0, i, j;
struct sockaddr_in source, dest;
char hex[2];
 
//Its free!
IPV4_HDR *iphdr;
TCP_HDR *tcpheader;
UDP_HDR *udpheader;
ICMP_HDR *icmpheader;
 
int main()
{
    SOCKET sniffer;
    struct in_addr addr;
    int in;
 
    char hostname[100];
    struct hostent *local;
    WSADATA wsa;
 
    logfile = fopen("log.txt", "w");
    if (logfile == NULL)
    {
        printf("Unable to create file.");
    }
 
    //Initialise Winsock
    printf("\nInitialising Winsock... \nProgramm by Yury and Oleg\n");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("WSAStartup() failed.\n");
        return 1;
    }
    printf("Initialised");
 
    //Create a RAW Socket
    printf("\nCreating RAW Socket...");
    sniffer = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
    if (sniffer == INVALID_SOCKET)
    {
        printf("Failed to create raw socket.\n");
        return 1;
    }
    printf("Created.");
 
    //Retrive the local hostname
    if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR)
    {
        printf("Error : %d", WSAGetLastError());
        return 1;
    }
    printf("\nHost name : %s \n", hostname);
 
    //Retrive the available IPs of the local host
    local = gethostbyname(hostname);
    printf("\nAvailable Network Interfaces : \n");
    if (local == NULL)
    {
        printf("Error : %d.\n", WSAGetLastError());
        return 1;
    }
 
    for (i = 0; local->h_addr_list[i] != 0; ++i)
    {
        memcpy(&addr, local->h_addr_list[i], sizeof(struct in_addr));
        printf("Interface Number : %d Address : %s\n", i, inet_ntoa(addr));
    }
 
    printf("Enter the interface number you would like to sniff : ");
    scanf("%d", &in);
 
    memset(&dest, 0, sizeof(dest));
    memcpy(&dest.sin_addr.s_addr, local->h_addr_list[in], sizeof(dest.sin_addr.s_addr));
    dest.sin_family = AF_INET;
    dest.sin_port = 0;
 
    printf("\nBinding socket to local system and port 0 ...");
    if (bind(sniffer, (struct sockaddr *)&dest, sizeof(dest)) == SOCKET_ERROR)
    {
        printf("bind(%s) failed.\n", inet_ntoa(addr));
        return 1;
    }
    printf("Binding successful");
 
    //Enable this socket with the power to sniff : SIO_RCVALL is the key Receive ALL ;)
 
    j = 1;
    printf("\nSetting socket to sniff...");
    if (WSAIoctl(sniffer, SIO_RCVALL, &j, sizeof(j), 0, 0, (LPDWORD)&in, 0, 0) == SOCKET_ERROR)
    {
        printf("WSAIoctl() failed.\n");
        return 1;
    }
    printf("Socket set.");
 
    //Begin
    printf("\nStarted Sniffing\n");
    printf("Packet Capture Statistics...\n");
    StartSniffing(sniffer); //Happy Sniffing
 
    //End
    closesocket(sniffer);
    WSACleanup();
 
    return 0;
}
 
void StartSniffing(SOCKET sniffer)
{
    char *Buffer = (char *)malloc(65536); //Its Big!
    int mangobyte;
 
    if (Buffer == NULL)
    {
        printf("malloc() failed.\n");
        return;
    }
 
    do
    {
        mangobyte = recvfrom(sniffer, Buffer, 65536, 0, 0, 0); //Eat as much as u can
 
        if (mangobyte > 0)
        {
            ProcessPacket(Buffer, mangobyte);
        }
        else
        {
            printf("recvfrom() failed.\n");
        }
    } while (mangobyte > 0);
 
    free(Buffer);
}
 
void ProcessPacket(char* Buffer, int Size)
{
    iphdr = (IPV4_HDR *)Buffer;
    ++total;
 
    switch (iphdr->ip_protocol) //Check the Protocol and do accordingly...
    {
    case 1: //ICMP Protocol
        ++icmp;
        PrintIcmpPacket(Buffer, Size);
        break;
 
    case 2: //IGMP Protocol
        ++igmp;
        break;
 
    case 6: //TCP Protocol
        ++tcp;
        PrintTcpPacket(Buffer, Size);
        break;
 
    case 17: //UDP Protocol
        ++udp;
        PrintUdpPacket(Buffer, Size);
        break;
 
    default: //Some Other Protocol like ARP etc.
        ++others;
        break;
    }
    printf("TCP : %d UDP : %d ICMP : %d IGMP : %d  Others : %d Total : %d\r", tcp, udp, icmp, igmp, others, total);
}
 
void PrintIpHeader(char* Buffer)
{
    unsigned short iphdrlen;
 
    iphdr = (IPV4_HDR *)Buffer;
    iphdrlen = iphdr->ip_header_len * 4;
 
    memset(&source, 0, sizeof(source));
    source.sin_addr.s_addr = iphdr->ip_srcaddr;
 
    memset(&dest, 0, sizeof(dest));
    dest.sin_addr.s_addr = iphdr->ip_destaddr;
 
    fprintf(logfile, "\n");
    fprintf(logfile, "IP Header\n");
    fprintf(logfile, " |-IP Version : %d\n", (unsigned int)iphdr->ip_version);
    fprintf(logfile, " |-IP Header Length : %d DWORDS or %d Bytes\n", (unsigned int)iphdr->ip_header_len, ((unsigned int)(iphdr->ip_header_len)) * 4);
    fprintf(logfile, " |-Type Of Service : %d\n", (unsigned int)iphdr->ip_tos);
    fprintf(logfile, " |-IP Total Length : %d Bytes(Size of Packet)\n", ntohs(iphdr->ip_total_length));
    fprintf(logfile, " |-Identification : %d\n", ntohs(iphdr->ip_id));
    fprintf(logfile, " |-Reserved ZERO Field : %d\n", (unsigned int)iphdr->ip_reserved_zero);
    fprintf(logfile, " |-Dont Fragment Field : %d\n", (unsigned int)iphdr->ip_dont_fragment);
    fprintf(logfile, " |-More Fragment Field : %d\n", (unsigned int)iphdr->ip_more_fragment);
    fprintf(logfile, " |-TTL : %d\n", (unsigned int)iphdr->ip_ttl);
    fprintf(logfile, " |-Protocol : %d\n", (unsigned int)iphdr->ip_protocol);
    fprintf(logfile, " |-Checksum : %d\n", ntohs(iphdr->ip_checksum));
    fprintf(logfile, " |-Source IP : %s\n", inet_ntoa(source.sin_addr));
    fprintf(logfile, " |-Destination IP : %s\n", inet_ntoa(dest.sin_addr));
}
 
void PrintTcpPacket(char* Buffer, int Size)
{
    unsigned short iphdrlen;
 
    iphdr = (IPV4_HDR *)Buffer;
    iphdrlen = iphdr->ip_header_len * 4;
 
    tcpheader = (TCP_HDR*)(Buffer + iphdrlen);
 
    fprintf(logfile, "\n\n***********************TCP Packet*************************\n");
 
    PrintIpHeader(Buffer);
 
    fprintf(logfile, "\n");
    fprintf(logfile, "TCP Header\n");
    fprintf(logfile, " |-Source Port : %u\n", ntohs(tcpheader->source_port));
    fprintf(logfile, " |-Destination Port : %u\n", ntohs(tcpheader->dest_port));
    fprintf(logfile, " |-Sequence Number : %u\n", ntohl(tcpheader->sequence));
    fprintf(logfile, " |-Acknowledge Number : %u\n", ntohl(tcpheader->acknowledge));
    fprintf(logfile, " |-Header Length : %d DWORDS or %d BYTES\n"
        , (unsigned int)tcpheader->data_offset, (unsigned int)tcpheader->data_offset * 4);
    fprintf(logfile, " |-CWR Flag : %d\n", (unsigned int)tcpheader->cwr);
    fprintf(logfile, " |-ECN Flag : %d\n", (unsigned int)tcpheader->ecn);
    fprintf(logfile, " |-Urgent Flag : %d\n", (unsigned int)tcpheader->urg);
    fprintf(logfile, " |-Acknowledgement Flag : %d\n", (unsigned int)tcpheader->ack);
    fprintf(logfile, " |-Push Flag : %d\n", (unsigned int)tcpheader->psh);
    fprintf(logfile, " |-Reset Flag : %d\n", (unsigned int)tcpheader->rst);
    fprintf(logfile, " |-Synchronise Flag : %d\n", (unsigned int)tcpheader->syn);
    fprintf(logfile, " |-Finish Flag : %d\n", (unsigned int)tcpheader->fin);
    fprintf(logfile, " |-Window : %d\n", ntohs(tcpheader->window));
    fprintf(logfile, " |-Checksum : %d\n", ntohs(tcpheader->checksum));
    fprintf(logfile, " |-Urgent Pointer : %d\n", tcpheader->urgent_pointer);
    fprintf(logfile, "\n");
    fprintf(logfile, " DATA Dump ");
    fprintf(logfile, "\n");
 
    fprintf(logfile, "IP Header\n");
    PrintData(Buffer, iphdrlen);
 
    fprintf(logfile, "TCP Header\n");
    PrintData(Buffer + iphdrlen, tcpheader->data_offset * 4);
 
    fprintf(logfile, "Data Payload\n");
    PrintData(Buffer + iphdrlen + tcpheader->data_offset * 4
        , (Size - tcpheader->data_offset * 4 - iphdr->ip_header_len * 4));
 
    fprintf(logfile, "\n###########################################################");
}
 
void PrintUdpPacket(char *Buffer, int Size)
{
    unsigned short iphdrlen;
 
    iphdr = (IPV4_HDR *)Buffer;
    iphdrlen = iphdr->ip_header_len * 4;
 
    udpheader = (UDP_HDR *)(Buffer + iphdrlen);
 
    fprintf(logfile, "\n\n***********************UDP Packet*************************\n");
 
    PrintIpHeader(Buffer);
 
    fprintf(logfile, "\nUDP Header\n");
    fprintf(logfile, " |-Source Port : %d\n", ntohs(udpheader->source_port));
    fprintf(logfile, " |-Destination Port : %d\n", ntohs(udpheader->dest_port));
    fprintf(logfile, " |-UDP Length : %d\n", ntohs(udpheader->udp_length));
    fprintf(logfile, " |-UDP Checksum : %d\n", ntohs(udpheader->udp_checksum));
 
    fprintf(logfile, "\n");
    fprintf(logfile, "IP Header\n");
 
    PrintData(Buffer, iphdrlen);
 
    fprintf(logfile, "UDP Header\n");
 
    PrintData(Buffer + iphdrlen, sizeof(UDP_HDR));
 
    fprintf(logfile, "Data Payload\n");
 
    PrintData(Buffer + iphdrlen + sizeof(UDP_HDR), (Size - sizeof(UDP_HDR) - iphdr->ip_header_len * 4));
 
    fprintf(logfile, "\n###########################################################");
}
 
 
void PrintIcmpPacket(char* Buffer, int Size)
{
    unsigned short iphdrlen;
 
    iphdr = (IPV4_HDR *)Buffer;
    iphdrlen = iphdr->ip_header_len * 4;
 
    icmpheader = (ICMP_HDR*)(Buffer + iphdrlen);
 
    fprintf(logfile, "\n\n***********************ICMP Packet*************************\n");
    PrintIpHeader(Buffer);
 
    fprintf(logfile, "\n");
 
    fprintf(logfile, "ICMP Header\n");
    fprintf(logfile, " |-Type : %d", (unsigned int)(icmpheader->type));
 
    if ((unsigned int)(icmpheader->type) == 11)
    {
        fprintf(logfile, " (TTL Expired)\n");
    }
    else if ((unsigned int)(icmpheader->type) == 0)
    {
        fprintf(logfile, " (ICMP Echo Reply)\n");
    }
 
    fprintf(logfile, " |-Code : %d\n", (unsigned int)(icmpheader->code));
    fprintf(logfile, " |-Checksum : %d\n", ntohs(icmpheader->checksum));
    fprintf(logfile, " |-ID : %d\n", ntohs(icmpheader->id));
    fprintf(logfile, " |-Sequence : %d\n", ntohs(icmpheader->seq));
    fprintf(logfile, "\n");
 
    fprintf(logfile, "IP Header\n");
    PrintData(Buffer, iphdrlen);
 
    fprintf(logfile, "UDP Header\n");
    PrintData(Buffer + iphdrlen, sizeof(ICMP_HDR));
 
    fprintf(logfile, "Data Payload\n");
    PrintData(Buffer + iphdrlen + sizeof(ICMP_HDR), (Size - sizeof(ICMP_HDR)-iphdr->ip_header_len * 4));
 
    fprintf(logfile, "\n###########################################################");
}
 
/*
Print the hex values of the data
*/
void PrintData(char* data, int Size)
{
    char a, line[17], c;
    int j;
 
    //loop over each character and print
    for (i = 0; i < Size; i++)
    {
        c = data[i];
 
        //Print the hex value for every character , with a space. Important to make unsigned
        fprintf(logfile, " %.2x", (unsigned char)c);
 
        //Add the character to data line. Important to make unsigned
        a = (c >= 32 && c <= 128) ? (unsigned char)c : '.';
 
        line[i % 16] = a;
 
        //if last character of a line , then print the line - 16 characters in 1 line
        if ((i != 0 && (i + 1) % 16 == 0) || i == Size - 1)
        {
            line[i % 16 + 1] = '\0';
 
            //print a big gap of 10 characters between hex and characters
            fprintf(logfile, "          ");
 
            //Print additional spaces for last lines which might be less than 16 characters in length
            for (j = strlen(line); j < 16; j++)
            {
                fprintf(logfile, "   ");
            }
 
            fprintf(logfile, "%s \n", line);
        }
    }
 
    fprintf(logfile, "\n");
}

Собственно проблема следующая: Как мне поймать и записать ARP пакет? TCP, UDP вычисляются из заголовка, а как быть с ARP? Как в принципе работать с канальным уровнем? Готов проставиться на пиво за хорошую помощь
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
04.12.2015, 00:02
Ответы с готовыми решениями:

ARP пакет [CPT]
Пишу курсач по сетям и с каждым разом стресса все больше и больше, а дедлайн уже скоро. В общем, суть проблемы - есть 2 локальные сети,...

Непонятный ARP-пакет от ip-камеры
Всем привет! Начал разбираться с Wireshark, поснифил рабочую сеть и увидел непонятный мне пакет от одной из ip-камер: Interface...

Как определить, какой из подсетей принадлежит пакет IP-пакет?
То есть у Олиферов это всё подробно расписано. Если маршрутизация сделана на основе масок, то надо пробежаться по таблице маршрутизации и...

3
654 / 575 / 164
Регистрация: 13.12.2012
Сообщений: 2,124
04.12.2015, 11:21
попробуйте в сторону libpcap посмотреть)

Добавлено через 3 минуты
Люди говорят что
C++
1
socket(AF_INET, SOCK_RAW, ETH_P_ALL);
работает

Не по теме:

или

C++
1
socket(AF_INET, SOCK_RAW, htons(ETH_P_ALL));

1
1 / 1 / 0
Регистрация: 22.03.2011
Сообщений: 56
05.12.2015, 11:19  [ТС]
Либо я глупенький и не умею гуглить либо еще что, но WinSock наотрез отказывается принимать этот аргумент.(Код то от софтины для линкуса.)
C++
1
ETH_P_ALL
Прошла инфа, что в WinSock нет возможности слушать ETH фреймы.
Хелп плиз, все сроки горят.

Добавлено через 3 часа 47 минут
Последовал вашему совету, взял исходники отсюда - в надежде переделать их под себя, но конечно же облажался. Получаю следующий эррор.
Code
1
2
Серьезность  Код  Описание    Проект    Файл    Строка
Ошибка    C2664   "int pcap_next_ex(pcap_t *,pcap_pkthdr **,const u_char **)": невозможно преобразовать аргумент 3 из "u_char **" в "const u_char **"   MyShittySniffer     176
MS VS Community 2015.

C++
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
// MyShittySniffer.cpp: определяет точку входа для консольного приложения.
//
 
#include "stdafx.h"
#include "pcap.h"
#include <iostream>
 
using namespace std;
 
#pragma comment(lib , "ws2_32.lib") //For winsock
#pragma comment(lib , "wpcap.lib") //For winpcap
 
//some packet processing functions
void ProcessPacket(u_char*, int); //This will decide how to digest
 
void print_ethernet_header(u_char*);
void PrintIpHeader(u_char*, int);
void PrintIcmpPacket(u_char*, int);
void print_udp_packet(u_char*, int);
void PrintTcpPacket(u_char*, int);
void PrintData(u_char*, int);
 
// Set the packing to a 1 byte boundary
//#include "pshpack1.h"
//Ethernet Header
typedef struct ethernet_header
{
    UCHAR dest[6];
    UCHAR source[6];
    USHORT type;
}   ETHER_HDR, *PETHER_HDR, FAR * LPETHER_HDR, ETHERHeader;
 
//Ip header (v4)
typedef struct ip_hdr
{
    unsigned char ip_header_len : 4; // 4-bit header length (in 32-bit words) normally=5 (Means 20 Bytes may be 24 also)
    unsigned char ip_version : 4; // 4-bit IPv4 version
    unsigned char ip_tos; // IP type of service
    unsigned short ip_total_length; // Total length
    unsigned short ip_id; // Unique identifier
 
    unsigned char ip_frag_offset : 5; // Fragment offset field
 
    unsigned char ip_more_fragment : 1;
    unsigned char ip_dont_fragment : 1;
    unsigned char ip_reserved_zero : 1;
 
    unsigned char ip_frag_offset1; //fragment offset
 
    unsigned char ip_ttl; // Time to live
    unsigned char ip_protocol; // Protocol(TCP,UDP etc)
    unsigned short ip_checksum; // IP checksum
    unsigned int ip_srcaddr; // Source address
    unsigned int ip_destaddr; // Source address
} IPV4_HDR;
 
//UDP header
typedef struct udp_hdr
{
    unsigned short source_port; // Source port no.
    unsigned short dest_port; // Dest. port no.
    unsigned short udp_length; // Udp packet length
    unsigned short udp_checksum; // Udp checksum (optional)
} UDP_HDR;
 
// TCP header
typedef struct tcp_header
{
    unsigned short source_port; // source port
    unsigned short dest_port; // destination port
    unsigned int sequence; // sequence number - 32 bits
    unsigned int acknowledge; // acknowledgement number - 32 bits
 
    unsigned char ns : 1; //Nonce Sum Flag Added in RFC 3540.
    unsigned char reserved_part1 : 3; //according to rfc
    unsigned char data_offset : 4; /*The number of 32-bit words in the TCP header.
                                   This indicates where the data begins.
                                   The length of the TCP header is always a multiple
                                   of 32 bits.*/
 
    unsigned char fin : 1; //Finish Flag
    unsigned char syn : 1; //Synchronise Flag
    unsigned char rst : 1; //Reset Flag
    unsigned char psh : 1; //Push Flag
    unsigned char ack : 1; //Acknowledgement Flag
    unsigned char urg : 1; //Urgent Flag
 
    unsigned char ecn : 1; //ECN-Echo Flag
    unsigned char cwr : 1; //Congestion Window Reduced Flag
 
                           ////////////////////////////////
 
    unsigned short window; // window
    unsigned short checksum; // checksum
    unsigned short urgent_pointer; // urgent pointer
} TCP_HDR;
 
typedef struct icmp_hdr
{
    BYTE type; // ICMP Error type
    BYTE code; // Type sub code
    USHORT checksum;
    USHORT id;
    USHORT seq;
} ICMP_HDR;
// Restore the byte boundary back to the previous value
//#include <poppack.h>
 
FILE *logfile;
int tcp = 0, udp = 0, icmp = 0, others = 0, igmp = 0, total = 0, i, j;
struct sockaddr_in source, dest;
char hex[2];
 
//Its free!
ETHER_HDR *ethhdr;
IPV4_HDR *iphdr;
TCP_HDR *tcpheader;
UDP_HDR *udpheader;
ICMP_HDR *icmpheader;
u_char *data;
 
int main()
{
    u_int i, res, inum;
    char errbuf[PCAP_ERRBUF_SIZE], buffer[100];
    u_char *pkt_data;
    time_t seconds;
    pcap_if_t *devlist;
 
    struct tm tbreak;
    pcap_if_t *alldevs, *d;
    pcap_t *fp;
    struct pcap_pkthdr *header;
 
    fopen_s(&logfile, "log.txt", "w");
 
    if (logfile == NULL)
    {
        printf("Unable to create file.");
    }
 
    i = 0;
    if (pcap_findalldevs(&devlist, errbuf) == -1)
    {
        cout << "game over";
    }
    cout << "Device list:"<<endl;
    for (d = devlist; d; d = d->next)
    {
        cout << ++i <<".  "<< d << " " << d->description <<endl;
    }
 
    if (i == 0)
    {
        fprintf(stderr, "No interfaces found! Exiting.\n");
        return -1;
    }
 
    printf("Enter the interface number you would like to sniff : ");
    scanf_s("%d", &inum);
 
    for (d = devlist, i = 0; i< inum - 1; d = d->next, i++);
    /* Open the device */
    if ((fp = pcap_open(d->name,
        100 /*snaplen*/,
        PCAP_OPENFLAG_PROMISCUOUS /*flags*/,
        20 /*read timeout*/,
        NULL /* remote authentication */,
        errbuf)
        ) == NULL)
    {
        fprintf(stderr, "\nError opening adapter\n");
        return -1;
    }
 
    while ((res = pcap_next_ex(fp, &header, &pkt_data)) >= 0)
    {
        if (res == 0)
        {
            // Timeout elapsed
            continue;
        }
        seconds = header->ts.tv_sec;
        localtime_s(&tbreak, &seconds);
        strftime(buffer, 80, "%d-%b-%Y %I:%M:%S %p", &tbreak);
        //print pkt timestamp and pkt len
        //fprintf(logfile , "\nNext Packet : %ld:%ld (Packet Length : %ld bytes) " , header->ts.tv_sec, header->ts.tv_usec, header->len);
        fprintf(logfile, "\nNext Packet : %s.%ld (Packet Length : %ld bytes) ", buffer, header->ts.tv_usec, header->len);
        ProcessPacket(pkt_data, header->caplen);
    }
 
    if (res == -1)
    {
        fprintf(stderr, "Error reading the packets: %s\n", pcap_geterr(fp));
        return -1;
    }
 
 
    system("PAUSE");
    return 0;
}
0
654 / 575 / 164
Регистрация: 13.12.2012
Сообщений: 2,124
06.12.2015, 21:21
ну тогда libpcap там можно полномтью сформировать пакет
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
06.12.2015, 21:21
Помогаю со студенческими работами здесь

Определить MAC адрес при ARP запросе
Всем привет. Прилагаю скриншот вопроса. Заранее спасибо за помощь!

Почему если отправить пакет UDP и конечного адресата в сети не существует, то пакет не отправляется?
Добрый день! Вопрос для расширения кругозора. Мониторю свой трафик с помощью WireShark и заметил такую вещь: при отправке пакета по...

Определить какой пакет тяжелее
Составить программу с комментариями: Рис расфасован в два пакета.Вес первого m кг, второго-n кг. Определить какой пакет...

Определить какой пакет тяжелее
Рис расфасован в два пакета. Масса первого - m кг, второго – n кг. Составить программу, определяющую: а) какой пакет тяжелее - первый...

Определить по каким зависимостям установлен пакет
Как узнать у каких пакетов в зависимостях находится пакет?


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru