Search code examples
csocketstcpnetcattcpserver

Testing a TCP/IP server locally


I have written an echo TCP server in C.

I wish to test my code to see if it works.

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

#define BUF_SIZE 500
#define LISTEN_BACKLOG 50

#define handle_error(msg) \
   do { perror(msg); exit(EXIT_FAILURE); } while (0)

int
main(int argc, char *argv[])
{
   struct addrinfo hints;
   struct addrinfo *res, *rp;
   struct sockaddr_storage peer_addr;
   socklen_t peer_addr_len;
   int sfd, cfd;

   if(argc != 3) {
      fprintf(stderr, "Usage: %s address port\n", argv[0]);
      exit(EXIT_FAILURE);
   }

   memset(&hints, 0, sizeof(struct addrinfo));
   hints.ai_family = AF_UNSPEC;
   hints.ai_socktype = SOCK_STREAM;
   hints.ai_flags = AI_PASSIVE;
   hints.ai_protocol = 0;
   hints.ai_addr = NULL;
   hints.ai_next = NULL;

   if(getaddrinfo(argv[1], argv[2], &hints, &res) != 0)
      handle_error("getaddrinfo");

   // Try each socket until we bind
   for(rp = res; rp != NULL; rp = rp->ai_next){
      sfd = socket(rp->ai_family, rp->ai_socktype, 0);
      if(sfd == -1) continue;
      if(bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0) break;
      else close(sfd);
   }

   freeaddrinfo(res);

   if (rp == NULL){
      fprintf(stderr, "Could not bind to any socket\n");
      exit(EXIT_FAILURE);
   }

   // Set the TCP socket to listen state
   if (listen(sfd, LISTEN_BACKLOG) == -1) handle_error("listen");

   for(;;){
      // Accept
      peer_addr_len = sizeof(struct sockaddr_storage);
      cfd = accept(sfd, (struct sockaddr *) &peer_addr, &peer_addr_len);
      if (cfd == -1) handle_error("accept");

      // Fork
      pid_t pid = fork();

      if (pid == 0){
         //Child code
         char buf[BUF_SIZE];
         while(1){
             ssize_t nread = recv(cfd, buf, BUF_SIZE, 0);
             if (nread == 0) {
                 close(cfd);
                 exit(EXIT_SUCCESS);
             } else {
                 ssize_t nsent = send(cfd, buf, nread, 0);
                 if (nsent != nread) fprintf(stderr, "Error sending response");
             }

         }
      } else {
         //Parent code

      }
   }
   close(sfd);
} 

It compiles just fine, but when I try running it as tcp_server 127.0.0.1 80 it gives me the error message Could not bind to any socket.

In my understanding, this should have bound the server to the IPv4 loopback address, port 80, and then I would have been able to interact with it using netcat.

What is going on?


Solution

  • Low-numbered ports are considered privileged by most operating systems. Try with a port like 8000 or 8080.