Abhishek Choubey
Abhishek Choubey

Reputation: 883

Browser displays HTML code as it is, written by a C program to a socket

I have the following C program, that writes text in HTML syntax to port 5010.

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h> 

int main(int argc, char *argv[])
{
    int listenfd = 0, connfd = 0;
    struct sockaddr_in serv_addr; 

    char* sendBuff="<html><head><title>page 1</title></head></html>";
    time_t ticks; 
    uint32_t ip = 0;
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&serv_addr, '0', sizeof(serv_addr));
    //memset(sendBuff, '0', sizeof(sendBuff)); 
    inet_aton("127.0.0.1", (struct in_addr*)&ip);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(ip);
    serv_addr.sin_port = htons(5010); 

    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); 

    listen(listenfd, 10); 

    while(1)
    {
        connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); 
    fprintf(stderr, "New connection \n");
        ticks = time(NULL);
        //snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
        write(connfd, sendBuff, strlen(sendBuff)); 

        close(connfd);
        sleep(1);
     }
}

And then I issue the following request in my browser's address bar:

127.0.0.1:5010

I was expecting my browser to show the title of page as "page1", but instead it rendered the HTML code as it is. Browser Output

Upvotes: 3

Views: 1709

Answers (1)

b4hand
b4hand

Reputation: 9770

When you type "127.0.0.1:5010" into your browser bar, it assumes the server on the other side is speaking the HTTP protocol. Your browser will automatically change your URL to http://127.0.0.1:5010/. This means the server on the other side must respond with a valid HTTP response.

The HTTP protocol requires you to pass more than just the data that you want to display. For example, here's a server response for a very simple web page:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Connection: close
Content-Length: 89

<!DOCTYPE html>
<html><head><title>page 1</title></head><body>Hello World!</body></html>

Furthermore, your browser cannot know to display the content as HTML unless you actually send it a Content-Type header with an appropriate value.

For more details on the HTTP protocol, you may want to read the corresponding Wikipedia article or the following 6 RFCs which actually define the current HTTP 1.1 specification:

Upvotes: 5

Related Questions