Guest User

recvdns.c by vincesafe based on Paul Krzyzanowski's work

a guest
Jan 20th, 2014
207
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* recvdns.c version alpha 1
  2. This code is under CC BY-NC-SA 3.0 license.
  3. For more information, please visit the link below:
  4. https://creativecommons.org/licenses/by-nc-sa/3.0/legalcode
  5.  
  6. Ce code est sous licence CC BY-NC-SA 3.0.
  7. Plus d'informations à l'adresse suivante :
  8. https://creativecommons.org/licenses/by-nc-sa/3.0/fr/legalcode
  9.  
  10. By vincesafe,
  11. based on "demo-udp-03: udp-recv: a simple udp server" by Paul Krzyzanowski
  12. http://vincesafe.fr/
  13. https://twitter.com/vincesafe
  14.  
  15. */
  16.  
  17. #include <stdlib.h>
  18. #include <stdio.h>
  19. #include <string.h>
  20. #include <netdb.h>
  21. #include <sys/socket.h>
  22. #include <arpa/inet.h>
  23.  
  24. #define SERVICE_PORT 53
  25. #define BUFSIZE 2048
  26.  
  27. int
  28. main(int argc, char **argv)
  29. {
  30.     struct sockaddr_in myaddr;  /* our address */
  31.     struct sockaddr_in remaddr; /* remote address */
  32.     socklen_t addrlen = sizeof(remaddr);        /* length of addresses */
  33.     int recvlen;            /* # bytes received */
  34.     int fd;             /* our socket */
  35.     unsigned char buf[BUFSIZE]; /* receive buffer */
  36.     int i;
  37.  
  38.     /* create a UDP socket */
  39.  
  40.     if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
  41.         perror("cannot create socket\n");
  42.         return 0;
  43.     }
  44.  
  45.     /* bind the socket to any valid IP address and a specific port (set by the client) */
  46.  
  47.     memset((char *)&myaddr, 0, sizeof(myaddr));
  48.     myaddr.sin_family = AF_INET;
  49.     myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  50.     myaddr.sin_port = htons(SERVICE_PORT);
  51.  
  52.     if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
  53.         perror("bind failed");
  54.         return 0;
  55.     }
  56.  
  57.     /* file to store domain */
  58.     FILE *f = NULL;
  59.     f = fopen("req", "wb");
  60.     if(f == NULL) return -1;
  61.  
  62.     /* now loop, receiving data and printing what we received */
  63.     for (;;) {
  64.         printf("waiting on port %d\n", SERVICE_PORT);
  65.         recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
  66.         printf("received %d bytes\n", recvlen);
  67.         if (recvlen > 0) {
  68.             buf[recvlen] = 0;
  69.             printf("received message: \"%s\"\n", buf);
  70.             for(i = 0; i < recvlen; i++)
  71.                 fputc(buf[i], f);
  72.             break;
  73.         }
  74.     }
  75.     /* never exits */
  76. }
RAW Paste Data