traceloop.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "trace.h"
  2. void
  3. traceloop(void)
  4. {
  5. int seq, code, done;
  6. double rtt;
  7. struct rec *rec;
  8. struct timeval tvrecv;
  9. recvfd = Socket(pr->sasend->sa_family, SOCK_RAW, pr->icmpproto);
  10. setuid(getuid()); /* don't need special permissions anymore */
  11. #ifdef IPV6
  12. if (pr->sasend->sa_family == AF_INET6 && verbose == 0) {
  13. struct icmp6_filter myfilt;
  14. ICMP6_FILTER_SETBLOCKALL(&myfilt);
  15. ICMP6_FILTER_SETPASS(ICMP6_TIME_EXCEEDED, &myfilt);
  16. ICMP6_FILTER_SETPASS(ICMP6_DST_UNREACH, &myfilt);
  17. setsockopt(recvfd, IPPROTO_IPV6, ICMP6_FILTER,
  18. &myfilt, sizeof(myfilt));
  19. }
  20. #endif
  21. sendfd = Socket(pr->sasend->sa_family, SOCK_DGRAM, 0);
  22. pr->sabind->sa_family = pr->sasend->sa_family;
  23. sport = (getpid() & 0xffff) | 0x8000; /* our source UDP port # */
  24. sock_set_port(pr->sabind, pr->salen, htons(sport));
  25. Bind(sendfd, pr->sabind, pr->salen);
  26. sig_alrm(SIGALRM);
  27. seq = 0;
  28. done = 0;
  29. for (ttl = 1; ttl <= max_ttl && done == 0; ttl++) {
  30. Setsockopt(sendfd, pr->ttllevel, pr->ttloptname, &ttl, sizeof(int));
  31. bzero(pr->salast, pr->salen);
  32. printf("%2d ", ttl);
  33. fflush(stdout);
  34. for (probe = 0; probe < nprobes; probe++) {
  35. rec = (struct rec *) sendbuf;
  36. rec->rec_seq = ++seq;
  37. rec->rec_ttl = ttl;
  38. Gettimeofday(&rec->rec_tv, NULL);
  39. sock_set_port(pr->sasend, pr->salen, htons(dport + seq));
  40. Sendto(sendfd, sendbuf, datalen, 0, pr->sasend, pr->salen);
  41. if ( (code = (*pr->recv)(seq, &tvrecv)) == -3)
  42. printf(" *"); /* timeout, no reply */
  43. else {
  44. char str[NI_MAXHOST];
  45. if (sock_cmp_addr(pr->sarecv, pr->salast, pr->salen) != 0) {
  46. if (getnameinfo(pr->sarecv, pr->salen, str, sizeof(str),
  47. NULL, 0, 0) == 0)
  48. printf(" %s (%s)", str,
  49. Sock_ntop_host(pr->sarecv, pr->salen));
  50. else
  51. printf(" %s",
  52. Sock_ntop_host(pr->sarecv, pr->salen));
  53. memcpy(pr->salast, pr->sarecv, pr->salen);
  54. }
  55. tv_sub(&tvrecv, &rec->rec_tv);
  56. rtt = tvrecv.tv_sec * 1000.0 + tvrecv.tv_usec / 1000.0;
  57. printf(" %.3f ms", rtt);
  58. if (code == -1) /* port unreachable; at destination */
  59. done++;
  60. else if (code >= 0)
  61. printf(" (ICMP %s)", (*pr->icmpcode)(code));
  62. }
  63. fflush(stdout);
  64. }
  65. printf("\n");
  66. }
  67. }