open.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* $Id: open.c,v 1.6 2001/04/12 19:38:39 kilobug Exp $ */
  2. #include "net_private.h"
  3. int net_connect_to(const char *host, int port, char *err, int errsz,
  4. struct timeval *to)
  5. {
  6. struct sockaddr_in sin;
  7. struct hostent *hp;
  8. int fd;
  9. if ((hp = gethostbyname(host)) == NULL)
  10. {
  11. if (err != NULL)
  12. snprintf(err, errsz, "%s: machine non trouvée.", host);
  13. return -1;
  14. }
  15. bcopy(hp->h_addr, (char *)&sin.sin_addr, hp->h_length);
  16. sin.sin_family = hp->h_addrtype;
  17. sin.sin_port = htons(port);
  18. if ((fd = socket(hp->h_addrtype, SOCK_STREAM, 0)) == -1)
  19. {
  20. if (err != NULL)
  21. snprintf(err, errsz, "socket: %s.", strerror(errno));
  22. return -1;
  23. }
  24. if (to != NULL)
  25. setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, to, sizeof(*to));
  26. if (connect(fd, (struct sockaddr *)&sin, sizeof (sin)) == -1)
  27. {
  28. if (err != NULL)
  29. snprintf(err, errsz, "connect: %s.", strerror(errno));
  30. return -1;
  31. }
  32. return fd;
  33. }
  34. int net_listen_at(int port, int max_con, char *err, int errsz)
  35. {
  36. int fd;
  37. struct sockaddr_in sin;
  38. int value = 1;
  39. if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  40. {
  41. if (err != NULL)
  42. snprintf(err, errsz, "socket: %s.", strerror(errno));
  43. return -1;
  44. }
  45. sin.sin_family = AF_INET;
  46. sin.sin_port = htons(port);
  47. sin.sin_addr.s_addr = INADDR_ANY;
  48. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value));
  49. if (bind(fd, (struct sockaddr *)&sin, sizeof (sin)) == -1)
  50. {
  51. if (err != NULL)
  52. snprintf(err, errsz, "bind: %s.", strerror(errno));
  53. return -1;
  54. }
  55. listen(fd, max_con);
  56. return (fd);
  57. }