ping.c (8675B)
1 /* see LICENSE file for copyright and license details */ 2 3 #if FEATURE_NET_IOCTL 4 #ifndef _DEFAULT_SOURCE 5 #define _DEFAULT_SOURCE 6 #endif 7 #endif 8 9 #include "arg.h" 10 #include "util.h" 11 12 #include <arpa/inet.h> 13 #include <errno.h> 14 #include <netdb.h> 15 #include <netinet/in.h> 16 #include <netinet/ip.h> 17 #include <netinet/ip_icmp.h> 18 #include <poll.h> 19 #include <signal.h> 20 #include <stdio.h> 21 #include <stdlib.h> 22 #include <string.h> 23 #include <sys/socket.h> 24 #include <sys/time.h> 25 #include <sys/types.h> 26 #include <unistd.h> 27 28 static int keep_running = 1; 29 30 static void 31 usage(void) 32 { 33 eprintf( 34 "usage: %s [-c count] [-i interval] [-s size] [-t ttl] [-w " 35 "deadline] [-q] host\n", 36 argv0 37 ); 38 } 39 40 static void 41 sigint_handler(int sig) 42 { 43 (void)sig; 44 keep_running = 0; 45 } 46 47 static unsigned short 48 checksum(unsigned short *addr, int len) 49 { 50 unsigned long sum = 0; 51 52 while (len > 1) { 53 sum += *addr++; 54 len -= 2; 55 } 56 if (len > 0) 57 sum += *(unsigned char *)addr; 58 while (sum >> 16) 59 sum = (sum & 0xffff) + (sum >> 16); 60 return ~sum; 61 } 62 63 static void 64 send_ping(int sock, struct sockaddr_in *dst, int seq, int size) 65 { 66 struct icmphdr *icmp; 67 char *packet; 68 struct timeval tv; 69 int packlen = sizeof(*icmp) + size; 70 71 packet = emalloc(packlen); 72 memset(packet, 0, packlen); 73 74 icmp = (struct icmphdr *)packet; 75 icmp->type = ICMP_ECHO; 76 icmp->code = 0; 77 icmp->un.echo.id = htons(getpid() & 0xffff); 78 icmp->un.echo.sequence = htons(seq); 79 80 /* store timestamp in payload if size is large enough */ 81 if (size >= (int)sizeof(struct timeval)) { 82 gettimeofday(&tv, NULL); 83 memcpy(packet + sizeof(*icmp), &tv, sizeof(tv)); 84 } 85 86 icmp->checksum = checksum((unsigned short *)packet, packlen); 87 88 if (sendto(sock, packet, packlen, 0, (struct sockaddr *)dst, sizeof(*dst)) < 0) 89 eprintf("sendto:"); 90 91 free(packet); 92 } 93 94 static double 95 get_time_ms(void) 96 { 97 struct timeval tv; 98 gettimeofday(&tv, NULL); 99 return (double)tv.tv_sec * 1000.0 + (double)tv.tv_usec / 1000.0; 100 } 101 102 static void 103 print_stats( 104 const char *host, int sent, int received, double min_rtt, double max_rtt, double sum_rtt 105 ) 106 { 107 printf("\n--- %s ping statistics ---\n", host); 108 printf( 109 "%d packets transmitted, %d received, %d%% packet loss\n", 110 sent, 111 received, 112 sent > 0 ? (sent - received) * 100 / sent : 0 113 ); 114 if (received > 0) { 115 printf("rtt min/avg/max = %.3f/%.3f/%.3f ms\n", min_rtt, sum_rtt / received, max_rtt); 116 } 117 } 118 119 // ?man ping: send icmp echo requests 120 // ?man arguments: host 121 // ?man send icmp echo requests to verify network connectivity 122 int 123 main(int argc, char *argv[]) 124 { 125 struct addrinfo hints, *res; 126 struct sockaddr_in dst; 127 struct sockaddr_in from; 128 struct pollfd pfd; 129 struct timeval sent_tv; 130 struct icmphdr *icmp; 131 char *cflag = NULL; 132 char *iflag = NULL; 133 char *sflag = NULL; 134 char *tflag = NULL; 135 char *wflag = NULL; 136 char *host; 137 char *rxbuf; 138 int qflag = 0; 139 int count = 0; 140 int size = 56; 141 int ttl = 0; 142 int deadline = 0; 143 int sock = -1; 144 int is_raw = 1; 145 int seq = 1; 146 int sent = 0; 147 int received = 0; 148 int r, optval, p_res, hlen; 149 double interval = 1.0; 150 double min_rtt = 999999.0; 151 double max_rtt = 0.0; 152 double sum_rtt = 0.0; 153 double start_time, deadline_ms, next_send_ms, now, timeout_ms, time_to_deadline, rtt, sent_ms; 154 ssize_t n; 155 socklen_t fromlen; 156 157 ARGBEGIN 158 { 159 // ?man -c:str: print count or perform stdout action 160 case 'c': 161 cflag = EARGF(usage()); 162 break; 163 // ?man -i:str: interactive mode or prompt for confirmation 164 case 'i': 165 iflag = EARGF(usage()); 166 break; 167 // ?man -s:str: silent mode or print summary 168 case 's': 169 sflag = EARGF(usage()); 170 break; 171 // ?man -t:str: sort or specify timestamp 172 case 't': 173 tflag = EARGF(usage()); 174 break; 175 // ?man -w:str: wait for completion 176 case 'w': 177 wflag = EARGF(usage()); 178 break; 179 // ?man -q: quiet mode; suppress output 180 case 'q': 181 qflag = 1; 182 break; 183 default: 184 usage(); 185 } 186 ARGEND 187 188 if (argc < 1) 189 usage(); 190 191 host = argv[0]; 192 193 if (cflag) 194 count = estrtonum(cflag, 1, 1000000); 195 if (iflag) 196 interval = estrtod(iflag); 197 if (sflag) 198 size = estrtonum(sflag, 0, 65507); 199 if (tflag) 200 ttl = estrtonum(tflag, 1, 255); 201 if (wflag) 202 deadline = estrtonum(wflag, 1, 1000000); 203 204 memset(&hints, 0, sizeof(hints)); 205 hints.ai_family = AF_INET; 206 hints.ai_socktype = SOCK_RAW; 207 208 r = getaddrinfo(host, NULL, &hints, &res); 209 if (r != 0) 210 eprintf("getaddrinfo %s: %s\n", host, gai_strerror(r)); 211 212 memcpy(&dst, res->ai_addr, sizeof(dst)); 213 freeaddrinfo(res); 214 215 /* try opening raw icmp socket first, fallback to dgram */ 216 sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); 217 if (sock < 0) { 218 sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP); 219 if (sock < 0) 220 eprintf("socket:"); 221 is_raw = 0; 222 } 223 224 if (ttl > 0) { 225 if (setsockopt(sock, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl)) < 0) 226 eprintf("setsockopt IP_TTL:"); 227 } 228 229 /* request that recvfrom returns the ttl value */ 230 optval = 1; 231 if (is_raw) { 232 setsockopt(sock, IPPROTO_IP, IP_RECVTTL, &optval, sizeof(optval)); 233 } 234 235 if (!qflag) { 236 printf("PING %s (%s) %d bytes of data.\n", host, inet_ntoa(dst.sin_addr), size); 237 } 238 239 signal(SIGINT, sigint_handler); 240 241 pfd.fd = sock; 242 pfd.events = POLLIN; 243 244 start_time = get_time_ms(); 245 deadline_ms = deadline > 0 ? start_time + deadline * 1000.0 : 0.0; 246 next_send_ms = start_time; 247 248 rxbuf = emalloc(size + 1024); 249 250 while (keep_running) { 251 now = get_time_ms(); 252 253 if (deadline > 0 && now >= deadline_ms) 254 break; 255 256 if (count > 0 && sent >= count && received >= sent) 257 break; 258 259 if (now >= next_send_ms && (count == 0 || sent < count)) { 260 send_ping(sock, &dst, seq++, size); 261 sent++; 262 next_send_ms = now + interval * 1000.0; 263 } 264 265 timeout_ms = next_send_ms - now; 266 if (deadline > 0) { 267 time_to_deadline = deadline_ms - now; 268 if (time_to_deadline < timeout_ms) 269 timeout_ms = time_to_deadline; 270 } 271 if (timeout_ms < 0) 272 timeout_ms = 0; 273 274 if (count > 0 && sent >= count) 275 timeout_ms = 2000.0; 276 277 p_res = poll(&pfd, 1, (int)timeout_ms); 278 if (p_res < 0) { 279 if (errno == EINTR) 280 continue; 281 eprintf("poll:\n"); 282 } 283 284 if (p_res > 0 && (pfd.revents & POLLIN)) { 285 fromlen = sizeof(from); 286 n = recvfrom(sock, rxbuf, size + 1024, 0, (struct sockaddr *)&from, &fromlen); 287 if (n < 0) { 288 if (errno == EINTR || errno == EAGAIN) 289 continue; 290 eprintf("recvfrom:\n"); 291 } 292 293 hlen = 0; 294 if (is_raw) { 295 struct ip *ip = (struct ip *)rxbuf; 296 hlen = ip->ip_hl << 2; 297 if (n < hlen + (int)sizeof(*icmp)) 298 continue; 299 } 300 icmp = (struct icmphdr *)(rxbuf + hlen); 301 302 if (icmp->type == ICMP_ECHOREPLY 303 && (!is_raw || ntohs(icmp->un.echo.id) == (getpid() & 0xffff))) { 304 received++; 305 rtt = get_time_ms(); 306 if (n - hlen - (int)sizeof(*icmp) >= (int)sizeof(struct timeval)) { 307 memcpy(&sent_tv, rxbuf + hlen + sizeof(*icmp), sizeof(sent_tv)); 308 sent_ms = (double)sent_tv.tv_sec * 1000.0 + (double)sent_tv.tv_usec / 1000.0; 309 rtt -= sent_ms; 310 if (rtt < min_rtt) 311 min_rtt = rtt; 312 if (rtt > max_rtt) 313 max_rtt = rtt; 314 sum_rtt += rtt; 315 if (!qflag) { 316 printf( 317 "%d bytes from %s: " 318 "icmp_seq=%d ttl=%d " 319 "time=%.3f ms\n", 320 (int)n, 321 inet_ntoa(from.sin_addr), 322 ntohs(icmp->un.echo.sequence), 323 is_raw ? ((struct ip *)rxbuf)->ip_ttl : 64, 324 rtt 325 ); 326 } 327 } else { 328 if (!qflag) { 329 printf( 330 "%d bytes from %s: " 331 "icmp_seq=%d ttl=%d\n", 332 (int)n, 333 inet_ntoa(from.sin_addr), 334 ntohs(icmp->un.echo.sequence), 335 is_raw ? ((struct ip *)rxbuf)->ip_ttl : 64 336 ); 337 } 338 } 339 } 340 } 341 } 342 343 free(rxbuf); 344 close(sock); 345 346 print_stats(host, sent, received, min_rtt, max_rtt, sum_rtt); 347 348 return received > 0 ? 0 : 1; 349 }