I'm trying to write a web server but with the code I have but I'm getting the GET/ht.html can't be opened. The html document (ht.html) is supposed to be opened in the browser. What can be added or changed so it'll work properly?

The code I have is:

#include <sys/types.h>
#include <sys/fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>

#define SERVER_PORT 12345       /* arbitrary, but client and server must agree */
#define BUF_SIZE 4096           /* block transfer size */
#define QUEUE_SIZE 10
#define PATH 128

int main(int argc, char *argv[])
  int s, b, l, fd, sa, bytes, on = 1;
  char buf[BUF_SIZE];           /* buffer for outgoing file */
  struct sockaddr_in channel;       /* hold's IP address */

  /* Build address structure to bind to socket. */
  memset(&channel, 0, sizeof(channel)); /* zero channel */
  channel.sin_family = AF_INET;
  channel.sin_addr.s_addr = htonl(INADDR_ANY);
  channel.sin_port = htons(SERVER_PORT);

  /* Passive open. Wait for connection. */
  s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); /* create socket */
  if (s < 0) fatal("socket failed");
  setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));

  b = bind(s, (struct sockaddr *) &channel, sizeof(channel));
  if (b < 0) fatal("bind failed");

  l = listen(s, QUEUE_SIZE);        /* specify queue size */
  if (l < 0) fatal("listen failed");

  /* Socket is now set up and bound. Wait for connection and process it. */

        sa = accept(s, 0, 0);       /* block for connection request */


            int n=0, i=0;

            char filename[PATH];

            char err_msg[] = "Could not open";
            char newline[] = "\n";


            while((n=read(sa, &filename[i], (PATH - i)))>0)

            if(!(fd=fopen(filename, "r")))
                write(sa, err_msg, strlen(err_msg));
                write(sa, filename, strlen(filename));
                write(sa, newline, strlen(newline));

            while((write(sa, recvline, fread(recvline, sizeof(char), MAXLINE, fd))))



fatal(char *string)
  printf("%s", string);

A simple page request from a browser looks something like

GET /example.html HTTP/1.1
Host: www.example.com

(actually with an extra newline at the end of it but the code parser on this site wont show it.)

At line 68 - 74 of your code you make no attempt to parse this request but just treat the received data as though the browser has sent you a file name. Since the browser did not just send you a file name unsurprisingly you code fails to open the file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.