ping.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. *
  22. * This version of ping is adapted from the ping in netkit-base 0.10,
  23. * which is:
  24. *
  25. * Copyright (c) 1989 The Regents of the University of California.
  26. * All rights reserved.
  27. *
  28. * This code is derived from software contributed to Berkeley by
  29. * Mike Muuss.
  30. *
  31. * Original copyright notice is retained at the end of this file.
  32. */
  33. #include <sys/param.h>
  34. #include <sys/socket.h>
  35. #include <sys/file.h>
  36. #include <sys/time.h>
  37. #include <sys/times.h>
  38. #include <sys/signal.h>
  39. #include <netinet/in.h>
  40. #include <netinet/ip.h>
  41. #include <netinet/ip_icmp.h>
  42. #include <arpa/inet.h>
  43. #include <netdb.h>
  44. #include <stdio.h>
  45. #include <stdlib.h>
  46. #include <errno.h>
  47. #include <unistd.h>
  48. #include <string.h>
  49. #include <stdlib.h>
  50. #include "busybox.h"
  51. static const int DEFDATALEN = 56;
  52. static const int MAXIPLEN = 60;
  53. static const int MAXICMPLEN = 76;
  54. static const int MAXPACKET = 65468;
  55. #define MAX_DUP_CHK (8 * 128)
  56. static const int MAXWAIT = 10;
  57. static const int PINGINTERVAL = 1; /* second */
  58. #define O_QUIET (1 << 0)
  59. #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
  60. #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
  61. #define SET(bit) (A(bit) |= B(bit))
  62. #define CLR(bit) (A(bit) &= (~B(bit)))
  63. #define TST(bit) (A(bit) & B(bit))
  64. static void ping(const char *host);
  65. /* common routines */
  66. static int in_cksum(unsigned short *buf, int sz)
  67. {
  68. int nleft = sz;
  69. int sum = 0;
  70. unsigned short *w = buf;
  71. unsigned short ans = 0;
  72. while (nleft > 1) {
  73. sum += *w++;
  74. nleft -= 2;
  75. }
  76. if (nleft == 1) {
  77. *(unsigned char *) (&ans) = *(unsigned char *) w;
  78. sum += ans;
  79. }
  80. sum = (sum >> 16) + (sum & 0xFFFF);
  81. sum += (sum >> 16);
  82. ans = ~sum;
  83. return (ans);
  84. }
  85. /* simple version */
  86. #ifndef CONFIG_FEATURE_FANCY_PING
  87. static char *hostname = NULL;
  88. static void noresp(int ign)
  89. {
  90. printf("No response from %s\n", hostname);
  91. exit(EXIT_FAILURE);
  92. }
  93. static void ping(const char *host)
  94. {
  95. struct hostent *h;
  96. struct sockaddr_in pingaddr;
  97. struct icmp *pkt;
  98. int pingsock, c;
  99. char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];
  100. pingsock = create_icmp_socket();
  101. memset(&pingaddr, 0, sizeof(struct sockaddr_in));
  102. pingaddr.sin_family = AF_INET;
  103. h = xgethostbyname(host);
  104. memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
  105. hostname = h->h_name;
  106. pkt = (struct icmp *) packet;
  107. memset(pkt, 0, sizeof(packet));
  108. pkt->icmp_type = ICMP_ECHO;
  109. pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
  110. c = sendto(pingsock, packet, sizeof(packet), 0,
  111. (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
  112. if (c < 0 || c != sizeof(packet))
  113. bb_perror_msg_and_die("sendto");
  114. signal(SIGALRM, noresp);
  115. alarm(5); /* give the host 5000ms to respond */
  116. /* listen for replies */
  117. while (1) {
  118. struct sockaddr_in from;
  119. size_t fromlen = sizeof(from);
  120. if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
  121. (struct sockaddr *) &from, &fromlen)) < 0) {
  122. if (errno == EINTR)
  123. continue;
  124. bb_perror_msg("recvfrom");
  125. continue;
  126. }
  127. if (c >= 76) { /* ip + icmp */
  128. struct iphdr *iphdr = (struct iphdr *) packet;
  129. pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr */
  130. if (pkt->icmp_type == ICMP_ECHOREPLY)
  131. break;
  132. }
  133. }
  134. printf("%s is alive!\n", hostname);
  135. return;
  136. }
  137. extern int ping_main(int argc, char **argv)
  138. {
  139. argc--;
  140. argv++;
  141. if (argc < 1)
  142. bb_show_usage();
  143. ping(*argv);
  144. return EXIT_SUCCESS;
  145. }
  146. #else /* ! CONFIG_FEATURE_FANCY_PING */
  147. /* full(er) version */
  148. static struct sockaddr_in pingaddr;
  149. static int pingsock = -1;
  150. static int datalen; /* intentionally uninitialized to work around gcc bug */
  151. static long ntransmitted, nreceived, nrepeats, pingcount;
  152. static int myid, options;
  153. static unsigned long tmin = ULONG_MAX, tmax, tsum;
  154. static char rcvd_tbl[MAX_DUP_CHK / 8];
  155. #ifndef CONFIG_FEATURE_FANCY_PING6
  156. static
  157. #endif
  158. struct hostent *hostent;
  159. static void sendping(int);
  160. static void pingstats(int);
  161. static void unpack(char *, int, struct sockaddr_in *);
  162. /**************************************************************************/
  163. static void pingstats(int junk)
  164. {
  165. int status;
  166. signal(SIGINT, SIG_IGN);
  167. printf("\n--- %s ping statistics ---\n", hostent->h_name);
  168. printf("%ld packets transmitted, ", ntransmitted);
  169. printf("%ld packets received, ", nreceived);
  170. if (nrepeats)
  171. printf("%ld duplicates, ", nrepeats);
  172. if (ntransmitted)
  173. printf("%ld%% packet loss\n",
  174. (ntransmitted - nreceived) * 100 / ntransmitted);
  175. if (nreceived)
  176. printf("round-trip min/avg/max = %lu.%lu/%lu.%lu/%lu.%lu ms\n",
  177. tmin / 10, tmin % 10,
  178. (tsum / (nreceived + nrepeats)) / 10,
  179. (tsum / (nreceived + nrepeats)) % 10, tmax / 10, tmax % 10);
  180. if (nreceived != 0)
  181. status = EXIT_SUCCESS;
  182. else
  183. status = EXIT_FAILURE;
  184. exit(status);
  185. }
  186. static void sendping(int junk)
  187. {
  188. struct icmp *pkt;
  189. int i;
  190. char packet[datalen + 8];
  191. pkt = (struct icmp *) packet;
  192. pkt->icmp_type = ICMP_ECHO;
  193. pkt->icmp_code = 0;
  194. pkt->icmp_cksum = 0;
  195. pkt->icmp_seq = ntransmitted++;
  196. pkt->icmp_id = myid;
  197. CLR(pkt->icmp_seq % MAX_DUP_CHK);
  198. gettimeofday((struct timeval *) &packet[8], NULL);
  199. pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));
  200. i = sendto(pingsock, packet, sizeof(packet), 0,
  201. (struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));
  202. if (i < 0)
  203. bb_perror_msg_and_die("sendto");
  204. else if ((size_t)i != sizeof(packet))
  205. bb_error_msg_and_die("ping wrote %d chars; %d expected", i,
  206. (int)sizeof(packet));
  207. signal(SIGALRM, sendping);
  208. if (pingcount == 0 || ntransmitted < pingcount) { /* schedule next in 1s */
  209. alarm(PINGINTERVAL);
  210. } else { /* done, wait for the last ping to come back */
  211. /* todo, don't necessarily need to wait so long... */
  212. signal(SIGALRM, pingstats);
  213. alarm(MAXWAIT);
  214. }
  215. }
  216. static char *icmp_type_name (int id)
  217. {
  218. switch (id) {
  219. case ICMP_ECHOREPLY: return "Echo Reply";
  220. case ICMP_DEST_UNREACH: return "Destination Unreachable";
  221. case ICMP_SOURCE_QUENCH: return "Source Quench";
  222. case ICMP_REDIRECT: return "Redirect (change route)";
  223. case ICMP_ECHO: return "Echo Request";
  224. case ICMP_TIME_EXCEEDED: return "Time Exceeded";
  225. case ICMP_PARAMETERPROB: return "Parameter Problem";
  226. case ICMP_TIMESTAMP: return "Timestamp Request";
  227. case ICMP_TIMESTAMPREPLY: return "Timestamp Reply";
  228. case ICMP_INFO_REQUEST: return "Information Request";
  229. case ICMP_INFO_REPLY: return "Information Reply";
  230. case ICMP_ADDRESS: return "Address Mask Request";
  231. case ICMP_ADDRESSREPLY: return "Address Mask Reply";
  232. default: return "unknown ICMP type";
  233. }
  234. }
  235. static void unpack(char *buf, int sz, struct sockaddr_in *from)
  236. {
  237. struct icmp *icmppkt;
  238. struct iphdr *iphdr;
  239. struct timeval tv, *tp;
  240. int hlen, dupflag;
  241. unsigned long triptime;
  242. gettimeofday(&tv, NULL);
  243. /* check IP header */
  244. iphdr = (struct iphdr *) buf;
  245. hlen = iphdr->ihl << 2;
  246. /* discard if too short */
  247. if (sz < (datalen + ICMP_MINLEN))
  248. return;
  249. sz -= hlen;
  250. icmppkt = (struct icmp *) (buf + hlen);
  251. if (icmppkt->icmp_id != myid)
  252. return; /* not our ping */
  253. if (icmppkt->icmp_type == ICMP_ECHOREPLY) {
  254. ++nreceived;
  255. tp = (struct timeval *) icmppkt->icmp_data;
  256. if ((tv.tv_usec -= tp->tv_usec) < 0) {
  257. --tv.tv_sec;
  258. tv.tv_usec += 1000000;
  259. }
  260. tv.tv_sec -= tp->tv_sec;
  261. triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
  262. tsum += triptime;
  263. if (triptime < tmin)
  264. tmin = triptime;
  265. if (triptime > tmax)
  266. tmax = triptime;
  267. if (TST(icmppkt->icmp_seq % MAX_DUP_CHK)) {
  268. ++nrepeats;
  269. --nreceived;
  270. dupflag = 1;
  271. } else {
  272. SET(icmppkt->icmp_seq % MAX_DUP_CHK);
  273. dupflag = 0;
  274. }
  275. if (options & O_QUIET)
  276. return;
  277. printf("%d bytes from %s: icmp_seq=%u", sz,
  278. inet_ntoa(*(struct in_addr *) &from->sin_addr.s_addr),
  279. icmppkt->icmp_seq);
  280. printf(" ttl=%d", iphdr->ttl);
  281. printf(" time=%lu.%lu ms", triptime / 10, triptime % 10);
  282. if (dupflag)
  283. printf(" (DUP!)");
  284. printf("\n");
  285. } else
  286. if (icmppkt->icmp_type != ICMP_ECHO)
  287. bb_error_msg("Warning: Got ICMP %d (%s)",
  288. icmppkt->icmp_type, icmp_type_name (icmppkt->icmp_type));
  289. }
  290. static void ping(const char *host)
  291. {
  292. char packet[datalen + MAXIPLEN + MAXICMPLEN];
  293. int sockopt;
  294. pingsock = create_icmp_socket();
  295. memset(&pingaddr, 0, sizeof(struct sockaddr_in));
  296. pingaddr.sin_family = AF_INET;
  297. hostent = xgethostbyname(host);
  298. if (hostent->h_addrtype != AF_INET)
  299. bb_error_msg_and_die("unknown address type; only AF_INET is currently supported.");
  300. memcpy(&pingaddr.sin_addr, hostent->h_addr, sizeof(pingaddr.sin_addr));
  301. /* enable broadcast pings */
  302. sockopt = 1;
  303. setsockopt(pingsock, SOL_SOCKET, SO_BROADCAST, (char *) &sockopt,
  304. sizeof(sockopt));
  305. /* set recv buf for broadcast pings */
  306. sockopt = 48 * 1024;
  307. setsockopt(pingsock, SOL_SOCKET, SO_RCVBUF, (char *) &sockopt,
  308. sizeof(sockopt));
  309. printf("PING %s (%s): %d data bytes\n",
  310. hostent->h_name,
  311. inet_ntoa(*(struct in_addr *) &pingaddr.sin_addr.s_addr),
  312. datalen);
  313. signal(SIGINT, pingstats);
  314. /* start the ping's going ... */
  315. sendping(0);
  316. /* listen for replies */
  317. while (1) {
  318. struct sockaddr_in from;
  319. socklen_t fromlen = (socklen_t) sizeof(from);
  320. int c;
  321. if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,
  322. (struct sockaddr *) &from, &fromlen)) < 0) {
  323. if (errno == EINTR)
  324. continue;
  325. bb_perror_msg("recvfrom");
  326. continue;
  327. }
  328. unpack(packet, c, &from);
  329. if (pingcount > 0 && nreceived >= pingcount)
  330. break;
  331. }
  332. pingstats(0);
  333. }
  334. extern int ping_main(int argc, char **argv)
  335. {
  336. char *thisarg;
  337. datalen = DEFDATALEN; /* initialized here rather than in global scope to work around gcc bug */
  338. argc--;
  339. argv++;
  340. options = 0;
  341. /* Parse any options */
  342. while (argc >= 1 && **argv == '-') {
  343. thisarg = *argv;
  344. thisarg++;
  345. switch (*thisarg) {
  346. case 'q':
  347. options |= O_QUIET;
  348. break;
  349. case 'c':
  350. if (--argc <= 0)
  351. bb_show_usage();
  352. argv++;
  353. pingcount = atoi(*argv);
  354. break;
  355. case 's':
  356. if (--argc <= 0)
  357. bb_show_usage();
  358. argv++;
  359. datalen = atoi(*argv);
  360. break;
  361. default:
  362. bb_show_usage();
  363. }
  364. argc--;
  365. argv++;
  366. }
  367. if (argc < 1)
  368. bb_show_usage();
  369. myid = getpid() & 0xFFFF;
  370. ping(*argv);
  371. return EXIT_SUCCESS;
  372. }
  373. #endif /* ! CONFIG_FEATURE_FANCY_PING */
  374. /*
  375. * Copyright (c) 1989 The Regents of the University of California.
  376. * All rights reserved.
  377. *
  378. * This code is derived from software contributed to Berkeley by
  379. * Mike Muuss.
  380. *
  381. * Redistribution and use in source and binary forms, with or without
  382. * modification, are permitted provided that the following conditions
  383. * are met:
  384. * 1. Redistributions of source code must retain the above copyright
  385. * notice, this list of conditions and the following disclaimer.
  386. * 2. Redistributions in binary form must reproduce the above copyright
  387. * notice, this list of conditions and the following disclaimer in the
  388. * documentation and/or other materials provided with the distribution.
  389. *
  390. * 3. <BSD Advertising Clause omitted per the July 22, 1999 licensing change
  391. * ftp://ftp.cs.berkeley.edu/pub/4bsd/README.Impt.License.Change>
  392. *
  393. * 4. Neither the name of the University nor the names of its contributors
  394. * may be used to endorse or promote products derived from this software
  395. * without specific prior written permission.
  396. *
  397. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  398. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  399. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  400. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  401. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  402. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  403. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  404. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  405. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  406. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  407. * SUCH DAMAGE.
  408. */