tcp_connect.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* include tcp_connect */
  2. #include "unp.h"
  3. int
  4. tcp_connect(const char *host, const char *serv)
  5. {
  6. int sockfd, n;
  7. struct addrinfo hints, *res, *ressave;
  8. bzero(&hints, sizeof(struct addrinfo));
  9. hints.ai_family = AF_UNSPEC;
  10. hints.ai_socktype = SOCK_STREAM;
  11. if ( (n = getaddrinfo(host, serv, &hints, &res)) != 0)
  12. err_quit("tcp_connect error for %s, %s: %s",
  13. host, serv, gai_strerror(n));
  14. ressave = res;
  15. do {
  16. sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  17. if (sockfd < 0)
  18. continue; /* ignore this one */
  19. if (connect(sockfd, res->ai_addr, res->ai_addrlen) == 0)
  20. break; /* success */
  21. Close(sockfd); /* ignore this one */
  22. } while ( (res = res->ai_next) != NULL);
  23. if (res == NULL) /* errno set from final connect() */
  24. err_sys("tcp_connect error for %s, %s", host, serv);
  25. freeaddrinfo(ressave);
  26. return(sockfd);
  27. }
  28. /* end tcp_connect */
  29. /*
  30. * We place the wrapper function here, not in wraplib.c, because some
  31. * XTI programs need to include wraplib.c, and it also defines
  32. * a Tcp_connect() function.
  33. */
  34. int
  35. Tcp_connect(const char *host, const char *serv)
  36. {
  37. return(tcp_connect(host, serv));
  38. }