Skip to content

Instantly share code, notes, and snippets.

@yongboy
Created April 9, 2013 08:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yongboy/5343986 to your computer and use it in GitHub Desktop.
Save yongboy/5343986 to your computer and use it in GitHub Desktop.
test bind local ip with local port
#include <sys/types.h>
#include <sys/time.h>
#include <sys/queue.h>
#include <stdlib.h>
#include <err.h>
#include <event.h>
#include <evhttp.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
#include <pthread.h>
#include <errno.h>
#define BUFSIZE 4096
#define SLEEP_MS 10
char buf[BUFSIZE];
int bytes_recvd = 0;
int chunks_recvd = 0;
void chunkcb(struct evhttp_request *req, void *arg) {
int s = evbuffer_remove( req->input_buffer, &buf, BUFSIZE );
bytes_recvd += s;
chunks_recvd++;
printf(">Chunks: %d\tBytes: %d\n", chunks_recvd, bytes_recvd);
}
void reqcb(struct evhttp_request *req, void *arg) {
fprintf(stderr, ">Now closed\n");
exit(-1);
}
void err_cb(int err){
fprintf(stderr, "setup failed(errno = %d): %s", errno, strerror(errno));
}
int main(int argc, char **argv) {
char server_ip[16] = "";
int server_port = 0;
char local_ip[16] = "";
int local_port = 0;
int ch;
while ((ch = getopt(argc, argv, "h:p:c:o:")) != -1) {
switch (ch) {
case 'h':
printf("remote host is %s\n", optarg);
strncpy(server_ip, optarg, 15);
break;
case 'p':
printf("remote port is %s\n", optarg);
server_port = atoi(optarg);
break;
case 'c':
printf("local ip is %s\n", optarg);
strncpy(local_ip, optarg, 15);
break;
case 'o':
printf("local port is %s\n", optarg);
local_port = atoi(optarg);
break;
}
}
event_init();
event_set_fatal_callback(err_cb);
struct evhttp *evhttp_connection;
struct evhttp_request *evhttp_request;
char path[32];
evhttp_connection = evhttp_connection_new(server_ip, server_port);
evhttp_connection_set_local_address(evhttp_connection, local_ip);
evhttp_connection_set_local_port(evhttp_connection, local_port);
evhttp_set_timeout(evhttp_connection, 864000); // 10 day timeout
evhttp_request = evhttp_request_new(reqcb, NULL);
evhttp_request->chunk_cb = chunkcb;
sprintf(&path, "/test/%d", local_port);
evhttp_make_request( evhttp_connection, evhttp_request, EVHTTP_REQ_GET, path );
evhttp_connection_set_timeout(evhttp_request->evcon, 864000);
event_loop( EVLOOP_NONBLOCK );
usleep(SLEEP_MS * 10);
event_dispatch();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment