ping.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * $Id: ping.c,v 1.56 2004/03/15 08:28:48 andersen Exp $
  4. * Mini ping implementation for busybox
  5. *
  6. * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
  7. *
  8. * Adapted from the ping in netkit-base 0.10:
  9. * Copyright (c) 1989 The Regents of the University of California.
  10. * Derived from software contributed to Berkeley by Mike Muuss.
  11. *
  12. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  13. */
  14. #include <sys/param.h>
  15. #include <sys/socket.h>
  16. #include <sys/file.h>
  17. #include <sys/time.h>
  18. #include <sys/times.h>
  19. #include <signal.h>
  20. #include <netinet/in.h>
  21. #include <netinet/ip.h>
  22. #include <netinet/ip_icmp.h>
  23. #include <arpa/inet.h>
  24. #include <netdb.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <errno.h>
  28. #include <unistd.h>
  29. #include <string.h>
  30. #include <stdlib.h>
  31. #include "busybox.h"
  32. enum {
  33. DEFDATALEN = 56,
  34. MAXIPLEN = 60,
  35. MAXICMPLEN = 76,
  36. MAXPACKET = 65468,
  37. MAX_DUP_CHK = (8 * 128),
  38. MAXWAIT = 10,
  39. PINGINTERVAL = 1 /* second */
  40. };
  41. #define O_QUIET (1 << 0)
  42. #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
  43. #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
  44. #define SET(bit) (A(bit) |= B(bit))
  45. #define CLR(bit) (A(bit) &= (~B(bit)))
  46. #define TST(bit) (A(bit) & B(bit))
  47. static void ping(const char *host);
  48. /* common routines */
  49. static int in_cksum(unsigned short *buf, int sz)
  50. {
  51. int nleft = sz;
  52. int sum = 0;
  53. unsigned short *w = buf;
  54. unsigned short ans = 0;
  55. while (nleft > 1) {
  56. sum += *w++;
  57. nleft -= 2;
  58. }
  59. if (nleft == 1) {
  60. *(unsigned char *) (&ans) = *(unsigned char *) w;
  61. sum += ans;
  62. }
  63. sum = (sum >> 16) + (sum & 0xFFFF);
  64. sum += (sum >> 16);
  65. ans = ~sum;
  66. return (ans);
  67. }
  68. /* simple version */
  69. #ifndef CONFIG_FEATURE_FANCY_PING
  70. static char *hostname = NULL;
  71. static void noresp(int ign)
  72. {
  73. printf("No response from %s\n", hostname);
  74. exit(EXIT_FAILURE);
  75. }
  76. static void ping(const char *host)
  77. {
  78. struct hostent *h;
  79. struct sockaddr_in pingaddr;
  80. struct icmp *pkt;
  81. int pingsock, c;
  82. char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
  83. pingsock = create_icmp_socket();
  84. memset(&pingaddr, 0, sizeof(struct sockaddr_in));
  85. pingaddr.sin_family = AF_INET;
  86. h = xgethostbyname(host);
  87. memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
  88. hostname = h->h_name;
  89. pkt = (struct icmp *) packet;
  90. memset(pkt, 0, sizeof(packet));
  91. pkt->icmp_type = ICMP_ECHO;
  92. pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
  93. c = sendto(pingsock, packet, sizeof(packet), 0,
  94. (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
  95. if (c < 0 || c != sizeof(packet))
  96. bb_perror_msg_and_die("sendto");
  97. signal(SIGALRM, noresp);
  98. alarm(5); /* give the host 5000ms to respond */
  99. /* listen for replies */
  100. while (1) {
  101. struct sockaddr_in from;
  102. socklen_t fromlen = sizeof(from);
  103. if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
  104. (struct sockaddr *) &from, &fromlen)) < 0) {
  105. if (errno == EINTR)
  106. continue;
  107. bb_perror_msg("recvfrom");
  108. continue;
  109. }
  110. if (c >= 76) { /* ip + icmp */
  111. struct iphdr *iphdr = (struct iphdr *) packet;
  112. pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
  113. if (pkt->icmp_type == ICMP_ECHOREPLY)
  114. break;
  115. }
  116. }
  117. printf("%s is alive!\n", hostname);
  118. return;
  119. }
  120. int ping_main(int argc, char **argv)
  121. {
  122. argc--;
  123. argv++;
  124. if (argc < 1)
  125. bb_show_usage();
  126. ping(*argv);
  127. return EXIT_SUCCESS;
  128. }
  129. #else /* ! CONFIG_FEATURE_FANCY_PING */
  130. /* full(er) version */
  131. static struct sockaddr_in pingaddr;
  132. static int pingsock = -1;
  133. static int datalen; /* intentionally uninitialized to work around gcc bug */
  134. static long ntransmitted, nreceived, nrepeats, pingcount;
  135. static int myid, options;
  136. static unsigned long tmin = ULONG_MAX, tmax, tsum;
  137. static char rcvd_tbl[MAX_DUP_CHK / 8];
  138. #ifndef CONFIG_FEATURE_FANCY_PING6
  139. static
  140. #endif
  141. struct hostent *hostent;
  142. static void sendping(int);
  143. static void pingstats(int);
  144. static void unpack(char *, int, struct sockaddr_in *);
  145. /**************************************************************************/
  146. static void pingstats(int junk)
  147. {
  148. int status;
  149. signal(SIGINT, SIG_IGN);
  150. printf("\n--- %s ping statistics ---\n", hostent->h_name);
  151. printf("%ld packets transmitted, ", ntransmitted);
  152. printf("%ld packets received, ", nreceived);
  153. if (nrepeats)
  154. printf("%ld duplicates, ", nrepeats);
  155. if (ntransmitted)
  156. printf("%ld%% packet loss\n",
  157. (ntransmitted - nreceived) * 100 / ntransmitted);
  158. if (nreceived)
  159. printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
  160. tmin / 10, tmin % 10,
  161. (tsum / (nreceived + nrepeats)) / 10,
  162. (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
  163. if (nreceived != 0)
  164. status = EXIT_SUCCESS;
  165. else
  166. status = EXIT_FAILURE;
  167. exit(status);
  168. }
  169. static void sendping(int junk)
  170. {
  171. struct icmp *pkt;
  172. int i;
  173. char packet[datalen + sizeof(struct icmp)];
  174. pkt = (struct icmp *) packet;
  175. pkt->icmp_type = ICMP_ECHO;
  176. pkt->icmp_code = 0;
  177. pkt->icmp_cksum = 0;
  178. pkt->icmp_seq = htons(ntransmitted++);
  179. pkt->icmp_id = myid;
  180. CLR(ntohs(pkt->icmp_seq) % MAX_DUP_CHK);
  181. gettimeofday((struct timeval *) &pkt->icmp_dun, NULL);
  182. pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
  183. i = sendto(pingsock, packet, sizeof(packet), 0,
  184. (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
  185. if (i < 0)
  186. bb_perror_msg_and_die("sendto");
  187. else if ((size_t)i != sizeof(packet))
  188. bb_error_msg_and_die("ping wrote %d chars; %d expected", i,
  189. (int)sizeof(packet));
  190. signal(SIGALRM, sendping);
  191. if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
  192. alarm(PINGINTERVAL);
  193. } else { /* done, wait for the last ping to come back */
  194. /* todo, don't necessarily need to wait so long... */
  195. signal(SIGALRM, pingstats);
  196. alarm(MAXWAIT);
  197. }
  198. }
  199. static char *icmp_type_name (int id)
  200. {
  201. switch (id) {
  202. case ICMP_ECHOREPLY: return "Echo Reply";
  203. case ICMP_DEST_UNREACH: return "Destination Unreachable";
  204. case ICMP_SOURCE_QUENCH: return "Source Quench";
  205. case ICMP_REDIRECT: return "Redirect (change route)";
  206. case ICMP_ECHO: return "Echo Request";
  207. case ICMP_TIME_EXCEEDED: return "Time Exceeded";
  208. case ICMP_PARAMETERPROB: return "Parameter Problem";
  209. case ICMP_TIMESTAMP: return "Timestamp Request";
  210. case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
  211. case ICMP_INFO_REQUEST: return "Information Request";
  212. case ICMP_INFO_REPLY: return "Information Reply";
  213. case ICMP_ADDRESS: return "Address Mask Request";
  214. case ICMP_ADDRESSREPLY: return "Address Mask Reply";
  215. default: return "unknown ICMP type";
  216. }
  217. }
  218. static void unpack(char *buf, int sz, struct sockaddr_in *from)
  219. {
  220. struct icmp *icmppkt;
  221. struct iphdr *iphdr;
  222. struct timeval tv, *tp;
  223. int hlen, dupflag;
  224. unsigned long triptime;
  225. gettimeofday(&tv, NULL);
  226. /* check IP header */
  227. iphdr = (struct iphdr *) buf;
  228. hlen = iphdr->ihl << 2;
  229. /* discard if too short */
  230. if (sz < (datalen + ICMP_MINLEN))
  231. return;
  232. sz -= hlen;
  233. icmppkt = (struct icmp *) (buf + hlen);
  234. if (icmppkt->icmp_id != myid)
  235. return; /* not our ping */
  236. if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
  237. u_int16_t recv_seq = ntohs(icmppkt->icmp_seq);
  238. ++nreceived;
  239. tp = (struct timeval *) icmppkt->icmp_data;
  240. if ((tv.tv_usec -= tp->tv_usec) < 0) {
  241. --tv.tv_sec;
  242. tv.tv_usec += 1000000;
  243. }
  244. tv.tv_sec -= tp->tv_sec;
  245. triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
  246. tsum += triptime;
  247. if (triptime < tmin)
  248. tmin = triptime;
  249. if (triptime > tmax)
  250. tmax = triptime;
  251. if (TST(recv_seq % MAX_DUP_CHK)) {
  252. ++nrepeats;
  253. --nreceived;
  254. dupflag = 1;
  255. } else {
  256. SET(recv_seq % MAX_DUP_CHK);
  257. dupflag = 0;
  258. }
  259. if (options & O_QUIET)
  260. return;
  261. printf("%d bytes from %s: icmp_seq=%u", sz,
  262. inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
  263. recv_seq);
  264. printf(" ttl=%d", iphdr->ttl);
  265. printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
  266. if (dupflag)
  267. printf(" (DUP!)");
  268. printf("\n");
  269. } else
  270. if (icmppkt->icmp_type != ICMP_ECHO)
  271. bb_error_msg("Warning: Got ICMP %d (%s)",
  272. icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
  273. fflush(stdout);
  274. }
  275. static void ping(const char *host)
  276. {
  277. char packet[datalen + MAXIPLEN + MAXICMPLEN];
  278. int sockopt;
  279. pingsock = create_icmp_socket();
  280. memset(&pingaddr, 0, sizeof(struct sockaddr_in));
  281. pingaddr.sin_family = AF_INET;
  282. hostent = xgethostbyname(host);
  283. if (hostent->h_addrtype != AF_INET)
  284. bb_error_msg_and_die("unknown address type; only AF_INET is currently supported.");
  285. memcpy(&pingaddr.sin_addr, hostent->h_addr, sizeof(pingaddr.sin_addr));
  286. /* enable broadcast pings */
  287. sockopt = 1;
  288. setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
  289. sizeof(sockopt));
  290. /* set recv buf for broadcast pings */
  291. sockopt = 48 * 1024;
  292. setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
  293. sizeof(sockopt));
  294. printf("PING %s (%s): %d data bytes\n",
  295. hostent->h_name,
  296. inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
  297. datalen);
  298. signal(SIGINT, pingstats);
  299. /* start the ping's going ... */
  300. sendping(0);
  301. /* listen for replies */
  302. while (1) {
  303. struct sockaddr_in from;
  304. socklen_t fromlen = (socklen_t) sizeof(from);
  305. int c;
  306. if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
  307. (struct sockaddr *) &from, &fromlen)) < 0) {
  308. if (errno == EINTR)
  309. continue;
  310. bb_perror_msg("recvfrom");
  311. continue;
  312. }
  313. unpack(packet, c, &from);
  314. if (pingcount > 0 && nreceived >= pingcount)
  315. break;
  316. }
  317. pingstats(0);
  318. }
  319. int ping_main(int argc, char **argv)
  320. {
  321. char *thisarg;
  322. datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
  323. argc--;
  324. argv++;
  325. options = 0;
  326. /* Parse any options */
  327. while (argc >= 1 && **argv == '-') {
  328. thisarg = *argv;
  329. thisarg++;
  330. switch (*thisarg) {
  331. case 'q':
  332. options |= O_QUIET;
  333. break;
  334. case 'c':
  335. if (--argc <= 0)
  336. bb_show_usage();
  337. argv++;
  338. pingcount = atoi(*argv);
  339. break;
  340. case 's':
  341. if (--argc <= 0)
  342. bb_show_usage();
  343. argv++;
  344. datalen = atoi(*argv);
  345. break;
  346. default:
  347. bb_show_usage();
  348. }
  349. argc--;
  350. argv++;
  351. }
  352. if (argc < 1)
  353. bb_show_usage();
  354. myid = getpid() & 0xFFFF;
  355. ping(*argv);
  356. return EXIT_SUCCESS;
  357. }
  358. #endif /* ! CONFIG_FEATURE_FANCY_PING */