libfuncs is collection of code (list, queue, circular buffer, io, logging, etc.). https://georgi.unixsol.org/programs/libfuncs/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.c 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Server functions
  3. * Copyright (C) 2006-2010 Unix Solutions Ltd.
  4. *
  5. * Released under MIT license.
  6. * See LICENSE-MIT.txt for license terms.
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <unistd.h>
  11. #include <string.h>
  12. #include <errno.h>
  13. #include <netdb.h>
  14. #include <sys/types.h>
  15. #include <sys/socket.h>
  16. #include <netinet/in.h>
  17. #include <arpa/inet.h>
  18. void daemonize(char *pidfile) {
  19. if (!pidfile)
  20. return;
  21. printf("Daemonizing.\n");
  22. pid_t pid = fork();
  23. if (pid > 0) {
  24. FILE *F = fopen(pidfile,"w");
  25. if (F) {
  26. fprintf(F,"%i\n",pid);
  27. fclose(F);
  28. }
  29. exit(0);
  30. }
  31. // Child process continues...
  32. setsid(); // request a new session (job control)
  33. if (!freopen("/dev/null", "r", stdin)) return;
  34. if (!freopen("/dev/null", "w", stdout)) return;
  35. if (!freopen("/dev/null", "w", stderr)) return;
  36. }
  37. void init_server_socket(char *bind_addr, int bind_port, struct sockaddr_in *server, int *server_socket) {
  38. char *binded;
  39. struct hostent *host_ptr;
  40. *server_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  41. if (*server_socket == -1) {
  42. perror("socket(server_socket)");
  43. exit(1);
  44. }
  45. int j = 1;
  46. if (setsockopt(*server_socket, SOL_SOCKET, SO_REUSEADDR,(const char *) &j, sizeof(j))<0) {
  47. perror("setsockopt(SO_REUSEADDR)");
  48. exit(1);
  49. }
  50. memset(server, 0, sizeof(struct sockaddr_in));
  51. if (!bind_addr) {
  52. binded = "*";
  53. server->sin_addr.s_addr = htonl(INADDR_ANY);
  54. } else {
  55. host_ptr = gethostbyname(bind_addr);
  56. if (!host_ptr) {
  57. fprintf(stderr,"Error can't resolve bind address: %s\n", bind_addr);
  58. exit(1);
  59. }
  60. memcpy(&server->sin_addr, host_ptr->h_addr, sizeof(server->sin_addr));
  61. binded = inet_ntoa(server->sin_addr);
  62. }
  63. /* Bind to server socket */
  64. fprintf(stderr, "Binding to %s:%i\t", binded, bind_port);
  65. if (strcmp(binded,"*")==0)
  66. fprintf(stderr,"\t");
  67. server->sin_family = AF_INET;
  68. server->sin_port = htons(bind_port);
  69. if (bind(*server_socket, (struct sockaddr *)server, sizeof(struct sockaddr_in)) < 0) {
  70. perror("bind(server_socket)");
  71. exit(1);
  72. }
  73. if (listen(*server_socket, 256) < 0) {
  74. perror("listen()");
  75. exit(1);
  76. }
  77. fputs("[OK]\n",stderr);
  78. }