分享

C++中实现ping功能2

 禁忌石 2017-05-16

二、使用socket协议实现

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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
// MyPing.cpp : Defines the entry point for the console application.
  
//
#include "stdafx.h"
  
#include <winsock2.h>
  
#include <WS2tcpip.h>
  
#include <stdio.h>
  
#include <stdlib.h>
  
  
#define ICMP_ECHO 8
  
#define ICMP_ECHOREPLY 0
  
#define ICMP_MIN 8 //Minimum 8-byte ICMP packet (header)
  
   
  
#define DEF_PACKET_SIZE 32
  
#define MAX_PACKET 1024
  
#define MAX_IP_HDR_SIZE 60
  
   
  
//IP header structure
  
typedef struct _iphdr
  
{
  
    unsigned int h_len:4;//Length of the header
  
    unsigned int version:4;//Version of IP
  
    unsigned char tos;//Type of service
  
    unsigned short total_len;//Total length of the packet
  
    unsigned short ident;//Unique identifier
  
    unsigned short frag_and_flags;//Flags
  
    unsigned char ttl;//Time to live
  
    unsigned char proto;//Protocol (TCP,UDP,etc.)
  
    unsigned short checksum;//IP checksum
  
   
  
    unsigned int sourceIP;
  
    unsigned int destIP;
  
} IpHeader;
  
   
  
//ICMP header structure
  
typedef struct _icmphdr
  
{
  
    BYTE i_type;
  
    BYTE i_code;//Type sub code
  
    USHORT i_cksum;
  
    USHORT i_id;
  
    USHORT i_seq;
  
   
  
    //This is not the standard header, but we reserve space for time
  
    ULONG timestamp;
  
} IcmpHeader;
  
   
  
//IP option header--use with socket option IP_OPTIONS
  
typedef struct _ipoptionhdr
  
{
  
    unsigned char code;//Option type
  
    unsigned char len;//Length of option hdr
  
    unsigned char ptr;//Offset into optons
  
    unsigned long addr[9];//List of IP addrs
  
} IpOptionHeader;
  
   
  
int datasize;
  
char* lpdest;
  
   
  
//Print usage information
  
void usage()
  
{
  
    printf("usage:MyPing -i:IP [data size]\n");
  
    printf("    -i:IP           remote machine to Ping\n");
  
    printf("    datasize     can be up to 1 KB\n");
  
   
  
    ExitProcess(1);
  
}
  
   
  
//Helper function to fill in various fields for our ICMP request
  
void FillICMPData(char* icmp_data, int datasize)
  
{
  
    IcmpHeader* icmp_hdr = (IcmpHeader*)icmp_data;
  
    icmp_hdr->i_type = ICMP_ECHO;//Request an ICMP echo
  
    icmp_hdr->i_code = 0;
  
    icmp_hdr->i_id = (USHORT)GetCurrentProcessId();
  
    icmp_hdr->i_cksum = 0;
  
    icmp_hdr->i_seq = 0;
  
   
  
    char* datapart = icmp_data + sizeof(IcmpHeader);
  
   
  
    //Place some junk in the buffer
  
    memset(datapart, 'E', datasize - sizeof(IcmpHeader));
  
}
  
   
  
//This function calculates the 16-bit one's complement sum
  
//of the supplied buffer (ICMP) header
  
USHORT checksum(USHORT* buffer, int size)
  
{
  
    unsigned long cksum = 0;
  
   
  
    while (size > 1)
  
    {
  
        cksum += *buffer++;
  
        size -= sizeof(USHORT);
  
    }
  
   
  
    if (size)
  
    {
  
        cksum += *(UCHAR*)buffer;
  
    }
  
   
  
    cksum = (cksum>>16) + (cksum & 0xffff);
  
    cksum += (cksum>>16);
  
   
  
    return (USHORT)(~cksum);
  
}
  
   
  
//If the IP option header is present, find the IP options
  
//within the IP header and print the record route option values
  
void DecodeIPOptions(char* buf, int bytes)
  
{
  
    IpOptionHeader* ipopt = (IpOptionHeader*)(buf + 20);
  
   
  
    printf("RR:    ");
  
    for (int i = 0; i < (ipopt->ptr / 4) - 1; i++)
  
    {
  
        IN_ADDR inaddr;
  
        inaddr.S_un.S_addr = ipopt->addr[i];
  
   
  
        if (i != 0)
  
        {
  
            printf("        ");
  
        }
  
   
  
        HOSTENT* host = gethostbyaddr((char*)&inaddr.S_un.S_addr,
  
            sizeof(inaddr.S_un.S_addr), AF_INET);
  
        if (host)
  
        {
  
            printf("(%-15s) %s\n", inet_ntoa(inaddr), host->h_name);
  
        }
  
        else
  
        {
  
            printf("(%-15s)\n", inet_ntoa(inaddr));
  
        }
  
    }
  
   
  
    return;
  
}
  
   
  
//The response is an IP packet. We must decode the IP header to
  
//locate the ICMP data.
  
void DecodeICMPHeader(char* buf, int bytes, struct sockaddr_in* from)
  
{
  
    static int icmpcount = 0;
  
    IpHeader* iphdr = (IpHeader*)buf;
  
   
  
    //Number of 32-bit words * 4 = bytes
  
    unsigned short iphdrlen = iphdr->h_len * 4;
  
    DWORD tick = GetTickCount();
  
   
  
    if ((iphdrlen == MAX_IP_HDR_SIZE) && (!icmpcount))
  
    {
  
        DecodeIPOptions(buf, bytes);
  
    }
  
   
  
    if (bytes < iphdrlen + ICMP_MIN)
  
    {
  
        printf("Too few bytes from %s\n", inet_ntoa(from->sin_addr));
  
    }
  
   
  
    IcmpHeader* icmphdr = (IcmpHeader*)(buf + iphdrlen);
  
    if (icmphdr->i_type != ICMP_ECHOREPLY)
  
    {
  
        printf("nonecho type %d recvd\n", icmphdr->i_type);
  
        return;
  
    }
  
   
  
    //Make sure this is an ICMP reply to something we sent!
  
    if (icmphdr->i_id != (USHORT)GetCurrentProcessId())
  
    {
  
        printf("someone else's packet!\n");
  
        return;
  
    }
  
   
  
    printf("%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
  
    printf("  icmp_seq = %d. ", icmphdr->i_seq);
  
    printf("  time:%d ms", tick - icmphdr->timestamp);
  
    printf("\n");
  
   
  
    icmpcount++;
  
    return;
  
}
  
   
  
void ValidateArgs(int argc, _TCHAR** argv)
  
{
  
    lpdest = NULL;
  
    datasize = DEF_PACKET_SIZE;
  
   
  
    for (int i = 1; i < argc; i++)
  
    {
  
        if ((argv[i][0] == '-') || (argv[i][0] == '/'))
  
        {
  
            switch (tolower(argv[i][1]))
  
            {
  
            case 'i':
  
                lpdest = argv[i] + 3;
  
                break;
  
            default:
  
                usage();
  
                break;
  
            }
  
        }
  
        else if (isdigit(argv[i][0]))
  
        {
  
            datasize = atoi(argv[i]);
  
        }
  
    }
  
}
  
   
  
int _tmain(int argc, _TCHAR* argv[])
  
{
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
  
    {
        printf("WSAStartup() failed:%d\n", GetLastError());
        return -1;
    }
  
  
    ValidateArgs(argc, argv);
  
   
  
    SOCKET sockRaw = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP,
  
        NULL, 0, WSA_FLAG_OVERLAPPED);
  
    if (sockRaw == INVALID_SOCKET)
  
    {
  
        printf("WSASocket() failed:%d\n", WSAGetLastError());
  
        return -1;
  
    }
  
   
  
    //Set the send/recv timeout values
  
    struct sockaddr_in from;
    int fromlen = sizeof(from);
    int timeout = 1000;
  
 
    int bread = setsockopt(sockRaw, SOL_SOCKET, SO_RCVTIMEO,
  
        (char*)&timeout, sizeof(timeout));
  
    if (bread == SOCKET_ERROR)
  
    {
  
        printf("setsockopt(SO_RCVTIMEO) failed:%d\n", WSAGetLastError());
  
        return -1;
  
    }
  
    timeout = 1000;
 
    bread = setsockopt(sockRaw, SOL_SOCKET, SO_SNDTIMEO,(char*)&timeout, sizeof(timeout));
    if (bread == SOCKET_ERROR)
    {
        printf("setsockopt(SO_SNDTIMEO) failed:%d\n", WSAGetLastError());
        return -1;
  
    }
 
    struct sockaddr_in dest;
    memset(&dest, 0, sizeof(dest));
  
    //Resolve the endpoint's name if necessary
    dest.sin_family = AF_INET;
  
   
  
    if ((lpdest != NULL) && strlen(lpdest) != 0)
    {
        dest.sin_addr.s_addr = inet_addr(lpdest);
    }
  
    else
  
    {
        struct hostent* hp = gethostbyname(lpdest);
        if (hp != NULL)
  
        {
            memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);
            dest.sin_family = hp->h_addrtype;
            printf("dest.sin_addr = %s\n", inet_ntoa(dest.sin_addr));
  
        }
  
        else
  
        {
            printf("gethostbyname() failed:%d\n", WSAGetLastError());
            return -1;
        }
  
    }
  
  
    //Create the ICMP packet
  
    datasize += sizeof(IcmpHeader);
  
   
  
    char* icmp_data = (char*)HeapAlloc(GetProcessHeap(),
  
        HEAP_ZERO_MEMORY, MAX_PACKET);
  
    if (!icmp_data)
  
    {
  
        printf("HeapAlloc() failed:%d\n", GetLastError());
  
        return -1;
  
    }
  
    memset(icmp_data, 0, MAX_PACKET);
    FillICMPData(icmp_data, datasize);
    char* recvbuf = (char*)HeapAlloc(GetProcessHeap(),   HEAP_ZERO_MEMORY, MAX_PACKET);
  
   
  
    //Start sending/receiving ICMP packets
  
    USHORT seq_no = 0;
  
    while (true)
    {
        static int nCount = 0;
        int bwrote;
  
        if (nCount++ == 4)
        {
            break;
        }
  
  
        ((IcmpHeader*)icmp_data)->i_cksum = 0;
        ((IcmpHeader*)icmp_data)->timestamp = GetTickCount();
        ((IcmpHeader*)icmp_data)->i_seq = seq_no++;
        ((IcmpHeader*)icmp_data)->i_cksum = checksum((USHORT*)icmp_data, datasize);
  
  
        bwrote = sendto(sockRaw, icmp_data, datasize, 0,(struct sockaddr*)&dest, sizeof(dest));
        if (bwrote == SOCKET_ERROR)
  
        {
            if (WSAGetLastError() == WSAETIMEDOUT)
            {
                printf("timed out\n");
                continue;
            }
  
            printf("sendto() failed:%d\n", WSAGetLastError());
            return -1;
        }
  
        if (bwrote < datasize)
        {
            printf("Wrote %d bytes\n", bwrote);
        }
  
        bread = recvfrom(sockRaw, recvbuf, MAX_PACKET, 0,
            (struct sockaddr*)&from, &fromlen);
        if (bread == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAETIMEDOUT)
  
            {
                printf("timed out\n");
  
                continue;
  
            }
  
            printf("revefrom() failed:%d\n", WSAGetLastError());
            return -1;
        }
  
  
        DecodeICMPHeader(recvbuf, bread, &from);
  
        Sleep(1000);
  
    }
  
  
    //Cleanup
  
    if (sockRaw != INVALID_SOCKET)
    {
        closesocket(sockRaw);
    }
  
    HeapFree(GetProcessHeap(), 0, recvbuf);
    HeapFree(GetProcessHeap(), 0, icmp_data);
    WSACleanup();
  
    return 0;
  
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多