qa_sock.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <strings.h>
  4. #include <unistd.h>
  5. #include <errno.h>
  6. #include <sys/types.h>
  7. #include <sys/socket.h>
  8. #include <netdb.h>
  9. #include "qa.h"
  10. #define SOCKET_PROTOCOL 0
  11. #define INVALID_SOCKET (-1)
  12. int init_client(const struct qa_conf *options)
  13. {
  14. struct addrinfo hints;
  15. struct addrinfo *result, *rp;
  16. int s;
  17. int i;
  18. hints.ai_family = AF_UNSPEC;
  19. hints.ai_socktype = SOCK_STREAM;
  20. hints.ai_flags = 0;
  21. hints.ai_protocol = 0;
  22. if ((i=getaddrinfo(options->host, options->port, NULL, &result))) {
  23. fprintf(stderr, "Error: %s\n", gai_strerror(i));
  24. exit(EXIT_FAILURE);
  25. }
  26. for (rp=result; rp; rp = rp->ai_next) {
  27. s = socket(rp->ai_family,
  28. rp->ai_socktype,
  29. rp->ai_protocol);
  30. if (s == INVALID_SOCKET) continue;
  31. if (rp->ai_protocol == SOCK_STREAM) {
  32. i = 0;
  33. i = setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char*) &i, sizeof(i));
  34. if (i < 0) exit(EXIT_FAILURE);
  35. }
  36. if (connect(s, rp->ai_addr, rp->ai_addrlen) != -1) break;
  37. }
  38. if (!rp) exit(EXIT_FAILURE);
  39. return s;
  40. }