Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5.  
  6. #include <unistd.h>
  7. #include <sys/types.h>
  8. #include <sys/socket.h>
  9. #include <netdb.h>
  10. #include <netinet/ip_icmp.h>
  11. #include <netinet/in.h>
  12. #include <arpa/inet.h>
  13.  
  14. #include "utils.h"
  15.  
  16. void send_icmp(int sock, struct sockaddr_in *whereto,
  17. struct icmphdr *header, struct icmp_response *response)
  18. {
  19. struct timespec start, end;
  20.  
  21. clock_gettime(CLOCK_MONOTONIC, &start);
  22. int res = sendto(sock, header, sizeof(*header), 0, (struct sockaddr *)whereto, sizeof(*whereto));
  23. DIE(res < 0, "sendto");
  24.  
  25. struct icmphdr rheader;
  26. struct sockaddr_in raddr;
  27. char buffer[256];
  28. socklen_t slength;
  29. res = recv(sock, buffer, sizeof(buffer), 0);
  30. DIE(res < 0, "recv");
  31.  
  32. clock_gettime(CLOCK_MONOTONIC, &end);
  33.  
  34. // XXX should check ihl?
  35. memcpy(&response->header, buffer + 20, 8);
  36.  
  37. response->timeElapsed = (float)(end.tv_sec - start.tv_sec) +
  38. (end.tv_nsec - start.tv_nsec) / 1e9f;
  39. }
  40.  
  41. int ping(int sock, struct sockaddr_in *whereto, int count)
  42. {
  43. int res;
  44.  
  45. struct icmphdr header;
  46.  
  47. int i;
  48. for (i = 0; i < count; i++){
  49. struct icmp_response rez;
  50. header.type = ICMP_ECHO;
  51. //header.checksum = 0;
  52. header.code = 0;
  53. header.un.echo.sequence = i;
  54. header.un.echo.id = i;
  55.  
  56. rez.header = header;
  57. //rez.timeElapsed = 1.0;
  58.  
  59. header.checksum = in_cksum((short *)&header, 8, 0);
  60.  
  61. send_icmp(sock, whereto, &header, &rez);
  62. }
  63.  
  64.  
  65. // TODO build and send packets using "send_icmp"
  66. }
  67.  
  68. int main(int argc, char **argv)
  69. {
  70. int res;
  71.  
  72. if (argc != 3) {
  73. fprintf(stderr, "Usage: %s <count> <ip>\n", argv[0]);
  74. exit(1);
  75. }
  76.  
  77. char *ip_addr, *hostname;
  78. struct sockaddr_in whereto;
  79.  
  80. ip_addr = dns_lookup(argv[2], &whereto);
  81. DIE(ip_addr == NULL, "dns_lookup");
  82.  
  83. hostname = reverse_dns_lookup(ip_addr);
  84. DIE(hostname == NULL, "reverse_dns_lookup");
  85.  
  86. printf("PING %s (%s) ...\n", argv[2], ip_addr);
  87.  
  88. int sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  89. DIE(sock < 0, "socket");
  90.  
  91. int count = atoi(argv[1]);
  92. ping(sock, &whereto, count);
  93.  
  94. return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement