3 * COPYRIGHT: See COPYING in the top level directory
4 * PROJECT: ReactOS ping utility
5 * FILE: apps/net/ping/ping.c
6 * PURPOSE: Network test utility
7 * PROGRAMMERS: Casper S. Hornstrup (chorns@users.sourceforge.net)
9 * CSH 01/09/2000 Created
11 //#include <windows.h>
23 /* FIXME: Where should this be? */
27 #define CopyMemory(Destination, Source, Length) memcpy(Destination, Source, Length);
29 /* Should be in the header files somewhere (exported by ntdll.dll) */
30 long atol(const char *str
);
33 typedef long long __int64
;
36 char * _i64toa(__int64 value
, char *string
, int radix
);
41 /* General ICMP constants */
42 #define ICMP_MINSIZE 8 /* Minimum ICMP packet size */
43 #define ICMP_MAXSIZE 65535 /* Maximum ICMP packet size */
45 /* ICMP message types */
46 #define ICMPMSG_ECHOREQUEST 8 /* ICMP ECHO request message */
47 #define ICMPMSG_ECHOREPLY 0 /* ICMP ECHO reply message */
51 /* IPv4 header structure */
52 typedef struct _IPv4_HEADER
{
54 unsigned char Version
:4;
56 unsigned short Length
;
58 unsigned short FragFlags
;
60 unsigned char Protocol
;
61 unsigned short Checksum
;
62 unsigned int SrcAddress
;
63 unsigned int DstAddress
;
64 } IPv4_HEADER
, *PIPv4_HEADER
;
66 /* ICMP echo request/reply header structure */
67 typedef struct _ICMP_HEADER
{
70 unsigned short Checksum
;
72 unsigned short SeqNum
;
73 } ICMP_HEADER
, *PICMP_HEADER
;
75 typedef struct _ICMP_ECHO_PACKET
{
77 LARGE_INTEGER Timestamp
;
78 } ICMP_ECHO_PACKET
, *PICMP_ECHO_PACKET
;
84 BOOL ResolveAddresses
;
86 UINT DataSize
; /* ICMP echo request data size */
101 LARGE_INTEGER MinRTT
; /* Minimum round trip time in microseconds */
102 LARGE_INTEGER MaxRTT
;
103 LARGE_INTEGER SumRTT
;
104 LARGE_INTEGER AvgRTT
;
105 LARGE_INTEGER TicksPerMs
; /* Ticks per millisecond */
106 LARGE_INTEGER TicksPerUs
; /* Ticks per microsecond */
107 BOOL UsePerformanceCounter
;
110 /* Display the contents of a buffer */
111 static VOID
DisplayBuffer(
118 printf("Buffer (0x%p) Size (0x%lX).\n", Buffer
, Size
);
121 for (i
= 0; i
< Size
; i
++) {
125 printf("%02X ", (p
[i
]) & 0xFF);
130 /* Display usage information on screen */
131 static VOID
Usage(VOID
)
133 printf("\nUsage: ping [-t] [-n count] [-l size] [-w timeout] destination-host\n\n");
134 printf("Options:\n");
135 printf(" -t Ping the specified host until stopped.\n");
136 printf(" To stop - type Control-C.\n");
137 printf(" -n count Number of echo requests to send.\n");
138 printf(" -l size Send buffer size.\n");
139 printf(" -w timeout Timeout in milliseconds to wait for each reply.\n\n");
142 /* Reset configuration to default values */
143 static VOID
Reset(VOID
)
145 LARGE_INTEGER PerformanceCounterFrequency
;
148 ResolveAddresses
= FALSE
;
151 DontFragment
= FALSE
;
155 UsePerformanceCounter
= QueryPerformanceFrequency(&PerformanceCounterFrequency
);
157 if (UsePerformanceCounter
) {
158 /* Performance counters may return incorrect results on some multiprocessor
159 platforms so we restrict execution on the first processor. This may fail
160 on Windows NT so we fall back to GetCurrentTick() for timing */
161 if (SetThreadAffinityMask (GetCurrentThread(), 1) == 0) {
162 UsePerformanceCounter
= FALSE
;
165 /* Convert frequency to ticks per millisecond */
166 TicksPerMs
.QuadPart
= PerformanceCounterFrequency
.QuadPart
/ 1000;
167 /* And to ticks per microsecond */
168 TicksPerUs
.QuadPart
= PerformanceCounterFrequency
.QuadPart
/ 1000000;
170 if (!UsePerformanceCounter
) {
171 /* 1 tick per millisecond for GetCurrentTick() */
172 TicksPerMs
.QuadPart
= 1;
173 /* GetCurrentTick() cannot handle microseconds */
174 TicksPerUs
.QuadPart
= 1;
178 /* Return ULONG in a string */
179 static ULONG
GetULONG(LPSTR String
)
185 Length
= (UINT
)_tcslen(String
);
186 while ((i
< Length
) && ((String
[i
] < '0') || (String
[i
] > '9'))) i
++;
187 if ((i
>= Length
) || ((String
[i
] < '0') || (String
[i
] > '9'))) {
188 InvalidOption
= TRUE
;
191 Value
= (ULONG
)atol(&String
[i
]);
196 /* Return ULONG in a string. Try next paramter if not successful */
197 static ULONG
GetULONG2(LPSTR String1
, LPSTR String2
, PINT i
)
201 Value
= GetULONG(String1
);
203 InvalidOption
= FALSE
;
204 if (String2
[0] != '-') {
205 Value
= GetULONG(String2
);
214 /* Parse command line parameters */
215 static BOOL
ParseCmdline(int argc
, char* argv
[])
221 // lstrcpy(TargetName, "127.0.0.1");
231 InvalidOption
= FALSE
;
233 for (i
= 1; i
< argc
; i
++) {
234 if (argv
[i
][0] == '-') {
235 switch (argv
[i
][1]) {
236 case 't': NeverStop
= TRUE
; break;
237 case 'a': ResolveAddresses
= TRUE
; break;
238 case 'n': PingCount
= GetULONG2(&argv
[i
][2], argv
[i
+ 1], &i
); break;
240 DataSize
= GetULONG2(&argv
[i
][2], argv
[i
+ 1], &i
);
241 if ((DataSize
< 0) || (DataSize
> ICMP_MAXSIZE
- sizeof(ICMP_ECHO_PACKET
))) {
242 printf("Bad value for option -l, valid range is from 0 to %d.\n",
243 ICMP_MAXSIZE
- sizeof(ICMP_ECHO_PACKET
));
247 case 'f': DontFragment
= TRUE
; break;
248 case 'i': TTLValue
= GetULONG2(&argv
[i
][2], argv
[i
+ 1], &i
); break;
249 case 'v': TOSValue
= GetULONG2(&argv
[i
][2], argv
[i
+ 1], &i
); break;
250 case 'w': Timeout
= GetULONG2(&argv
[i
][2], argv
[i
+ 1], &i
); break;
252 printf("Bad option %s.\n", argv
[i
]);
257 printf("Bad option format %s.\n", argv
[i
]);
262 printf("Bad parameter %s.\n", argv
[i
]);
265 lstrcpy(TargetName
, argv
[i
]);
271 if ((!ShowUsage
) && (!FoundTarget
)) {
272 printf("Name or IP address of destination host must be specified.\n");
283 /* Calculate checksum of data */
284 static WORD
Checksum(PUSHORT data
, UINT size
)
290 size
-= sizeof(USHORT
);
294 sum
+= *(UCHAR
*)data
;
296 sum
= (sum
>> 16) + (sum
& 0xFFFF);
299 return (USHORT
)(~sum
);
302 /* Prepare to ping target */
303 static BOOL
Setup(VOID
)
305 WORD wVersionRequested
;
311 wVersionRequested
= MAKEWORD(2, 2);
313 Status
= WSAStartup(wVersionRequested
, &WsaData
);
315 printf("Could not initialize winsock dll.\n");
319 IcmpSock
= WSASocket(AF_INET
, SOCK_RAW
, IPPROTO_ICMP
, NULL
, 0, 0);
320 if (IcmpSock
== INVALID_SOCKET
) {
321 printf("Could not create socket (#%d).\n", WSAGetLastError());
325 ZeroMemory(&Target
, sizeof(Target
));
327 Addr
= inet_addr(TargetName
);
328 if (Addr
== INADDR_NONE
) {
329 phe
= gethostbyname(TargetName
);
331 printf("Unknown host %s.\n", TargetName
);
337 CopyMemory(&Target
.sin_addr
, phe
->h_addr
, phe
->h_length
);
339 Target
.sin_addr
.s_addr
= Addr
;
343 Target
.sin_family
= phe
->h_addrtype
;
345 Target
.sin_family
= AF_INET
;
348 TargetIP
= inet_ntoa(Target
.sin_addr
);
360 static VOID
Cleanup(VOID
)
362 if (IcmpSock
!= INVALID_SOCKET
)
363 closesocket(IcmpSock
);
368 static VOID
QueryTime(PLARGE_INTEGER Time
)
370 if (UsePerformanceCounter
) {
371 if (QueryPerformanceCounter(Time
) == 0) {
372 /* This should not happen, but we fall
373 back to GetCurrentTick() if it does */
374 Time
->u
.LowPart
= (ULONG
)GetTickCount();
375 Time
->u
.HighPart
= 0;
377 /* 1 tick per millisecond for GetCurrentTick() */
378 TicksPerMs
.QuadPart
= 1;
379 /* GetCurrentTick() cannot handle microseconds */
380 TicksPerUs
.QuadPart
= 1;
382 UsePerformanceCounter
= FALSE
;
385 Time
->u
.LowPart
= (ULONG
)GetTickCount();
386 Time
->u
.HighPart
= 0;
390 static VOID
TimeToMsString(LPSTR String
, LARGE_INTEGER Time
)
393 LARGE_INTEGER LargeTime
;
395 LargeTime
.QuadPart
= Time
.QuadPart
/ TicksPerMs
.QuadPart
;
397 _i64toa(LargeTime
.QuadPart
, Convstr
, 10);
398 strcpy(String
, Convstr
);
399 strcat(String
, "ms");
402 /* Locate the ICMP data and print it. Returns TRUE if the packet was good,
404 static BOOL
DecodeResponse(PCHAR buffer
, UINT size
, PSOCKADDR_IN from
)
406 PIPv4_HEADER IpHeader
;
407 PICMP_ECHO_PACKET Icmp
;
410 LARGE_INTEGER RelativeTime
;
411 LARGE_INTEGER LargeTime
;
414 IpHeader
= (PIPv4_HEADER
)buffer
;
416 IphLength
= IpHeader
->IHL
* 4;
418 if (size
< IphLength
+ ICMP_MINSIZE
) {
420 printf("Bad size (0x%X < 0x%X)\n", size
, IphLength
+ ICMP_MINSIZE
);
425 Icmp
= (PICMP_ECHO_PACKET
)(buffer
+ IphLength
);
427 if (Icmp
->Icmp
.Type
!= ICMPMSG_ECHOREPLY
) {
429 printf("Bad ICMP type (0x%X should be 0x%X)\n", Icmp
->Icmp
.Type
, ICMPMSG_ECHOREPLY
);
434 if (Icmp
->Icmp
.Id
!= (USHORT
)GetCurrentProcessId()) {
436 printf("Bad ICMP id (0x%X should be 0x%X)\n", Icmp
->Icmp
.Id
, (USHORT
)GetCurrentProcessId());
441 QueryTime(&LargeTime
);
443 RelativeTime
.QuadPart
= (LargeTime
.QuadPart
- Icmp
->Timestamp
.QuadPart
);
445 if ((RelativeTime
.QuadPart
/ TicksPerMs
.QuadPart
) < 1) {
450 TimeToMsString(Time
, RelativeTime
);
454 printf("Reply from %s: bytes=%d time%s%s TTL=%d\n", inet_ntoa(from
->sin_addr
),
455 size
- IphLength
- sizeof(ICMP_ECHO_PACKET
), Sign
, Time
, IpHeader
->TTL
);
456 if (RelativeTime
.QuadPart
< MinRTT
.QuadPart
) {
457 MinRTT
.QuadPart
= RelativeTime
.QuadPart
;
460 if (RelativeTime
.QuadPart
> MaxRTT
.QuadPart
)
461 MaxRTT
.QuadPart
= RelativeTime
.QuadPart
;
462 SumRTT
.QuadPart
+= RelativeTime
.QuadPart
;
467 /* Send and receive one ping */
468 static BOOL
Ping(VOID
)
475 PICMP_ECHO_PACKET Packet
;
477 /* Account for extra space for IP header when packet is received */
478 Size
= DataSize
+ 128;
479 Buffer
= GlobalAlloc(0, Size
);
481 printf("Not enough free resources available.\n");
485 ZeroMemory(Buffer
, Size
);
486 Packet
= (PICMP_ECHO_PACKET
)Buffer
;
488 /* Assemble ICMP echo request packet */
489 Packet
->Icmp
.Type
= ICMPMSG_ECHOREQUEST
;
490 Packet
->Icmp
.Code
= 0;
491 Packet
->Icmp
.Id
= (USHORT
)GetCurrentProcessId();
492 Packet
->Icmp
.SeqNum
= (USHORT
)CurrentSeqNum
;
493 Packet
->Icmp
.Checksum
= 0;
495 /* Timestamp is part of data area */
496 QueryTime(&Packet
->Timestamp
);
498 CopyMemory(Buffer
, &Packet
->Icmp
, sizeof(ICMP_ECHO_PACKET
) + DataSize
);
499 /* Calculate checksum for ICMP header and data area */
500 Packet
->Icmp
.Checksum
= Checksum((PUSHORT
)&Packet
->Icmp
, sizeof(ICMP_ECHO_PACKET
) + DataSize
);
504 /* Send ICMP echo request */
507 FD_SET(IcmpSock
, &Fds
);
508 Timeval
.tv_sec
= Timeout
/ 1000;
509 Timeval
.tv_usec
= Timeout
% 1000;
510 Status
= select(0, NULL
, &Fds
, NULL
, &Timeval
);
511 if ((Status
!= SOCKET_ERROR
) && (Status
!= 0)) {
514 printf("Sending packet\n");
515 DisplayBuffer(Buffer
, sizeof(ICMP_ECHO_PACKET
) + DataSize
);
519 Status
= sendto(IcmpSock
, Buffer
, sizeof(ICMP_ECHO_PACKET
) + DataSize
,
520 0, (SOCKADDR
*)&Target
, sizeof(Target
));
523 if (Status
== SOCKET_ERROR
) {
524 if (WSAGetLastError() == WSAEHOSTUNREACH
) {
525 printf("Destination host unreachable.\n");
527 printf("Could not transmit data (%d).\n", WSAGetLastError());
533 /* Expect to receive ICMP echo reply */
535 FD_SET(IcmpSock
, &Fds
);
536 Timeval
.tv_sec
= Timeout
/ 1000;
537 Timeval
.tv_usec
= Timeout
% 1000;
539 Status
= select(0, &Fds
, NULL
, NULL
, &Timeval
);
540 if ((Status
!= SOCKET_ERROR
) && (Status
!= 0)) {
541 Length
= sizeof(From
);
542 Status
= recvfrom(IcmpSock
, Buffer
, Size
, 0, &From
, &Length
);
545 printf("Received packet\n");
546 DisplayBuffer(Buffer
, Status
);
550 if (Status
== SOCKET_ERROR
) {
551 if (WSAGetLastError() != WSAETIMEDOUT
) {
552 printf("Could not receive data (%d).\n", WSAGetLastError());
560 printf("Request timed out.\n");
566 if (!DecodeResponse(Buffer
, Status
, (PSOCKADDR_IN
)&From
)) {
567 /* FIXME: Wait again as it could be another ICMP message type */
568 printf("Request timed out (incomplete datagram received).\n");
577 /* Program entry point */
578 int main(int argc
, char* argv
[])
587 if ((ParseCmdline(argc
, argv
)) && (Setup())) {
589 printf("\nPinging %s [%s] with %d bytes of data:\n\n",
590 TargetName
, TargetIP
, DataSize
);
593 while ((NeverStop
) || (Count
< PingCount
)) {
601 /* Calculate avarage round trip time */
602 if ((SentCount
- LostCount
) > 0) {
603 AvgRTT
.QuadPart
= SumRTT
.QuadPart
/ (SentCount
- LostCount
);
608 /* Calculate loss percent */
610 Count
= (SentCount
* 100) / LostCount
;
618 TimeToMsString(MinTime
, MinRTT
);
619 TimeToMsString(MaxTime
, MaxRTT
);
620 TimeToMsString(AvgTime
, AvgRTT
);
622 /* Print statistics */
623 printf("\nPing statistics for %s:\n", TargetIP
);
624 printf(" Packets: Sent = %d, Received = %d, Lost = %d (%d%% loss),\n",
625 SentCount
, SentCount
- LostCount
, LostCount
, Count
);
626 printf("Approximate round trip times in milli-seconds:\n");
627 printf(" Minimum = %s, Maximum = %s, Average = %s\n",
628 MinTime
, MaxTime
, AvgTime
);