This C program implements a simple server using TCP (Transmission...

September 1, 2025 at 08:34 AM

/* A simple server in the internet domain using TCP The port number is passed as an argument */ #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #include <string.h> #include <unistd.h> void error(char *msg) { perror(msg); exit(1); } int main(int argc, char *argv[]) { int sockfd, newsockfd, portno, clilen; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; int n; if (argc < 2) { fprintf(stderr,"ERROR, no port provided\n"); exit(1); } /* create socket */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); /* fill in port number to listen on. IP address can be anything (INADDR_ANY) */ bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); /* bind socket to this port number on this machine */ if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); /* listen for incoming connection requests */ listen(sockfd,5); clilen = sizeof(cli_addr); /* accept a new request, create a newsockfd */ newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); /* read message from client */ bzero(buffer,256); n = read(newsockfd,buffer,255); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n",buffer); /* send reply to client */ n = write(newsockfd,"I got your message",18); if (n < 0) error("ERROR writing to socket"); return 0; }

This C program implements a simple server using TCP (Transmission Control Protocol). Here's a line-by-line explanation of what the code does:

  1. Setup and Error Handling:

    • The error() function is defined to print error messages and terminate the program.
  2. Main Function:

    • Argument Check:

      • The program checks if a port number is provided as a command-line argument. If not, it prints an error message and exits.
    • Socket Creation:

      • A socket is created using the socket() function with these parameters:
        • AF_INET: Indicates an IPv4 internet domain.
        • SOCK_STREAM: Specifies a TCP (stream-based) connection.
      • If the socket() call fails, an error is reported, and the program exits.
    • Bind to Port:

      • The serv_addr structure is initialized using the provided port number:
        • sin_family is set to AF_INET for IPv4.
        • sin_addr is set to INADDR_ANY, allowing the server to listen on all network interfaces.
        • sin_port is set to the specified port number (converted to network byte order using htons()).
      • The bind() function associates the socket with the specified IP address and port number.
      • If binding fails, an error is reported, and the program exits.
    • Listen for Connections:

      • The listen() function is called to mark the socket as a passive socket, ready to accept incoming connection requests.
      • A backlog of 5 is specified, meaning up to 5 pending connections are queued.
    • Accept Incoming Connections:

      • The accept() function waits for a client to connect. Once a client connects, it creates a new socket (newsockfd) specific to the connection with that client.
      • If accept() fails, an error is reported, and the program exits.
    • Communication with the Client:

      • Read From Client:
        • The read() function reads data sent by the client into a buffer.
        • If reading fails, an error is reported, and the program exits.
        • After a successful read, the received message is printed to the server's standard output.
      • Send a Reply:
        • The write() function sends a response back to the client: "I got your message".
        • If writing fails, an error is reported, and the program exits.
    • Return:

      • The program completes successfully and exits.

Summary:

This program is a basic example of a TCP server. The server:

  1. Accepts a port number as an argument and binds to it.
  2. Waits for a client to connect.
  3. Reads a message from the client and prints it to the server terminal.
  4. Sends a response ("I got your message") to the client.

It serves as an introductory implementation of socket programming in C to demonstrate TCP communication.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node