Skip to content

Instantly share code, notes, and snippets.

@gkres
Created February 14, 2013 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkres/4952640 to your computer and use it in GitHub Desktop.
Save gkres/4952640 to your computer and use it in GitHub Desktop.
Simple program to get data using HTTP.
#include <iostream>
#include <cstdlib>
#include <event.h>
#include <evhttp.h>
#include <event2/dns.h>
#include <event2/event.h>
using namespace std;
static void request_cb(struct evhttp_request *req, void *state) {
cout << "started request_cb." << endl;
printf("in reqhandler. state == %s\n", (char *) state);
string body;
if (req == NULL) {
cout << "Server returned NULL." << endl;
} else {
cout << "response code:" << req->response_code << endl;
int len = evbuffer_get_length(req->input_buffer);
void *buf = malloc(len);
evbuffer_copyout(req->input_buffer, buf, len);
body = string(static_cast<char*>(buf), len);
free(buf);
cout << "BODY LEN:" << endl << len << endl;
cout << "BODY:" << endl << body << endl;
}
cout << "finished request_cb." << endl;
}
int main(int argc, char *argv[]) {
cout << "ipv6test.cc started " << endl;
//show version used in runtime
const char *libeventver = event_get_version();
cout << "using libevent version:" << libeventver << endl;
//showing debug messages requires libevent compile time debug flags
event_enable_debug_mode();
//event_set_log_callback(logfn);
//prepare request data to use
string url = "/index.html";
//ipv6 data -not working
const char *addr = "[::1]";
string remote_host ="ip6-localhost";
//ipv4 data -working
//const char *addr = "127.0.0.1";
//string remote_host ="localhost";
cout << "initializing libevent subsystem." << endl;
struct event_base* base = event_init();
unsigned int port = 80;
cout << "Connecting to addr:" << addr << " sending header Host:" << remote_host << " fetching url:" << url << endl;
cout << "before creating connection." << endl;
struct evhttp_connection *connection = evhttp_connection_new(addr, port);
if (connection == NULL){
cout << "connection is null - failed new connection" << endl;
}
else
{
cout << "connection is not null " << endl;
}
struct evhttp_request *request;
request = evhttp_request_new(request_cb, NULL);
evhttp_add_header(request->output_headers, "Host", remote_host.c_str());
evhttp_add_header(request->output_headers, "Content-Length", "0");
if (evhttp_make_request(connection, request, EVHTTP_REQ_GET, url.c_str())==-1){
cout << "failed making request" << endl;
}
else
{
cout << "NOT failed" << endl;
};
cout << "after make request" << endl;
event_dispatch();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment