Repository navigation
Expand file tree
/
Copy pathft_ping.c
More file actions
841 lines (746 loc) · 29.3 KB
/
Copy pathft_ping.c
File metadata and controls
841 lines (746 loc) · 29.3 KB
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
#include "ft_ping.h"
volatile sig_atomic_t g_interrupt = 0;
/**
* print_help_message - Display usage information for ft_ping
*
* Prints command-line syntax and available options to stdout.
* Called when user specifies -h or -? flag, or when invalid option is given.
*/
void print_help_message() {
printf("Usage:\n ft_ping [options] <destination>\n\n");
printf("Options:\n");
printf(" <destination> DNS name or IP address\n");
printf(" -v Verbose output\n");
printf(" -n no reverse DNS name resolution\n");
printf(" -t, --ttl <value> Set Time To Live (default: 64)\n");
printf(" -w <deadline> Exit after <deadline> seconds\n");
printf(" -W <timeout> time to wait for response\n");
printf(" -?, -h Show this help message\n");
}
/**
* parse_ping_argc - Parse command-line arguments
* @argc: Argument count from main
* @argv: Argument values from main
* @options: Pointer to struct where parsed options will be stored
*
* Parses command-line flags (-v, -h, -?) and extracts destination parameter.
*
* Return:
* 0 - Success, options struct filled with valid data
* 1 - Error (invalid option or missing destination)
* 2 - Help requested (-h or -?), help message already printed
*/
int parse_ping_argc(int argc, char *argv[], struct s_ping_options *options) {
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
// Handle long options (--option)
if (argv[i][1] == '-') {
// --ttl
if (strcmp(argv[i], "--ttl") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "ft_ping: option requires an argument -- '--ttl'\n");
print_help_message();
return 1;
}
i++;
options->ttl = atoi(argv[i]);
if (options->ttl <= 0 || options->ttl > 255) {
fprintf(stderr, "ft_ping: invalid TTL value: %s (must be 1-255)\n", argv[i]);
return 1;
}
}
// Invalid long option
else {
fprintf(stderr, "ft_ping: invalid option -- '%s'\n", argv[i]);
print_help_message();
return 1;
}
}
// Handle short options (-o)
else {
// Check if it's a single character option (no extra chars after flag)
char option_char = argv[i][1];
bool has_extra_chars = argv[i][2] != '\0';
// -v (verbose)
if (option_char == 'v' && !has_extra_chars) {
options->verbose = true;
}
// -t (TTL)
else if (option_char == 't' && !has_extra_chars) {
if (i + 1 >= argc) {
fprintf(stderr, "ft_ping: option requires an argument -- 't'\n");
print_help_message();
return 1;
}
i++;
options->ttl = atoi(argv[i]);
if (options->ttl <= 0 || options->ttl > 255) {
fprintf(stderr, "ft_ping: invalid TTL value: %s (must be 1-255)\n", argv[i]);
return 1;
}
}
else if (option_char == 'n' && !has_extra_chars) {
options->numeric_output = true;
}
// -w (deadline)
else if (option_char == 'w' && !has_extra_chars) {
if (i + 1 >= argc) {
fprintf(stderr, "ft_ping: option requires an argument -- 'w'\n");
print_help_message();
return 1;
}
i++;
options->deadline_seconds = atoi(argv[i]);
if (options->deadline_seconds <= 0) {
fprintf(stderr, "ft_ping: invalid deadline value: %s (must be > 0)\n", argv[i]);
return 1;
}
}
// -W (timeout per packet)
else if (option_char == 'W' && !has_extra_chars) {
if (i + 1 >= argc) {
fprintf(stderr, "ft_ping: option requires an argument -- 'W'\n");
print_help_message();
return 1;
}
i++;
options->timeout_seconds = atof(argv[i]);
if (options->timeout_seconds <= 0) {
fprintf(stderr, "ft_ping: invalid timeout value: %s (must be > 0)\n", argv[i]);
return 1;
}
}
// -? or -h (help)
else if ((option_char == '?' || option_char == 'h') && !has_extra_chars) {
options->help_requested = true;
print_help_message();
return 2;
}
// Invalid short option
else {
fprintf(stderr, "ft_ping: invalid option -- '%s'\n", argv[i]);
print_help_message();
return 1;
}
}
} else {
// Handle destination address
options->destination = argv[i];
}
}
if (options->destination == NULL) {
fprintf(stderr, "ft_ping: usage error: Destination address required\n");
return 1;
}
return 0;
}
void copy_icmp_header(int8_t *dest, int8_t *src, int16_t len) {
for (int16_t i = 0; i < len; i++)
dest[i] = src[i];
}
/**
* resolve_ipv4_sockaddr - Resolve hostname/IP to binary IPv4 address
* @dest: Input hostname (e.g., "google.com") or IP string (e.g., "8.8.8.8")
* @out: Output struct to store resolved address information
*
* Performs DNS resolution using getaddrinfo() to convert hostname or IP string
* into a binary sockaddr_in structure usable by socket functions.
* Also converts the binary address back to a human-readable string.
*
* Steps:
* 1. Validates input parameters
* 2. Sets up getaddrinfo() hints for IPv4/ICMP/raw socket
* 3. Calls getaddrinfo() to perform DNS lookup
* 4. Extracts binary IPv4 address to out->addr
* 5. Converts binary to string using inet_ntop()
* 6. Stores original hostname pointer
* 7. Frees resolver resources
*
* Return:
* 0 - Success, out->addr and out->ip_string are filled
* -1 - Failure (DNS lookup failed or invalid input)
*/
int resolve_ipv4_sockaddr(const char *dest, struct s_resolved_ipv4 *out) {
struct addrinfo hints;
struct addrinfo *res;
struct sockaddr_in *ipv4_addr_in;
int ret;
// Validate input
if (dest == NULL || out == NULL) {
return -1;
}
// Initialize nullified hints
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; // IPv4
hints.ai_socktype = SOCK_RAW; // Raw socket for ICMP
hints.ai_protocol = IPPROTO_ICMP; // ICMP protocol
ret = getaddrinfo(dest, NULL, &hints, &res);
if (ret != 0) {
fprintf(stderr, "ft_ping: unknown host %s\n", dest);
return -1;
}
ipv4_addr_in = (struct sockaddr_in *)res->ai_addr;
memset(&out->addr, 0, sizeof(struct sockaddr_in));
out->addr.sin_family = AF_INET;
out->addr.sin_addr = ipv4_addr_in->sin_addr;
const char *inet_res = inet_ntop(AF_INET, &out->addr.sin_addr, out->ip_string, INET_ADDRSTRLEN);
if (inet_res == NULL) {
freeaddrinfo(res);
return -1;
}
out->hostname = (char *)dest;
freeaddrinfo(res);
return 0;
}
/**
* calculate_icmp_checksum - Calculate RFC 1071 Internet Checksum
* @data: Pointer to ICMP packet data (header + payload)
* @len: Length of data in bytes
*
* Calculates the 16-bit one's complement checksum used for ICMP packet
* integrity verification as defined in RFC 1071.
*
* Algorithm:
* 1. Sum all 16-bit words in the data
* 2. If length is odd, add the last byte as 8-bit value
* 3. Fold any carry bits from 32-bit sum into 16 bits
* 4. Return the one's complement (~sum)
*
* Usage:
* - Set checksum field to 0 before calling this function
* - Calculate checksum over entire ICMP packet
* - Store returned value in checksum field
*
* Return: 16-bit checksum value
*/
uint16_t calculate_icmp_checksum(void *data, int16_t len) {
uint16_t *ptr = data;
uint32_t sum = 0; // 32-bit sum to handle overflow
while (len > 1) {
sum += *ptr++;
len -= 2; // read 16-bit chunks for checksum
}
if (len == 1) {
sum += *((uint8_t *)ptr); // Add remaining byte if odd length
}
while (sum >> 16) // Fold 32-bit sum to 16 bits
sum = (sum & 0xFFFF) + (sum >> 16);
return (uint16_t)(~sum);
}
/**
* create_raw_socket - Create a raw ICMP socket
*
* Creates a raw socket for sending/receiving ICMP packets.
* Requires CAP_NET_RAW capability or root privileges.
*
* Return:
* Socket file descriptor on success (>= 0)
* -1 on failure (prints error message)
*/
int create_raw_socket(void) {
int sockfd;
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (sockfd < 0) {
if (errno == EPERM) {
fprintf(stderr, "ft_ping: Lacking privilege for raw socket.\n");
} else {
perror("ft_ping: socket");
}
return -1;
} else {
return sockfd;
}
}
/**
* configure_socket - Set socket options for ping operation
* @sockfd: Socket file descriptor
* @ttl: Time To Live value (1-255)
*
* Configures timeout and TTL options for the ICMP socket.
*
* Return: 0 on success, -1 on failure
*/
int configure_socket(int sockfd, int ttl, double timeout_seconds) {
struct timeval timeout;
timeout.tv_sec = (long)timeout_seconds; // Seconds part
timeout.tv_usec = (long)((timeout_seconds - timeout.tv_sec) * 1000000); // Microseconds part
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0) {
perror("ft_ping: setsockopt SO_RCVTIMEO");
return -1;
}
if (setsockopt(sockfd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl)) < 0) {
perror("ft_ping: setsockopt IP_TTL");
return -1;
}
return 0;
}
/**
* build_icmp_packet - Build ICMP Echo Request packet
* @packet: Buffer to store packet (must be PACKET_SIZE bytes)
* @sequence: Sequence number for this packet
*
* Constructs an ICMP Echo Request packet with:
* - Type: 8 (Echo Request)
* - Code: 0
* - Identifier: Process ID
* - Sequence: Given sequence number
* - Data: Current timestamp + padding
* - Checksum: Calculated over entire packet
*/
void build_icmp_packet(uint8_t *packet, uint16_t sequence) {
struct s_icmp_header *icmp_hdr = (struct s_icmp_header *)packet;
icmp_hdr->type = ICMP_ECHO_REQUEST; // Echo Request
icmp_hdr->code = 0;
icmp_hdr->id = htons(getpid()); // Use lower 16 bits of PID
icmp_hdr->sequence = htons(sequence);
icmp_hdr->checksum = 0; // Initialize checksum to 0 before calculation
// Fill data with current timestamp (for RTT calculation) + padding
struct timeval *timestamp = (struct timeval *)(packet + ICMP_HEADER_SIZE);
gettimeofday(timestamp, NULL); // Store current time in data section
memset(packet + ICMP_HEADER_SIZE + sizeof(struct timeval), 0, PACKET_DATA_SIZE - sizeof(struct timeval)); // Zero padding fot the rest of 56 bytes
icmp_hdr->checksum = calculate_icmp_checksum(packet, PACKET_SIZE); // Calculate checksum over entire packet
}
/**
* calculate_rtt - Calculate Round Trip Time in milliseconds
* @send_time: Time when packet was sent
* @recv_time: Time when reply was received
*
* Calculates the time difference between sending and receiving,
* converting the result to milliseconds with decimal precision.
*
* Return: RTT in milliseconds (e.g., 23.456 ms)
*/
double calculate_rtt(struct timeval *send_time, struct timeval *recv_time) {
double sec_diff = recv_time->tv_sec - send_time->tv_sec;
double usec_diff = recv_time->tv_usec - send_time->tv_usec; // Microsecond difference
return (sec_diff * 1000.0) + (usec_diff / 1000.0); // Convert to milliseconds
}
/**
* print_icmp_error - Display ICMP error messages in verbose mode
* @type: ICMP message type
* @code: ICMP message code (subtype)
* @ip_hdr: IP header from the received packet
* @seq: Sequence number of the original packet
*
* Prints human-readable ICMP error messages when verbose mode is enabled.
* Common errors include:
* - Type 3: Destination Unreachable (network/host/port)
* - Type 11: Time Exceeded (TTL expired)
* - Type 8: Echo Request (our own packet)
*/
void print_icmp_error(uint8_t type, uint8_t code, struct iphdr *ip_idr, uint16_t seq) {
char source_ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ip_idr->saddr, source_ip, INET_ADDRSTRLEN);
// Print error message based on type and code
printf("From %s icmp_seq=%u ", source_ip, seq);
switch (type)
{
case ICMP_DEST_UNREACH: // Type 3
switch (code)
{
case ICMP_NET_UNREACH:
printf("Destination Network Unreachable\n");
break;
case ICMP_HOST_UNREACH:
printf("Destination Host Unreachable\n");
break;
case ICMP_PROT_UNREACH:
printf("Destination Protocol Unreachable\n");
break;
case ICMP_PORT_UNREACH:
printf("Destination Port Unreachable\n");
break;
default:
printf("Destination Unreachable (code %d)\n", code);
break;
}
break;
case ICMP_TIME_EXCEEDED: // Type 11
if (code == ICMP_TTL_EXCEEDED) {
printf("Time to live exceeded\n");
} else {
printf("Time Exceeded (code %d)\n", code);
}
break;
case ICMP_ECHO_REQUEST: // Type 8 (our own packet, should not happen in receive)
printf("Echo Request (unexpected)\n");
break;
default:
printf("Unknown ICMP type %d (code %d)\n", type, code);
break;
}
}
/**
* send_ping - Send ICMP Echo Request packet
* @sockfd: Socket file descriptor
* @dest_addr: Destination address
* @sequence: Sequence number for this packet
*
* Builds and sends an ICMP Echo Request packet to the destination.
*
* Return: 0 on success, -1 on failure
*/
int send_ping(int sockfd, struct sockaddr_in *dest_addr, uint16_t sequence) {
uint8_t packet[PACKET_SIZE];
build_icmp_packet(packet, sequence);
// Send packet to destination using sendto()
ssize_t sent_bytes = sendto(
sockfd,
packet,
PACKET_SIZE,
0,
(struct sockaddr *)dest_addr,
sizeof(struct sockaddr_in)
);
if (sent_bytes < 0) {
perror("ft_ping: sendto");
return -1;
} else if (sent_bytes != PACKET_SIZE) {
fprintf(stderr, "ft_ping: sendto: sent %zd bytes, expected %d\n", sent_bytes, PACKET_SIZE);
return -1;
}
return 0;
}
/**
* receive_ping - Receive and process ICMP Echo Reply
* @sockfd: Socket file descriptor
* @expected_seq: Expected sequence number
*
* Receives ICMP reply, verifies it matches our request, extracts timestamp,
* calculates RTT, and displays result.
*
* Steps:
* 1. Receive packet with recvfrom()
* 2. Parse IP header to get TTL and find ICMP offset
* 3. Parse ICMP reply
* 4. Verify type, ID, sequence
* 5. Extract timestamp and calculate RTT
* 6. Display result
*
* Return: 0 on success, -1 on failure or timeout
*/
int receive_ping(int sockfd, uint16_t expected_seq, bool verbose, bool numeric_output, struct s_ping_stats *stats) {
uint8_t buffer[RECV_BUFFER_SIZE]; // Large buffer for IP + ICMP
struct timeval recv_time;
// Loop to handle potential non-echo replies (e.g., time exceeded) until we get the expected reply or timeout
while (1) {
ssize_t received_bytes = recvfrom(sockfd, buffer, sizeof(buffer), 0, NULL, NULL);
gettimeofday(&recv_time, NULL); // Timestamp when packet is received
if (received_bytes < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
fprintf(stderr, "ft_ping: Request timeout for icmp_seq %u\n", expected_seq);
if (stats) {
update_stats(stats, 0, false); // Timeout, no RTT
}
return -1;
} else {
perror("ft_ping: recvfrom");
return -1;
}
}
struct iphdr *ip_hdr = (struct iphdr *)buffer;
int ip_header_len = ip_hdr->ihl * 4; // IP header length in bytes
struct s_icmp_header *icmp_hdr = (struct s_icmp_header *)(buffer + ip_header_len);
if (icmp_hdr->type != ICMP_ECHO_REPLY) {
// For ICMP error messages (TTL exceeded, unreachable), check if they belong to our packet
// by parsing the embedded original IP+ICMP headers in the error payload
if (icmp_hdr->type == ICMP_TIME_EXCEEDED || icmp_hdr->type == ICMP_DEST_UNREACH) {
struct iphdr *inner_ip = (struct iphdr *)((uint8_t *)icmp_hdr + ICMP_HEADER_SIZE);
int inner_ip_len = inner_ip->ihl * 4;
struct s_icmp_header *inner_icmp = (struct s_icmp_header *)((uint8_t *)inner_ip + inner_ip_len);
if (ntohs(inner_icmp->id) == (uint16_t)getpid() &&
ntohs(inner_icmp->sequence) == expected_seq) {
// This error is for our packet — print it and return without "Request timeout"
print_icmp_error(icmp_hdr->type, icmp_hdr->code, ip_hdr, ntohs(inner_icmp->sequence));
if (stats) {
update_stats(stats, 0, false);
}
return -1;
}
} else if (icmp_hdr->type == ICMP_ECHO_REQUEST && verbose) {
// Echo Request (Type 8) - only show with verbose flag
print_icmp_error(icmp_hdr->type, icmp_hdr->code, ip_hdr, expected_seq);
}
continue;
}
// Verify that the reply matches our request by checking ID
uint16_t reply_id = ntohs(icmp_hdr->id);
if (reply_id != (uint16_t)getpid()) {
continue; // Not our packet, ignore and keep waiting
// fprintf(stderr, "ft_ping: Received packet with mismatched ID (got %u, expected %u)\n", reply_id, getpid() & 0xFFFF);
// return -1;
}
// Verify sequence number matches expected
uint16_t reply_seq = ntohs(icmp_hdr->sequence);
if (reply_seq != expected_seq) {
// Old or duplicate packet, ignore it
continue;
// fprintf(stderr, "ft_ping: Received packet with mismatched sequence (got %u, expected %u)\n", reply_seq, expected_seq);
// return -1;
}
// Extract timestamp by skipping IP header and ICMP header
struct timeval *send_time = (struct timeval *)(buffer + ip_header_len + ICMP_HEADER_SIZE);
double rtt = calculate_rtt(send_time, &recv_time);
// Update statistics (received successfully)
if (stats) {
update_stats(stats, rtt, true);
}
// Format time with adaptive precision (matches inetutils ping)
char time_str[32];
if (rtt < 1.0) {
// Very fast (< 1ms): 3 decimals (e.g., 0.047)
snprintf(time_str, sizeof(time_str), "%.3f", rtt);
} else if (rtt < 10.0) {
// Fast (1-10ms): 2 decimals (e.g., 8.77)
snprintf(time_str, sizeof(time_str), "%.2f", rtt);
} else if (rtt < 100.0) {
// Medium (10-100ms): 1 decimal (e.g., 12.4)
snprintf(time_str, sizeof(time_str), "%.1f", rtt);
} else {
// Slow (100ms+): whole number (e.g., 125)
snprintf(time_str, sizeof(time_str), "%.0f", rtt);
}
char source_ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ip_hdr->saddr, source_ip, INET_ADDRSTRLEN);
// Reverse DNS lookup for hostname if numeric output -n is not requested
char hostname[NI_MAXHOST];
if (!numeric_output) {
struct sockaddr_in source_addr;
memset(&source_addr, 0, sizeof(source_addr));
source_addr.sin_family = AF_INET;
source_addr.sin_addr.s_addr = ip_hdr->saddr;
int ret = getnameinfo(
(struct sockaddr *)&source_addr,
sizeof(source_addr),
hostname,
sizeof(hostname),
NULL,
0,
0);
if (ret == 0) {
// Success - show hostname (IP)
if (verbose) {
printf("%zd bytes from %s (%s): icmp_seq=%u ident=%u ttl=%d time=%s ms\n",
received_bytes - ip_header_len,
hostname, // Reverse DNS result
source_ip, // Original IP
reply_seq,
reply_id,
ip_hdr->ttl,
time_str);
} else {
printf("%zd bytes from %s (%s): icmp_seq=%u ttl=%d time=%s ms\n",
received_bytes - ip_header_len,
hostname, // Reverse DNS result
source_ip, // Original IP
reply_seq,
ip_hdr->ttl,
time_str);
}
}
else {
// Reverse DNS failed, show IP only
if (verbose) {
printf("%zd bytes from %s: icmp_seq=%u ident=%u ttl=%d time=%s ms\n",
received_bytes - ip_header_len,
source_ip,
reply_seq,
reply_id,
ip_hdr->ttl,
time_str);
} else {
printf("%zd bytes from %s: icmp_seq=%u ttl=%d time=%s ms\n",
received_bytes - ip_header_len,
source_ip,
reply_seq,
ip_hdr->ttl,
time_str);
}
}
}
else {
// -n flag: numeric only, skip reverse DNS
if (verbose) {
printf("%zd bytes from %s: icmp_seq=%u ident=%u ttl=%d time=%s ms\n",
received_bytes - ip_header_len,
source_ip,
reply_seq,
reply_id,
ip_hdr->ttl,
time_str);
} else {
printf("%zd bytes from %s: icmp_seq=%u ttl=%d time=%s ms\n",
received_bytes - ip_header_len,
source_ip,
reply_seq,
ip_hdr->ttl,
time_str);
}
}
return 0;
}
}
/**
* handle_sigint - Signal handler for SIGINT (Ctrl+C)
* @sig: Signal number (unused)
*
* Sets global flag to indicate interrupt received.
* This allows graceful shutdown with statistics display.
*/
void handle_sigint(int sig) {
(void)sig; // Unused parameter
g_interrupt = 1; // Set flag to indicate interrupt received
printf("\n"); // Print newline after ^C
}
/**
* init_stats - Initialize statistics structure
* @stats: Statistics structure to initialize
*/
void init_stats(struct s_ping_stats *stats) {
stats->packets_transmitted = 0;
stats->packets_received = 0;
stats->rtt_min = 999999.0; // Start with very large value
stats->rtt_max = 0.0;
stats->rtt_sum = 0.0;
stats->rtt_sum_sq = 0.0;
gettimeofday(&stats->start_time, NULL);
}
/**
* update_stats - Update statistics with new packet result
* @stats: Statistics structure
* @rtt: Round trip time in milliseconds (if received)
* @received: true if reply was received, false if timeout
*/
void update_stats(struct s_ping_stats *stats, double rtt, bool received) {
stats->packets_transmitted++;
if (received) {
stats->packets_received++;
// Update min/max
if (rtt < stats->rtt_min) stats->rtt_min = rtt;
if (rtt > stats->rtt_max) stats->rtt_max = rtt;
// Update sum for average
stats->rtt_sum += rtt;
// Update sum of squares for mdev
stats->rtt_sum_sq += (rtt * rtt);
}
}
/**
* print_stats - Display ping statistics on exit
* @stats: Statistics structure with collected data
* @hostname: Target hostname or IP
*
* Displays summary like standard ping:
* - Packets transmitted/received/lost
* - Total time elapsed
* - RTT min/avg/max/mdev
*/
void print_stats(struct s_ping_stats *stats, const char *hostname) {
struct timeval end_time;
gettimeofday(&end_time, NULL);
// Calculate total time in milliseconds
long total_ms = (end_time.tv_sec - stats->start_time.tv_sec) * 1000 +
(end_time.tv_usec - stats->start_time.tv_usec) / 1000;
// Calculate packet loss percentage
double loss_percent = 0.0;
if (stats->packets_transmitted > 0) {
loss_percent = 100.0 * (stats->packets_transmitted - stats->packets_received) /
stats->packets_transmitted;
}
printf("\n--- %s ping statistics ---\n", hostname);
printf("%u packets transmitted, %u received, %.0f%% packet loss, time %ldms\n",
stats->packets_transmitted,
stats->packets_received,
loss_percent,
total_ms);
// Only show RTT stats if we received at least one packet
if (stats->packets_received > 0) {
double avg = stats->rtt_sum / stats->packets_received;
// Calculate mdev (standard deviation)
double variance = (stats->rtt_sum_sq / stats->packets_received) - (avg * avg);
double mdev = sqrt(variance);
printf("rtt min/avg/max/mdev = %.3f/%.3f/%.3f/%.3f ms\n",
stats->rtt_min, avg, stats->rtt_max, mdev);
}
}
int main(int argc, char *argv[]) {
struct s_ping_options options = {
.verbose = false,
.destination = NULL,
.help_requested = false,
.ttl = 64, // Default TTL value
.numeric_output = false,
.deadline_seconds = 0, // 0 = no deadline
.timeout_seconds = 1.0 // Default: 1 second timeout per packet
};
struct s_resolved_ipv4 target; // To hold resolved address info
int parse_result = parse_ping_argc(argc, argv, &options);
if (parse_result == 2)
return 0; // Help was shown, exit success
if (parse_result == 1)
return 1; // Error occurred, exit failure
// Continue with normal ping operation
// Create raw socket first (needed for verbose output)
int sockfd = create_raw_socket();
if (sockfd < 0) {
return 1; // Error creating socket
}
if (configure_socket(sockfd, options.ttl, options.timeout_seconds) < 0) {
close(sockfd);
return 1; // Error configuring socket
}
// Verbose: show socket debug info (before DNS resolution)
if (options.verbose) {
printf("ft_ping: sock4.fd: %d (socktype: SOCK_RAW), hints.ai_family: AF_INET\n\n", sockfd);
}
if (resolve_ipv4_sockaddr(options.destination, &target) != 0) {
close(sockfd);
return 1; // Error resolving address
}
// Verbose: show DNS resolution info
if (options.verbose) {
printf("ai->ai_family: AF_INET, ai->ai_canonname: '%s'\n", target.hostname);
}
printf("ft_ping %s (%s) %d(%d) bytes of data\n",
target.hostname,
target.ip_string,
PACKET_DATA_SIZE,
PACKET_SIZE + 20
);
// Initialize statistics tracking
struct s_ping_stats stats;
init_stats(&stats);
// Register signal handler for Ctrl+C
signal(SIGINT, handle_sigint);
uint16_t seq = 1;
while (!g_interrupt) {
// Check if deadline has been reached
if (options.deadline_seconds > 0) {
struct timeval current_time;
gettimeofday(¤t_time, NULL);
double elapsed = (current_time.tv_sec - stats.start_time.tv_sec) +
(current_time.tv_usec - stats.start_time.tv_usec) / 1000000.0;
if (elapsed >= options.deadline_seconds) {
break; // Exit loop, deadline reached
}
}
// Send ICMP Echo Request
if (send_ping(sockfd, &target.addr, seq) < 0) {
fprintf(stderr, "ft_ping: Failed to send ping for sequence %u\n", seq);
update_stats(&stats, 0, false); // Count as failed
seq++;
continue; // Try next sequence
}
// Receive ICMP Echo Reply
if (receive_ping(sockfd, seq, options.verbose, options.numeric_output, &stats) < 0) {
seq++;
sleep(1); // Wait 1 second before sending next ping
continue; // Try next sequence
}
sleep(1); // Wait 1 second before sending next ping
seq++;
}
// Print statistics summary
print_stats(&stats, target.hostname);
close(sockfd);
return 0;
}