#define _GNU_SOURCE
#include <errno.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/poll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <time.h>
#include <arpa/inet.h>
#include <stdarg.h>
#include <Conn.h>
/* Global variables */
static unsigned short debug = 20;
static FILE *Logf = NULL;
static char *log_file = "timeout.log";
static void Log(unsigned short level, char *format, ...)
{
va_list ap;
if (level > debug)
return;
va_start(ap, format);
vfprintf(Logf, format, ap);
va_end(ap);
}
static void c_connected(struct Conn *C)
{
Log(4, "%s(A connection was estabilished on slot %d)\n",
__FUNCTION__, C->slot);
Conn_close(C);
}
static void c_close(struct Conn *C)
{
Log(5, "%s(Slot %d will close)\n",
__FUNCTION__, C->slot);
free(C->private);
}
static void c_data(struct Conn *C)
{
char *dump;
if (debug >= 8) {
dump = Conn_dump(C->ibuf + C->ibuf_head, Conn_qlen(C));
Log(8, "data: recv: %s\n", dump);
free(dump);
}
Conn_close(C);
Conn_eatall(C);
}
static void c_error(struct Conn *C)
{
Log(0, "%s Slot=%u [%s]\n",
__FUNCTION__, C->slot, Conn_strerror());
}
int main(void)
{
char *stat;
int ret;
struct Conn *C;
Logf = fopen(log_file, "a+");
if (!Logf) {
fprintf(stderr, "Cannot open log file [%s] [%s]\n",
log_file, strerror(errno));
return 1;
}
if (debug > 0)
setlinebuf(Logf);
Log(0, "Starting...\n");
Log(0, "\tLogFile=%s Debug=%d\n", log_file, debug);
Conn_debug(Logf, debug);
ret = Conn_init(0);
if (ret == -1) {
Log(0, "%s", Conn_strerror());
return 1;
}
Conn_connected_cb = c_connected;
Conn_data_cb = c_data;
Conn_close_cb = c_close;
Conn_error_cb = c_error;
/* Connect to google */
C = Conn_connect(PF_INET, SOCK_STREAM, "209.85.129.104", 80);
if (C == NULL) {
Log(0, "Error calling Conn_connect [%s]!\n",
Conn_strerror());
return 1;
}
/* Force a timeout for connect */
Conn_set(C, CONN_PARA_CONN_TIMEOUT, 1);
while (1) {
ret = Conn_poll(10);
if (ret == -1) {
Log(0, "Error in poll [%s]!\n",
Conn_strerror());
break;
}
if (ret == 0) {
Log(0, "Finish work!\n");
break;
}
if (debug >= 9) {
stat = Conn_status(0);
Log(9, "%s\n", stat);
free(stat);
}
}
return 0;
}