Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C
Tip/Trick

Capture Incoming HTTP Requests to the Web Server

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
27 Nov 2014CPOL1 min read 16.9K   1   1
How to handle post data coming inside an HTTP POST request

Introduction

Few days ago, I had a problem in my CGI application where I must capture the data inside the HTTP POST request coming to the application. The post data are XML data that I must parse and process. In this tip/trick, I will share the idea and the solution I found.

Background

There are few things at least you must know, types of HTTP requests and the HTTP request format, so I suggest you check this detailed article on Wikipedia on the HTTP protocol. I also suggest you review some CGI concepts especially the environment variables.

Using the Code

The idea behind the solution is the CGI environment variables, especially the CONTENT_LENGTH variable. This variable indicates the number of bytes (size) of the data passed within a POST HTTP request.

Any C/C++ application has standard input and output, so when you run the application as CGI, the standard input/output will be through server. So to read the post data, you read the value of CONTENT_LENGTH and then read from stdin. Here is how it is done:

C++
char* len_ = getenv("CONTENT_LENGTH");
if(len_)
{
    long int len = strtol(len_, NULL, 10);
    cout << "LENGTH = " << len << endl;
    char* postdata = (char*)malloc(len + 1);
    if (!postdata) { exit(EXIT_FAILURE); }
    fgets(postdata, len + 1, stdin);
    cout << "DATA = " << postdata << endl;
    free(postdata);
}
else
{
    // No CONTENT_LENGTH, therefore no post data available.
}

Points of Interest

Always check for the value of CONTENT_LENGTH, if no data is available within the request, it becomes null. And always allocate extra location for the null terminator.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Jordan Jordan
I'm a computer engineer, interested in hardware, software and security.

Always trying to learn new topics, to seek a decent computer engineering career!

Comments and Discussions

 
Generalhappy thanksgiving Pin
John Walter27-Nov-14 1:30
John Walter27-Nov-14 1:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.