tcpserver.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * SPDX-FileCopyrightText: 2019 Helmut Pozimski <helmut@pozimski.eu>
  3. *
  4. * SPDX-License-Identifier: GPL-2.0-only
  5. */
  6. #include <unistd.h>
  7. #include <sys/socket.h>
  8. #include <netinet/in.h>
  9. #include <arpa/inet.h>
  10. /*
  11. * Function: tcpserver_start
  12. * ----------------------------
  13. * Creates a socket and starts to listen on a specified port and address
  14. *
  15. * address: the IPv4 address to listen to
  16. * port: the TCP port to bind to
  17. *
  18. * returns: the socket used for the connection, -1 on failures
  19. */
  20. int tcpserver_start(const char *address, uint16_t port) {
  21. struct sockaddr_in server;
  22. int sock;
  23. server.sin_family = AF_INET;
  24. server.sin_port = htons(port);
  25. inet_pton(AF_INET ,address, &server.sin_addr.s_addr);
  26. if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  27. close(sock);
  28. return -1;
  29. }
  30. if (bind(sock, (struct sockaddr*) &server, sizeof(server)) < 0 ) {
  31. close(sock);
  32. return -1;
  33. }
  34. if (listen(sock, 1) != 0) {
  35. close(sock);
  36. return -1;
  37. }
  38. return sock;
  39. }
  40. /*
  41. * Function: tcpserver_stop
  42. * ------------------------
  43. * Stops the tcp server by closing the socket
  44. *
  45. * sock: the socket used for the connection
  46. *
  47. */
  48. void tcpserver_stop(int sock) {
  49. shutdown(sock, SHUT_RDWR);
  50. close(sock);
  51. }