network.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* This file is part of libepistle.
  2. *
  3. * libepistle is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU Lesser General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * libepistle is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU Lesser General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Lesser General Public License
  14. * along with libepistle. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include <unistd.h>
  17. #include "network.h"
  18. int
  19. network_server(uint16_t port, int backlog, Err *err)
  20. {
  21. int reuseaddr = 1;
  22. struct sockaddr_in6 addr = { 0 };
  23. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  24. if (sock < 0) {
  25. err_std(err);
  26. return -1;
  27. }
  28. addr.sin6_family = AF_INET6;
  29. addr.sin6_port = htons(port);
  30. addr.sin6_addr = in6addr_any;
  31. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  32. &reuseaddr, sizeof(reuseaddr));
  33. if (bind(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0 ||
  34. listen(sock, backlog < 0 ? SOMAXCONN : backlog) < 0) {
  35. err_std(err);
  36. close(sock);
  37. return -1;
  38. }
  39. return sock;
  40. }
  41. int
  42. network_client(struct in6_addr in6_addr, uint16_t port, Err *err)
  43. {
  44. struct sockaddr_in6 addr = { 0 };
  45. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  46. if (sock < 0) {
  47. err_std(err);
  48. return -1;
  49. }
  50. addr.sin6_family = AF_INET6;
  51. addr.sin6_port = htons(port);
  52. addr.sin6_addr = in6_addr;
  53. if (connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
  54. err_std(err);
  55. close(sock);
  56. return -1;
  57. }
  58. return sock;
  59. }