Advertisement
Mayk0

#; Original PING [Code]

May 17th, 2013
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.37 KB | None | 0 0
  1. /*
  2. * P I N G . C
  3. *
  4. * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
  5. * measure round-trip-delays and packet loss across network paths.
  6. *
  7. * Author -
  8. * Mike Muuss
  9. * U. S. Army Ballistic Research Laboratory
  10. * December, 1983
  11. * Modified at Uc Berkeley
  12. *
  13. * Changed argument to inet_ntoa() to be struct in_addr instead of u_long
  14. * DFM BRL 1992
  15. *
  16. * Status -
  17. * Public Domain. Distribution Unlimited.
  18. *
  19. * Bugs -
  20. * More statistics could always be gathered.
  21. * This program has to run SUID to ROOT to access the ICMP socket.
  22. */
  23.  
  24. #include <stdio.h>
  25. #include <errno.h>
  26. #include <sys/time.h>
  27.  
  28. #include <sys/param.h>
  29. #include <sys/types.h>
  30. #include <sys/socket.h>
  31. #include <sys/file.h>
  32.  
  33. #include <netinet/in_systm.h>
  34. #include <netinet/in.h>
  35. #include <netinet/ip.h>
  36. #include <netinet/ip_icmp.h>
  37. #include <netdb.h>
  38.  
  39. #define MAXWAIT 10 /* max time to wait for response, sec. */
  40. #define MAXPACKET 4096 /* max packet size */
  41. #define VERBOSE 1 /* verbose flag */
  42. #define QUIET 2 /* quiet flag */
  43. #define FLOOD 4 /* floodping flag */
  44. #ifndef MAXHOSTNAMELEN
  45. #define MAXHOSTNAMELEN 64
  46. #endif
  47.  
  48. u_char packet[MAXPACKET];
  49. int i, pingflags, options;
  50. extern int errno;
  51.  
  52. int s; /* Socket file descriptor */
  53. struct hostent *hp; /* Pointer to host info */
  54. struct timezone tz; /* leftover */
  55.  
  56. struct sockaddr whereto;/* Who to ping */
  57. int datalen; /* How much data */
  58.  
  59. char usage[] =
  60. "Usage: ping [-dfqrv] host [packetsize [count [preload]]]n";
  61.  
  62. char *hostname;
  63. char hnamebuf[MAXHOSTNAMELEN];
  64.  
  65. int npackets;
  66. int preload = 0; /* number of packets to "preload" */
  67. int ntransmitted = 0; /* sequence # for outbound packets = #sent */
  68. int ident;
  69.  
  70. int nreceived = 0; /* # of packets we got back */
  71. int timing = 0;
  72. int tmin = 999999999;
  73. int tmax = 0;
  74. int tsum = 0; /* sum of all times, for doing average */
  75. int finish(), catcher();
  76. char *inet_ntoa();
  77.  
  78. /*
  79. * M A I N
  80. */
  81. main(argc, argv)
  82. char *argv[];
  83. {
  84. struct sockaddr_in from;
  85. char **av = argv;
  86. struct sockaddr_in *to = (struct sockaddr_in *) &whereto;
  87. int on = 1;
  88. struct protoent *proto;
  89.  
  90. argc--, av++;
  91. while (argc > 0 && *av[0] == '-') {
  92. while (*++av[0]) switch (*av[0]) {
  93. case 'd':
  94. options |= SO_DEBUG;
  95. break;
  96. case 'r':
  97. options |= SO_DONTROUTE;
  98. break;
  99. case 'v':
  100. pingflags |= VERBOSE;
  101. break;
  102. case 'q':
  103. pingflags |= QUIET;
  104. break;
  105. case 'f':
  106. pingflags |= FLOOD;
  107. break;
  108. }
  109. argc--, av++;
  110. }
  111. if(argc < 1 || argc > 4) {
  112. printf(usage);
  113. exit(1);
  114. }
  115.  
  116. bzero((char *)&whereto, sizeof(struct sockaddr) );
  117. to->sin_family = AF_INET;
  118. to->sin_addr.s_addr = inet_addr(av[0]);
  119. if(to->sin_addr.s_addr != (unsigned)-1) {
  120. strcpy(hnamebuf, av[0]);
  121. hostname = hnamebuf;
  122. } else {
  123. hp = gethostbyname(av[0]);
  124. if (hp) {
  125. to->sin_family = hp->h_addrtype;
  126. bcopy(hp->h_addr, (caddr_t)&to->sin_addr, hp->h_length);
  127. hostname = hp->h_name;
  128. } else {
  129. printf("%s: unknown host %sn", argv[0], av[0]);
  130. exit(1);
  131. }
  132. }
  133.  
  134. if( argc >= 2 )
  135. datalen = atoi( av[1] );
  136. else
  137. datalen = 64-8;
  138. if (datalen > MAXPACKET) {
  139. fprintf(stderr, "ping: packet size too largen");
  140. exit(1);
  141. }
  142. if (datalen >= sizeof(struct timeval)) /* can we time 'em? */
  143. timing = 1;
  144.  
  145. if (argc >= 3)
  146. npackets = atoi(av[2]);
  147.  
  148. if (argc == 4)
  149. preload = atoi(av[3]);
  150.  
  151. ident = getpid() & 0xFFFF;
  152.  
  153. if ((proto = getprotobyname("icmp")) == NULL) {
  154. fprintf(stderr, "icmp: unknown protocoln");
  155. exit(10);
  156. }
  157.  
  158. if ((s = socket(AF_INET, SOCK_RAW, proto->p_proto)) < 0) {
  159. perror("ping: socket");
  160. exit(5);
  161. }
  162. if (options & SO_DEBUG) {
  163. if(pingflags & VERBOSE)
  164. printf("...debug on.n");
  165. setsockopt(s, SOL_SOCKET, SO_DEBUG, &on, sizeof(on));
  166. }
  167. if (options & SO_DONTROUTE) {
  168. if(pingflags & VERBOSE)
  169. printf("...no routing.n");
  170. setsockopt(s, SOL_SOCKET, SO_DONTROUTE, &on, sizeof(on));
  171. }
  172.  
  173. if(to->sin_family == AF_INET) {
  174. printf("PING %s (%s): %d data bytesn", hostname,
  175. inet_ntoa(to->sin_addr), datalen); /* DFM */
  176. } else {
  177. printf("PING %s: %d data bytesn", hostname, datalen );
  178. }
  179. setlinebuf( stdout );
  180.  
  181. signal( SIGINT, finish );
  182. signal(SIGALRM, catcher);
  183.  
  184. /* fire off them quickies */
  185. for(i=0; i < preload; i++)
  186. pinger();
  187.  
  188. if(!(pingflags & FLOOD))
  189. catcher(); /* start things going */
  190.  
  191. for (;;) {
  192. int len = sizeof (packet);
  193. int fromlen = sizeof (from);
  194. int cc;
  195. struct timeval timeout;
  196. int fdmask = 1 << s;
  197.  
  198. timeout.tv_sec = 0;
  199. timeout.tv_usec = 10000;
  200.  
  201. if(pingflags & FLOOD) {
  202. pinger();
  203. if( select(32, &fdmask, 0, 0, &timeout) == 0)
  204. continue;
  205. }
  206. if ( (cc=recvfrom(s, packet, len, 0, &from, &fromlen)) < 0) {
  207. if( errno == EINTR )
  208. continue;
  209. perror("ping: recvfrom");
  210. continue;
  211. }
  212. pr_pack( packet, cc, &from );
  213. if (npackets && nreceived >= npackets)
  214. finish();
  215. }
  216. /*NOTREACHED*/
  217. }
  218.  
  219. /*
  220. * C A T C H E R
  221. *
  222. * This routine causes another PING to be transmitted, and then
  223. * schedules another SIGALRM for 1 second from now.
  224. *
  225. * Bug -
  226. * Our sense of time will slowly skew (ie, packets will not be launched
  227. * exactly at 1-second intervals). This does not affect the quality
  228. * of the delay and loss statistics.
  229. */
  230. catcher()
  231. {
  232. int waittime;
  233.  
  234. pinger();
  235. if (npackets == 0 || ntransmitted < npackets)
  236. alarm(1);
  237. else {
  238. if (nreceived) {
  239. waittime = 2 * tmax / 1000;
  240. if (waittime == 0)
  241. waittime = 1;
  242. } else
  243. waittime = MAXWAIT;
  244. signal(SIGALRM, finish);
  245. alarm(waittime);
  246. }
  247. }
  248.  
  249. /*
  250. * P I N G E R
  251. *
  252. * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
  253. * will be added on by the kernel. The ID field is our UNIX process ID,
  254. * and the sequence number is an ascending integer. The first 8 bytes
  255. * of the data portion are used to hold a UNIX "timeval" struct in VAX
  256. * byte-order, to compute the round-trip time.
  257. */
  258. pinger()
  259. {
  260. static u_char outpack[MAXPACKET];
  261. register struct icmp *icp = (struct icmp *) outpack;
  262. int i, cc;
  263. register struct timeval *tp = (struct timeval *) &outpack[8];
  264. register u_char *datap = &outpack[8+sizeof(struct timeval)];
  265.  
  266. icp->icmp_type = ICMP_ECHO;
  267. icp->icmp_code = 0;
  268. icp->icmp_cksum = 0;
  269. icp->icmp_seq = ntransmitted++;
  270. icp->icmp_id = ident; /* ID */
  271.  
  272. cc = datalen+8; /* skips ICMP portion */
  273.  
  274. if (timing)
  275. gettimeofday( tp, &tz );
  276.  
  277. for( i=8; i<datalen; i++) /* skip 8 for time */
  278. *datap++ = i;
  279.  
  280. /* Compute ICMP checksum here */
  281. icp->icmp_cksum = in_cksum( icp, cc );
  282.  
  283. /* cc = sendto(s, msg, len, flags, to, tolen) */
  284. i = sendto( s, outpack, cc, 0, &whereto, sizeof(struct sockaddr) );
  285.  
  286. if( i < 0 || i != cc ) {
  287. if( i<0 ) perror("sendto");
  288. printf("ping: wrote %s %d chars, ret=%dn",
  289. hostname, cc, i );
  290. fflush(stdout);
  291. }
  292. if(pingflags == FLOOD) {
  293. putchar('.');
  294. fflush(stdout);
  295. }
  296. }
  297.  
  298. /*
  299. * P R _ T Y P E
  300. *
  301. * Convert an ICMP "type" field to a printable string.
  302. */
  303. char *
  304. pr_type( t )
  305. register int t;
  306. {
  307. static char *ttab[] = {
  308. "Echo Reply",
  309. "ICMP 1",
  310. "ICMP 2",
  311. "Dest Unreachable",
  312. "Source Quench",
  313. "Redirect",
  314. "ICMP 6",
  315. "ICMP 7",
  316. "Echo",
  317. "ICMP 9",
  318. "ICMP 10",
  319. "Time Exceeded",
  320. "Parameter Problem",
  321. "Timestamp",
  322. "Timestamp Reply",
  323. "Info Request",
  324. "Info Reply"
  325. };
  326.  
  327. if( t < 0 || t > 16 )
  328. return("OUT-OF-RANGE");
  329.  
  330. return(ttab[t]);
  331. }
  332.  
  333. /*
  334. * P R _ P A C K
  335. *
  336. * Print out the packet, if it came from us. This logic is necessary
  337. * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
  338. * which arrive ('tis only fair). This permits multiple copies of this
  339. * program to be run without having intermingled output (or statistics!).
  340. */
  341. pr_pack( buf, cc, from )
  342. char *buf;
  343. int cc;
  344. struct sockaddr_in *from;
  345. {
  346. struct ip *ip;
  347. register struct icmp *icp;
  348. register long *lp = (long *) packet;
  349. register int i;
  350. struct timeval tv;
  351. struct timeval *tp;
  352. int hlen, triptime;
  353.  
  354. from->sin_addr.s_addr = ntohl( from->sin_addr.s_addr );
  355. gettimeofday( &tv, &tz );
  356.  
  357. ip = (struct ip *) buf;
  358. hlen = ip->ip_hl << 2;
  359. if (cc < hlen + ICMP_MINLEN) {
  360. if (pingflags & VERBOSE)
  361. printf("packet too short (%d bytes) from %sn", cc,
  362. inet_ntoa(ntohl(from->sin_addr))); /* DFM */
  363. return;
  364. }
  365. cc -= hlen;
  366. icp = (struct icmp *)(buf + hlen);
  367. if( (!(pingflags & QUIET)) && icp->icmp_type != ICMP_ECHOREPLY ) {
  368. printf("%d bytes from %s: icmp_type=%d (%s) icmp_code=%dn",
  369. cc, inet_ntoa(ntohl(from->sin_addr)),
  370. icp->icmp_type, pr_type(icp->icmp_type), icp->icmp_code);/*DFM*/
  371. if (pingflags & VERBOSE) {
  372. for( i=0; i<12; i++)
  373. printf("x%2.2x: x%8.8xn", i*sizeof(long),
  374. *lp++);
  375. }
  376. return;
  377. }
  378. if( icp->icmp_id != ident )
  379. return; /* 'Twas not our ECHO */
  380.  
  381. if (timing) {
  382. tp = (struct timeval *)&icp->icmp_data[0];
  383. tvsub( &tv, tp );
  384. triptime = tv.tv_sec*1000+(tv.tv_usec/1000);
  385. tsum += triptime;
  386. if( triptime < tmin )
  387. tmin = triptime;
  388. if( triptime > tmax )
  389. tmax = triptime;
  390. }
  391.  
  392. if(!(pingflags & QUIET)) {
  393. if(pingflags != FLOOD) {
  394. printf("%d bytes from %s: icmp_seq=%d", cc,
  395. inet_ntoa(from->sin_addr),
  396. icp->icmp_seq ); /* DFM */
  397. if (timing)
  398. printf(" time=%d msn", triptime );
  399. else
  400. putchar('n');
  401. } else {
  402. putchar('b');
  403. fflush(stdout);
  404. }
  405. }
  406. nreceived++;
  407. }
  408.  
  409.  
  410. /*
  411. * I N _ C K S U M
  412. *
  413. * Checksum routine for Internet Protocol family headers (C Version)
  414. *
  415. */
  416. in_cksum(addr, len)
  417. u_short *addr;
  418. int len;
  419. {
  420. register int nleft = len;
  421. register u_short *w = addr;
  422. register u_short answer;
  423. register int sum = 0;
  424.  
  425. /*
  426. * Our algorithm is simple, using a 32 bit accumulator (sum),
  427. * we add sequential 16 bit words to it, and at the end, fold
  428. * back all the carry bits from the top 16 bits into the lower
  429. * 16 bits.
  430. */
  431. while( nleft > 1 ) {
  432. sum += *w++;
  433. nleft -= 2;
  434. }
  435.  
  436. /* mop up an odd byte, if necessary */
  437. if( nleft == 1 ) {
  438. u_short u = 0;
  439.  
  440. *(u_char *)(&u) = *(u_char *)w ;
  441. sum += u;
  442. }
  443.  
  444. /*
  445. * add back carry outs from top 16 bits to low 16 bits
  446. */
  447. sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
  448. sum += (sum >> 16); /* add carry */
  449. answer = ~sum; /* truncate to 16 bits */
  450. return (answer);
  451. }
  452.  
  453. /*
  454. * T V S U B
  455. *
  456. * Subtract 2 timeval structs: out = out - in.
  457. *
  458. * Out is assumed to be >= in.
  459. */
  460. tvsub( out, in )
  461. register struct timeval *out, *in;
  462. {
  463. if( (out->tv_usec -= in->tv_usec) < 0 ) {
  464. out->tv_sec--;
  465. out->tv_usec += 1000000;
  466. }
  467. out->tv_sec -= in->tv_sec;
  468. }
  469.  
  470. /*
  471. * F I N I S H
  472. *
  473. * Print out statistics, and give up.
  474. * Heavily buffered STDIO is used here, so that all the statistics
  475. * will be written with 1 sys-write call. This is nice when more
  476. * than one copy of the program is running on a terminal; it prevents
  477. * the statistics output from becomming intermingled.
  478. */
  479. finish()
  480. {
  481. putchar('n');
  482. fflush(stdout);
  483. printf("n----%s PING Statistics----n", hostname );
  484. printf("%d packets transmitted, ", ntransmitted );
  485. printf("%d packets received, ", nreceived );
  486. if (ntransmitted)
  487. if( nreceived > ntransmitted)
  488. printf("-- somebody's printing up packets!");
  489. else
  490. printf("%d%% packet loss",
  491. (int) (((ntransmitted-nreceived)*100) /
  492. ntransmitted));
  493. printf("n");
  494. if (nreceived && timing)
  495. printf("round-trip (ms) min/avg/max = %d/%d/%dn",
  496. tmin,
  497. tsum / nreceived,
  498. tmax );
  499. fflush(stdout);
  500. exit(0);
  501. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement