Blog / Home
About
Media Gallery

Welcome
to
Thronic.com

ժʝ_

Socket Listening in C


A server I wrote to receive data from Internet connections.

/*
 *
 *      A Linux socket listener for receiving and saving character
 *      data (null terminated) in client-key ordered text files.
 */

#define SERVER_PORT "3982"
#define MAX_PENDING_CONNECTIONS SOMAXCONN

#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>

int listen_socket, work_socket;
int mail_socket, remote_addr_len;
struct addrinfo hints, *res;
struct sockaddr_storage remote_addr;
char recvBuf[1025];
char ClientKey[11];
FILE* serverLog;

int main()
{
       memset(&hints, 0, sizeof(hints));
       hints.ai_family = AF_INET;
       hints.ai_socktype = SOCK_STREAM;
       hints.ai_flags = AI_PASSIVE;

       getaddrinfo(NULL,SERVER_PORT,&hints,&res);

       /* Initiate the listening socket */
       if ((listen_socket = socket(res->ai_family,
                                   res->ai_socktype,
                                   res->ai_protocol)) == -1)
       {
               printf("Failed to create a listening socket.\n\n");
               return 1;
       }

       /* Bind us to port SERVER_PORT */
       if (bind(listen_socket,
                       res->ai_addr,
                       res->ai_addrlen) == -1)
       {
               printf("Failed bind to %s.\r\n",SERVER_PORT);
               close(listen_socket);
               return 1;
       }

       /* Set up listening */
       if (listen(listen_socket,
                  MAX_PENDING_CONNECTIONS) == -1)
       {
               printf("Failed to set up listening.\n\n");
               close(listen_socket);
               return 1;
       }

       while ((work_socket = accept(listen_socket,
                                    (struct sockaddr*)&remote_addr,
                                    &remote_addr_len)) != -1)
       {

               /* First recv a client key for storage. */
               recv(work_socket, ClientKey, sizeof(ClientKey), 0);

               /* Save log to a local file. */
               serverLog = fopen(ClientKey, "a+");
               while (recv(work_socket,
                           recvBuf,
                           sizeof(recvBuf), 0) > 0)
               {
                       fprintf(serverLog, "%s", recvBuf);
               }

               fclose(serverLog);
               close(work_socket);
       }

       close(listen_socket);
       return 0;
}

Compiling: "gcc -o KGServer KGServer.c".
Execution: "nohup ./KGServer &".
Tested successfully on Debian Linux 5.0 "Lenny".


Original Post: Jan 27th, '22 18:47 CET.

C/C++
π