-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing3.html
executable file
·875 lines (762 loc) · 39 KB
/
listing3.html
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>SimplePing - /SimplePing.c</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html">Reference Library</a> > <a href="../../samplecode/index.html">Sample Code</a> > <a href="../../samplecode/Networking/index.html">Networking</a> > <a href="../../samplecode/Networking/idxDarwin-date.html">Darwin</a> > <A HREF="javascript:location.replace('index.html');">SimplePing</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">SimplePing</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/SimplePing.c</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/main.c</option>
<option value="listing2.html">/Readme.txt</option>
<option value="listing3.html">/SimplePing.c</option>
<option value="listing4.html">/SimplePing.h</option></select>
</p>
</form>
<p><strong><a href="SimplePing.zip">Download Sample</a></strong> (“SimplePing.zip”, 18.0K)<BR>
<strong><a href="SimplePing.dmg">Download Sample</a></strong> (“SimplePing.dmg”, 66.5K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox">/*
File: SimplePing.c
Description: This file provides a simple API to ping a remote host.
Author: Chad Jones
Copyright: Copyright 2003 Apple Computer, Inc. All rights reserved.
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under Apple’s
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Change History (most recent first):
10/3/03 Chad Jones Added comment indicating sample requires build tools
ProjectBuilder 2.1 or later
*/
/*
* P I N G . C
*
* Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
* measure round-trip-delays and packet loss across network paths.
*
* Author -
* Mike Muuss
* U. S. Army Ballistic Research Laboratory
* December, 1983
*
* Status -
* Public Domain. Distribution Unlimited.
* Bugs -
* More statistics could always be gathered.
*/
//Note this sample requires Mac OS X 10.2.x or later and
//ProjectBuilder version 2.1 or later.
#include "SimplePing.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/ip_var.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <errno.h>
/*****************************************************
* SimplePing
*****************************************************
* Purpose: This function uses the above functions to ping a given remote host with
* a given number of packets and with a given timeout to wait for responses on each packet.
* Note this function does not require root permissions since on MacOSX 10.2.x pings are
* possible using non-privileged datagram sockets.
*
* Parameters:
* HostToPing A C-String describing the remote host. On calling
* SimplePing this variable will hold a description of the host as a C-String. The string
* can either be a hostname (e.g. www.google.com) or an IP address (e.g. 17.203.23.111)
*
* NumberOfPacketsToSend An integer. On calling SimplePing this variable holds
* the number of ping packets to send to the host before stopping.
*
* PingTimeoutInSeconds An integer. On calling Simple Ping this variable holds
* the amount of time SimplePing will wait for responses from the ping before going onto the next packet.
*
* ReturnimmediatelyAfterReply An integer. On calling Simple Ping if this variable is zero then
* we will wait for the timeout to occur even if we get the appropriate ping reply (waiting for any other packets).
* If this variable is non-zero then simple ping will return immediately after getting the appropriate ping reply to
* the request.
*
* *Function Result* A UNIX error integer return value as described in:
* /usr/include/sys/errno.h on a BSD system.
* Note: This value will be zero on success.
*****************************************************/
int SimplePing(const char* HostToPing, const int NumberOfPacketsToSend, const int PingTimeoutInSeconds, const int ReturnimmediatelyAfterReply)
{
struct sockaddr_in hostAddress;
int packetSequenceNumber;
int socketConnectionToHost;
int gotResponse = 0;
int numberPacketsSent = 0;
int numberPacketsReceived = 0;
if ((HostToPing == NULL) || (NumberOfPacketsToSend < 1) || (PingTimeoutInSeconds < 1))
{
printf("Invalid arguments to SimplePing\n");
return(EINVAL); //invalid arguments error
}
int error = LookupHostAddress(HostToPing, &hostAddress);
if (error != 0)
{
printf("Unable to lookup host address. UNIX Error: %d", error);
return(error);
}
printf("PING %s (%s)\n", HostToPing, inet_ntoa(hostAddress.sin_addr));
fflush(stdout);
error = CreateSocketForCommunicationWithHost(hostAddress, &socketConnectionToHost);
if (error != 0)
{
printf("Unable to create socket. UNIX Error: %d", error);
return(error);
}
packetSequenceNumber = 0;
while ((packetSequenceNumber < NumberOfPacketsToSend) && (error == 0))
{
printf("*Pinging host %s: icmp_seq=%u\n",
inet_ntoa(hostAddress.sin_addr), packetSequenceNumber);
fflush(stdout);
error = CreateAndSendICMPPacket(hostAddress,
packetSequenceNumber, socketConnectionToHost);
if (error == 0) //successfully sent packet
{
numberPacketsSent = numberPacketsSent + 1;
//Here we wait for the return on the packet until we get it or until the timeout fires.
error = WaitAndPrintICMPs(socketConnectionToHost, PingTimeoutInSeconds, ReturnimmediatelyAfterReply, &gotResponse);
if (error == 0) //was able to wait for reply successfully (whether we got a reply or not)
{
if (gotResponse == 1)
{numberPacketsReceived = numberPacketsReceived + 1;}
}
else
{perror("\nError: Error waiting for packet response");}
}
else
{perror("\nError: Unable to ping host");}
packetSequenceNumber = packetSequenceNumber + 1;
}
close(socketConnectionToHost); //closing the socket connection since we are finished with it.
printf("\n--- %s ping statistics ---\n", HostToPing);
printf("%d packets transmitted, %d packets received, %.0f%% packet loss",
numberPacketsSent, numberPacketsReceived,
100*((double)numberPacketsSent -
(double)numberPacketsReceived)/(double)numberPacketsSent);
fflush(stdout);
return(error);
}
/*****************************************************
* LookupHostAddress
*****************************************************
* Purpose: This function provides a mechanism to get a host address
* as a internet address structure given only a string describing the
* remote host. The string passed will be either a host name
* (e.g. www.apple.com) or an IP address (e.g. 17.203.23.111)
*
* Parameters:
* HostToPing A constant C-string. On calling
* LookupHostAddress this variable holds a CString describing the
* remote host. The string can either be a host name (e.g. www.google.com)
* or an IP address (e.g. 17.203.23.112)
*
* HostAddress A pointer to a pre-allocated array of sockaddr_in structure.
* On calling LookupHostAddress this variable must be a pointer to a
* pre-allocated sockaddr_in structure. On successful return from LookupHostAddress
* this variable will hold the host address expressed as an sockaddr_in structure.
* On failed return the value of this variable is undefined
*
* *Function Result* A UNIX error integer return value as described in:
* /usr/include/sys/errno.h on a BSD system.
* Note: This value will be zero on success.
*****************************************************/
int LookupHostAddress(const char* HostToPing, struct sockaddr_in* HostAddress)
{
struct hostent * hostInformation;
//Checking input argument for validity
if ((HostToPing == NULL) || (HostAddress == NULL))
{
return(EINVAL); //invalid argument error return
}
//Initalizing host address
memset(HostAddress, 0, sizeof(struct sockaddr_in));
/* Calling inet_addr to try to interpret the input address as a
* IP string "xx.xx.xx.xx.xx. If this doesn't work then we will
* try gethostbyname which will resolve any domain names (i.e. www.google.com)
* First Argument: The IP address expressed as a character string. Assuming
* the string passed to us is an IP string we try to interpret the string.
* if this doesn't work then we will try gethostbyname.
* Return Value: If properly formed input then what is returned is an internet
* address structure. We will use this to set the internet address structure
* in our socket address. If the request is malformed then the constant
* INADDR_NONE will be returned for the internet address.
*/
HostAddress->sin_addr.s_addr = inet_addr(HostToPing);
//Checking to see if IP address was got correctly from character string.
if (HostAddress->sin_addr.s_addr != INADDR_NONE) //Success no error returned!
{
//Setting socket family to internet (TCP/IP) since know it was IP address interpreted
HostAddress->sin_family = AF_INET;
}
else //failure! now try with gethostbyname
{
/* The inet_addr call failed because the string isn't an IP address. Instead
* we will try to interpret it as a host name (e.g. www.google.com).
* First Argument: The character string we are trying to interpret of as a
* host name.
* Return Value: A host information structure on success which will contain the
* information we need for connecting to the host. On failure a NULL pointer
* will be returned
*/
hostInformation = gethostbyname(HostToPing);
if (hostInformation == NULL) //Failure!
{
//Failure unable to interpret character string as host name.
//We give up here by returning can't find host (unreachable host).
return(EHOSTUNREACH);
}
//Setting the socket family for connecting to the host. We get this information from
//the hostInformation structure directly
HostAddress->sin_family = hostInformation->h_addrtype;
//Now getting the internet address structure from our host information structure.
//We copy the structure into ours using a memmove
memmove(&HostAddress->sin_addr, hostInformation->h_addr, hostInformation->h_length);
}
/* Now for the host we have the address and connection family for the host we can return this
* information
*/
return(0); //return zero indicating success.
}
/*****************************************************
* CreateSocketForCommunicationWithHost
*****************************************************
* Purpose: This function sets up a socket for communicating
* with the given remote host and also sets the parameters of
* that socket to our required specifications (timeout of 1 second
* and larger receive buffer).
*
* Parameters:
* HostAddress A sockaddr_in structure. On calling
* CreateSocketForCommunicationWithHost this variable has an address
* of the host the socket will be established with expressed in sockaddr_in format.
*
* SocketToReturn A pointer to a pre-allocated integer. On successful
* return from CreateSocketForCommunicationWithHost this variable will hold
* a socket descriptor used to communicate with the socket in future calls. On
* failed result this variable will be undefined. Note on successful result its
* the caller's responsibility to close the socket.
*
* *Function Result* A UNIX error integer return value as described in:
* /usr/include/sys/errno.h on a BSD system.
* Note: This value will be zero on success.
*****************************************************/
int CreateSocketForCommunicationWithHost(const struct sockaddr_in HostAddress, int* SocketToReturn)
{
struct protoent* protocolInformation;
const int krecieveSocketBufferSize = 50 * 1024; //here we want 50K for size of receive buffer
struct timeval pingTimeout;
int error = 0;
/* Getting the protocol information we need to create the socket. This socket will use the
* icmp protocol (protocol used for pings). We first need to get the protocol information with
* a getprotobyname call
* First Argument: The name of the protocol we will be using
* Return Value: A pointer to a protocol structure which provides us with the protocol
* information used to create the socket. On failure the pointer will be NULL.
*/
protocolInformation = getprotobyname("icmp");
//Check to see if got protocol information successfully.
if (protocolInformation == NULL)
{
//here the protocol we want isn't supported or isn't found. Need to fail here
return(EPFNOSUPPORT); //return protocol not supported UNIX error
}
/* Now creating the socket which will be used for pinging the remote host. Note
* here we need to create a socket to send the ping. Note previous to MacOSX 10.2
* this required a raw socket which required root permissions. However, now in 10.2.x
* you can simply create a datagram socket and can use that to ping remote hosts.
* First Argument: The communication domain to use. In this case the ARPA internet
* protocol which is used to do pings.
* Second Argument: The type of socket to create. In this case we need a raw socket
* to ping the remote host.
* Third Argument: The particular protocol to use over the socket. Here we use the
* icmp protocol so pass the protocol number from the protocol information found earlier.
* Return Value: On success the created socket will be returned. On failure a value
* less then zero will be returned.
*/
*SocketToReturn = socket(AF_INET, SOCK_DGRAM, protocolInformation->p_proto);
if (*SocketToReturn < 0)
{
//error creating socket give up here. Return operation not permitted error indicating
//we can't create socket.
return(EPERM);
}
/* Now that we have the socket created there is one extra step we would like to do.
* That is increase the receive buffer size. The reason we do this is when we send
* an echo request there can be many replies. This means that a regular sized buffer
* might get overwhelmed. Thus we increase the receive buffer size to 50K which
* should be large enough to hold the ICMP replies.
* First Argument: The socket we are editing the receive buffer size on. In this case
* the socket we just created.
* Second Argument: UNIX constant SOL_SOCKET indicating we are editing a socket level
* attribute (see man page for setsockopt for more details).
* Third Argument: UNIX constant SO_RCVBUF indicating we are editing a receive buffer on
* the socket (see man page for setsockopt for more details).
* Forth Argument: The new size of the buffer we desire. In this case the arbitrarily
* chosen 50K buffer.
* Fifth Argument: The size of the forth argument (i.e. sizeof())
* Return Value: There is actually a return value of zero on success and -1 on failure.
* However, whether we get an error or not we will continue. We would *like* to increase
* the buffer size but its not required.
*/
(void) setsockopt(*SocketToReturn, SOL_SOCKET, SO_RCVBUF,
&krecieveSocketBufferSize, sizeof(krecieveSocketBufferSize));
/* Now that we have the socket created we want to set the timeout on the socket. This is
* the time a ping request will wait before assuming failure. Here we use the value which
* is passed to us as the timeout value. We set the timeout by setting the timeout for
* recieve requests on the socket using setsockopt.
* First Argument: The socket we are editing the receive timeout. In this case
* the socket we just created. This timeout will end up being the time ping waits for a response.
* Second Argument: UNIX constant SOL_SOCKET indicating we are editing a socket level
* attribute (see man page for setsockopt for more details).
* Third Argument: UNIX constant SO_RCVTIMEO indicating we are editing the receive timeout on
* the socket (see man page for setsockopt for more details).
* Forth Argument: The value that the timeout should be as a timeval structure. In this case
* we use the timeout passed to us as the timeout for the requests.
* Fifth Argument: The size of the forth argument (i.e. sizeof())
* Return Value: There is actually a return value of zero on success and -1 on failure.
*/
//Setting the ping timeout to one second. This way a recieve call will timeout after 1
//second later on. This saves us from having to use UNIX signal alarms for timeouts
pingTimeout.tv_sec = 1;
pingTimeout.tv_usec = 0;
error = setsockopt(*SocketToReturn, SOL_SOCKET, SO_RCVTIMEO,
&pingTimeout, sizeof(pingTimeout));
if (error != 0)
{
close(*SocketToReturn); //before returning error close the socket.
//were unable to set timeout on the socket. Here we will return an error.
return(errno);
}
return(0); //if got this far were successful. Return zero for success.
}
/*****************************************************
* CreateAndSendICMPPacket
*****************************************************
* Purpose: This function creates an ICMP packet with the necessary information
* inside of it to make it a ping packet. This function also sends that ping packet to
* the remote host.
*
* Parameters:
* HostAddress A sockaddr_in structure. On calling
* CreateAndSendICMPPacket this variable has an address
* of the host where the ping will be sent.
*
* SequenceNumber A integer. when calling CreateAndSendICMPPacket this variable
* will hold the sequence number of the ping packet being sent. This information is
* then put in the ping packet sent to the host so when they reply we know which
* send the reply is associated with.
*
* SocketConnectionToHost A socket descriptor expressed as an integer. On calling
* CreateAndSendICMPPacket this variable will be a valid socket which is already setup
* for communicating with the remote host.
*
* *Function Result* A UNIX error integer return value as described in:
* /usr/include/sys/errno.h on a BSD system.
* Note: This value will be zero on success.
*****************************************************/
int CreateAndSendICMPPacket(struct sockaddr_in HostAddress, int SequenceNumber, int SocketConnectionToHost)
{
struct PingICMPPacket PacketToSend;
int error;
ssize_t sizeOfDataSent;
// --- Setting up the packet we are going to send. --- //
//ICMP type is an echo packet which is the packet type for a ping.
PacketToSend.icmpHeader.icmp_type = ICMP_ECHO;
//Zero code for ping packet.
PacketToSend.icmpHeader.icmp_code = 0;
//Sequence number of the packet is whatever is passed to us
PacketToSend.icmpHeader.icmp_seq = SequenceNumber;
//add our PID as the identifier so we know later the ping originated from us.
PacketToSend.icmpHeader.icmp_id = getpid();
/* Now we will get time of day so we can add it to the "extra" data on the ICMP packet.
* The time of day will allow us to calculate the round trip time on the ping upon
* recieveing the echo packet
*/
error = gettimeofday(&PacketToSend.packetTimeStamp, NULL);
if (error != 0) //if not equal to zero then couldn't get time of day
{
if (errno != 0)
{
return(errno); //errno was set by gettimeofday. Return that value as error.
}
return(EPERM); //could not perform operation return UNIX error code operation not permitted.
}
/* Now that we have the filled out packet we will calculate the checksum for the packet.
* We actually will calculate checksum but only after we have everything filled out and
* set the checksum value to zero (for calculation)
*/
PacketToSend.icmpHeader.icmp_cksum = 0;
//The in_cksum function will calculate the checksum for us given the packet and its length.
PacketToSend.icmpHeader.icmp_cksum = in_cksum((u_short *)&PacketToSend, sizeof(PacketToSend));
/* Now that the packet is finished we will go ahead and send the packet to the host
* We use the sendto API to send the packet to the host.
* First Argument: The Socket used for sending the packet to the host. In this case the
* ICMP socket we already created.
* Second Argument: The actual packet itself we already created
* Third Argument: The size of the packet we are sending in this case the size of the packet
* structure
* Forth Argument: This is for additional flags which we won't use. Pass zero to ignore.
* Fifth Argument: The host address to send the packet to.
* Sixth Argument: The size of the host address passed in.
* Return Value: This call returns the size of the data sent (hopefully it will be the
* same as PacketToSend). On failure this function returns -1.
*/
sizeOfDataSent = sendto(SocketConnectionToHost, &PacketToSend,
sizeof(PacketToSend), 0,
(struct sockaddr*) &HostAddress, sizeof(HostAddress));
//if size of data sent is -1 (indicating error) or not size we wanted then we have a problem
if ((sizeOfDataSent < 0) || (sizeOfDataSent != sizeof(PacketToSend)))
{
if (errno != 0)
{
//packet wasn't sent properly return error.
return(errno); //return UNIX created by sendto
}
return(EPERM); //return more generic code since error code since errno wasn't set.
}
return(0); //If got this far were successful. Return zero indicating success.
}
/*****************************************************
* WaitAndPrintICMPs
*****************************************************
* Purpose: This function creates an ICMP packet with the necessary information
* inside of it to make it a ping packet. This function also sends that ping packet to
* the remote host.
*
* Parameters:
* SocketConnectionToHost A socket descriptor expressed as an integer. On calling
* WaitAndPrintICMPs this variable will be a valid socket which is already setup
* for communicating with the remote host. This will be used in getting the reply
* packets from the host.
*
* TimeoutInSeconds A timeout expressed as an integer. On calling
* WaitAndPrintICMPs this variable will have the number of seconds to wait for
* ICMP replies. Note even if a valid ICMP reply comes that matches what we expect
* we will still wait for additional ICMP packets until the timeout has occurred.
*
* ReturnimmediatelyAfterReply An integer. On calling WaitAndPrintICMPs if this variable is zero then
* we will wait for the timeout to occur even if we get the appropriate ping reply (waiting for any other packets).
* If this variable is non-zero then simple ping will return immediately after getting the appropriate ping reply to
* the request.
*
* GotResponse A pre-allocated integer. when calling WaitAndPrintICMPs
* this variable will be a pre-allocated integer. On successful return from WaitAndPrintICMPs this
* variable will hold a value of 1 if a ICMP packet response to our ping was received.
* And a zero otherwise. On failed return the value of this variable will be undefined.
*
* *Function Result* A UNIX error integer return value as described in:
* /usr/include/sys/errno.h on a BSD system.
* Note: This value will be zero on success.
*****************************************************/
int WaitAndPrintICMPs(int socketConnectionToHost, int TimeoutInSeconds, int ReturnimmediatelyAfterReply, int* GotResponse)
{
const int kBufferSize = 2048; //size we allocate for the reply buffer.
char pingReplyBuffer[kBufferSize];
struct sockaddr_in remoteHost;
int sizeOfRemoteHost = (int) sizeof(remoteHost);
ssize_t numberOfBytesReceived;
struct ip* packetInterpetedAsIPPacket;
int ipHeaderLength;
struct PingICMPPacket* icmpPacket;
int icmpPacketSize;
int error = 0;
int gotStartTime = 0;
struct timeval currentTime, timeSinceStartedWaiting;
struct timeval startTime, roundTripTimeOnPacket;
double roundTripTimeInMS;
//Checking input argument for validity
if ((GotResponse == NULL) || (TimeoutInSeconds < 1))
{
return(EINVAL); //invalid argument error return
}
*GotResponse = 0;
do
{
/* Now that he have sent the ping to the host we need to wait for a reply. We do this
* by calling recvfrom which will wait for a response for the timeout specified earlier
* when creating the socket
* First Argument: The socket we are waiting for data upon
* Second Argument: The buffer to use for storing the reply from the remote host.
* Third Argument: The size of the buffer in argument two
* Forth Argument: Additional flags which can be used for special options. We ignore this
* by passing zero
* Fifth Argument: A internet address structure used to hold the address information from where the
* data came from
* Sixth Argument: Size of the buffer/structure in argument five.
* Return Value: The size of the data returned. On error this value will be less than zero.
*/
numberOfBytesReceived = recvfrom(socketConnectionToHost, pingReplyBuffer,
sizeof(pingReplyBuffer), 0,
(struct sockaddr *) &remoteHost, &sizeOfRemoteHost);
if (numberOfBytesReceived < 0) //error receiving data, return error
{
error = errno; //return the UNIX errno variable which would be set by recvfrom.
}
if (gotStartTime == 0)
{
//Getting the start time for this function if we dont already have it.
if (gettimeofday(&startTime, NULL) != 0)
{
if (errno != 0)
{
//if got error getting time of day return UNIX error and give up.
return(errno);
}
return(EPERM); //return more generic error since wasn't set by gettimeofday
}
gotStartTime = 1;
}
if (error == 0)
{
/* Now that we have a reply we will test it to see if its the reply we expect.
* First step is to discard the IP header from the raw packet we got back. We can do this
* by determining the size of the IP header and then moving our pointer beyond that.
*/
//Interpret packet as IP packet to remove header
packetInterpetedAsIPPacket = (struct ip*)pingReplyBuffer;
//The ip_hl item within the IP packet has the length of the IP header expressed as bytes
//(shifted right twice, thus need to shift left to compensate.
ipHeaderLength = packetInterpetedAsIPPacket->ip_hl << 2;
//Now we know the IP header length we can get a pointer to the ICMP section of the packet
icmpPacket = (struct PingICMPPacket*)(pingReplyBuffer + ipHeaderLength);
icmpPacketSize = numberOfBytesReceived - ipHeaderLength;
//The echo request must be at least as large as the one we sent to have all echo information.
if (icmpPacketSize >= sizeof(struct PingICMPPacket))
{
//This packet also has to be an ICMP echo reply packet to the one.
if (icmpPacket->icmpHeader.icmp_type == ICMP_ECHOREPLY)
{
//To be our packet the id on the packet has to match our PID.
//This is because in the echo
//the id wouldn't change and we sent pid as the id.
if (icmpPacket->icmpHeader.icmp_id == getpid())
{
//If we got this far then this is a reply to our ping request!
*GotResponse = 1;
//--- Print out ICMP packet information ---//
//Get the current time for determining round trip time
if (gettimeofday(&currentTime, NULL) != 0)
{
if (errno != 0)
{
//if error getting time of day return UNIX error.
return(errno);
}
return(EPERM); //return more generic EPERM since gettimeofday
//didn't set error
}
//Subtracting the timeval structures to get roundTripTimeOnPacket
timersub(&currentTime, &(icmpPacket->packetTimeStamp), &roundTripTimeOnPacket);
//getting round trip time in milliseconds
roundTripTimeInMS = (double) (roundTripTimeOnPacket.tv_sec*1000 +
(((double) roundTripTimeOnPacket.tv_usec) / 1000));
printf("Response from %s: icmp_seq=%u ttl=%d time=%.3f ms\n",
inet_ntoa(remoteHost.sin_addr),
icmpPacket->icmpHeader.icmp_seq,
packetInterpetedAsIPPacket->ip_ttl,
roundTripTimeInMS);
fflush(stdout);
}//endif
}//endif
}//endif
}//endif no error on getting packet
else if (error == EAGAIN)
{
//we ignore EAGAIN errors since they are fired by the 1 second timeout on the socket
//On these occasions we just want to see if our timeout for the function has passed.
error = 0;
}
//no errors up to this point then calculate the time for timeout
if (error == 0)
{
//Get the current time for looking for determining timeout for function
if (gettimeofday(&currentTime, NULL) != 0)
{
if (errno != 0)
{
//if error getting time of day return UNIX error.
error = errno;
}
else
{error = EPERM;} //get more generic error since gettimeofday didn't set value
}
//Subtract two timeval structures to get the time since we started this function
timersub(&currentTime, &startTime, &timeSinceStartedWaiting);
}
}//end do while
while ((error == 0) && (timeSinceStartedWaiting.tv_sec < TimeoutInSeconds) && ((ReturnimmediatelyAfterReply == 0) || (GotResponse == 0)));
if (*GotResponse == 0)
{
printf("No Response From Host\n"); fflush(stdout);
}
return(0);
}
//Here stealing the in_cksum function which computes checksum for our packets from original ping.
int in_cksum(u_short *addr, int len)
{
register int nleft = len;
register u_short *w = addr;
register int sum = 0;
u_short answer = 0;
/*
* Our algorithm is simple, using a 32 bit accumulator (sum), we add
* sequential 16 bit words to it, and at the end, fold back all the
* carry bits from the top 16 bits into the lower 16 bits.
*/
while (nleft > 1) {
sum += *w++;
nleft -= 2;
}
/* mop up an odd byte, if necessary */
if (nleft == 1) {
*(u_char *)(&answer) = *(u_char *)w ;
sum += answer;
}
/* add back carry outs from top 16 bits to low 16 bits */
sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
sum += (sum >> 16); /* add carry */
answer = ~sum; /* truncate to 16 bits */
return(answer);
}
</pre>
<!--googleoff: index -->
</td>
</tr>
</table>
<!-- END WIDE COLUMN -->
<!-- END MAIN CONTENT -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><div style="width: 100%; height: 1px; background-color: #919699; margin-top: 5px; margin-bottom: 15px"></div></td>
</tr>
<tr>
<td align="center"><br/>
<table border="0" cellpadding="0" cellspacing="0" class="graybox">
<tr>
<th>Did this document help you?</th>
</tr>
<tr>
<td>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=1&url=/samplecode/SimplePing/listing3.html%3Fid%3DDTS10000716-1.1&media=dvd" target=_new>Yes</a>: Tell us what works for you.</div>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=2&url=/samplecode/SimplePing/listing3.html%3Fid%3DDTS10000716-1.1&media=dvd" target=_new>It’s good, but:</a> Report typos, inaccuracies, and so forth.</div>
<div><a href="http://developer.apple.com/feedback/?v=3&url=/samplecode/SimplePing/listing3.html%3Fid%3DDTS10000716-1.1&media=dvd" target=_new>It wasn’t helpful</a>: Tell us what would have helped.</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- START BOTTOM APPLE NAVIGATION -->
<!--#include virtual="/includes/footer"-->
<!-- END BOTTOM APPLE NAVIGATION -->
<!-- START CENTER CLOSE -->
</center>
<!-- END CENTER CLOSE -->
</body>
</html>