/src/udp.c

https://github.com/hilbix/misc · C · 47 lines · 40 code · 7 blank · 0 comment · 4 complexity · 74bc29078fad4e4219e3161eeca5e0e9 MD5 · raw file

  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <sys/socket.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8. #include <netdb.h>
  9. void
  10. oops(const char *s)
  11. {
  12. perror(s);
  13. exit(1);
  14. }
  15. int
  16. main(int argc, char **argv)
  17. {
  18. int fd;
  19. struct addrinfo *ret, hint;
  20. const char *host, *port, *text;
  21. size_t len;
  22. if ((fd = socket(AF_INET, SOCK_DGRAM, 0))<0)
  23. oops("no socket");
  24. host = argc>1 ? argv[1] : "localhost";
  25. port = argc>2 ? argv[2] : "1111";
  26. text = argc>3 ? argv[3] : "hello world";
  27. len = strlen(text);
  28. memset(&hint, 0, sizeof hint);
  29. hint.ai_family = AF_UNSPEC;
  30. hint.ai_flags = AI_IDN;
  31. if (getaddrinfo(host, port, &hint, &ret))
  32. oops("cannot resolve");
  33. for (;;)
  34. {
  35. if (sendto(fd, text, len, 0, ret->ai_addr, ret->ai_addrlen)!=len)
  36. oops("send error");
  37. write(1, ".", 1);
  38. usleep(100000);
  39. }
  40. }