#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 <linux/if_ether.h>
#include <Conn.h>
/* Global variables */
static unsigned short debug = 9;
static FILE *Logf = NULL;
static char *log_file = "raw.log";
static int port = 9000;
static int maxconn = 0;
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 s_close(struct Conn *C)
{
Log(5, "%s (A connection will be closed [%s] on slot %d)\n",
__FUNCTION__, C->addr, C->slot);
}
static void s_data(struct Conn *C)
{
char *dump;
char *p;
int len;
struct timeval tv;
p = Conn_ibuf(C);
len = Conn_qlen(C);
Conn_last_time(C, &tv);
dump = Conn_dumphex(p, len);
Log(8, "%s: recv %d bytes at %d.%06d on slot %d: [%s]\n",
__FUNCTION__, len, tv.tv_sec, tv.tv_usec, C->slot, dump);
free(dump);
Conn_eatall(C);
}
static void s_error(struct Conn *C)
{
Log(1, "%s slot=%d C=%p [%s]\n",
__FUNCTION__, C == NULL ? -1 : C->slot, (void *) C,
Conn_strerror());
}
int main(void)
{
struct Conn *I4;
int ret;
struct timeval start;
int loops = 0;
Logf = fopen(log_file, "w");
if (!Logf) {
fprintf(stderr, "Cannot open log file [%s] [%s]\n",
log_file, strerror(errno));
return 1;
}
if (debug > 0)
setlinebuf(Logf);
daemon(0, 0);
gettimeofday(&start, NULL);
Log(0, "\nStarting at %ld...\n", start.tv_sec);
Log(0, "\tPort=%d\n", port);
Log(0, "\tLogFile=%s Debug=%d\n", log_file, debug);
/* set library output debug */
Conn_debug(Logf, debug);
Conn_default_ibuf = 10240;
Conn_default_obuf = 10240;
ret = Conn_init(maxconn);
if (ret == -1) {
Log(0, "%s", Conn_strerror());
return 1;
}
Log(9, "Try to register IPv4 socket...\n");
I4 = Conn_socket(PF_PACKET, SOCK_RAW, ETH_P_IP);
if (I4 == NULL) {
Log(0, "Cannot create socket (%s)!\n",
Conn_strerror());
return 1;
}
ret = Conn_set_cb(I4, CONN_CB_CLOSE, s_close);
if (ret != 0) {
Log(0, "ERROR: Cannot set cb for 'close'!\n");
return 1;
}
ret = Conn_set_cb(I4, CONN_CB_ERROR, s_error);
if (ret != 0) {
Log(0, "ERROR: Cannot set cb for 'error'!\n");
return 1;
}
ret = Conn_set_cb(I4, CONN_CB_DATA, s_data);
if (ret != 0) {
Log(0, "ERROR: Cannot set cb for 'data'!\n");
return 1;
}
while (1) {
ret = Conn_poll(10000);
if (ret == -1) {
Log(0, "Error calling Conn_poll [%s]!\n",
Conn_strerror());
return 1;
}
loops++;
if (ret == 0)
break;
/*
if (loops > 1000000)
break;
*/
}
Log(0, "Finish!\n\n");
return 0;
}