Bind () returned permission denied C

I am trying to write a program that takes a port number as a command line argument and starts an HTTP server. I am passing listenfd to accept () for this. However, I get a permission denied from my open_listenfd () and then a handle error from Accept ().

The open_listenfd () and Accept () functions are copied from http://csapp.cs.cmu.edu/2e/ics2/code/src/csapp.c

I pass port 100 to the program:

int open_listenfd(int port)
{
   int listenfd, optval=1;
   struct sockaddr_in serveraddr;

   /* Create a socket descriptor */
   if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
      return -1;

   /* Eliminates "Address already in use" error from bind */
   if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int)) < 0)
      return -1;

   /* Listenfd will be an endpoint for all requests to port on any IP address for this host */
   bzero((char *) &serveraddr, sizeof(serveraddr));
   serveraddr.sin_family = AF_INET;
   serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
   serveraddr.sin_port = htons((unsigned short)port);
   if (bind(listenfd, (SA *)&serveraddr, sizeof(serveraddr)) < 0)
      return -1;

   /* Make it a listening socket
    * ready to accept connection
    * requests */
   if (listen(listenfd, LISTENQ) < 0)
      return -1;

   return listenfd;
}

int Open_listenfd(int port)
{
   int rc;

   if ((rc = open_listenfd(port)) < 0)
      unix_error("Open_listenfd error");
   return rc;
}

int Accept(int s, struct sockaddr *addr, socklen_t *addrlen)
{
   int rc;

   if ((rc = accept(s, addr, addrlen)) < 0)
      unix_error("Accept error");
   return rc;
}

int main(int argc, char **argv) {
   int listenfd, connfd, port, clientlen;
   struct sockaddr_in clientaddr;
   struct hostent *phost;
   char *phostaddr;

   port = atoi(argv[1]);

   listenfd = Open_listenfd(port);

   clientlen = sizeof(clientaddr);

   connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
   printf("%d\n", connfd);
   printf("%s\n", strerror(errno));

   return 0;
}

      

Another question: if I want the server to constantly accept () connections, read the form requests

GET /path HTTP/1.1\r\n\r\n

      

How to do it?

+3


source to share


1 answer


Ports below 1024 are considered privileged on Linux, so you need the root user to open a socket on ports <Thousand twenty-four



+6


source







All Articles