版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stSahana/article/details/79585391
/*
Copyright (c) 1999 Rafal Wojtczuk <[email protected]>. All rights reserved.
See the file COPYING for license details.
*/
/*
在原示例代码的基础上做了修改,使得可以一次性打印一个TCP流的数据。
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "nids.h"
#include <sys/file.h>
#define int_ntoa(x) inet_ntoa(*((struct in_addr *)&x))
#define LENGTH 0x0FFFFFFF
// struct tuple4 contains addresses and port numbers of the TCP connections
// the following auxiliary function produces a string looking like
// 10.0.0.1,1024,10.0.0.2,23
char *adres(struct tuple4 addr)
{
static char buf[256];
strcpy(buf, int_ntoa(addr.saddr));
sprintf(buf + strlen(buf), ",%i,", addr.source);
strcat(buf, int_ntoa(addr.daddr));
sprintf(buf + strlen(buf), ",%i", addr.dest);
return buf;
}
static FILE *fp = NULL;
void tcp_callback(struct tcp_stream *a_tcp, void ** this_time_not_needed)
{
char buf[1024];
strcpy(buf, adres(a_tcp->addr)); // we put conn params into buf
if (a_tcp->nids_state == NIDS_JUST_EST)
{
a_tcp->client.collect++; // we want data received by a client
a_tcp->server.collect++; // and by a server, too
//a_tcp->server.collect_urg++; // we want urgent data received by a
// server
#ifdef WE_WANT_URGENT_DATA_RECEIVED_BY_A_CLIENT
a_tcp->client.collect_urg++; // if we don't increase this value,
// we won't be notified of urgent data arrival
#endif
fprintf(stderr, "%s ---------------established\n", buf);
return;
}
if (a_tcp->nids_state == NIDS_CLOSE)
{
struct half_stream *client, *server;
client = &a_tcp->client;
server = &a_tcp->server;
fprintf(fp,"\n---------------%s closing start---------------\n", buf);
fprintf(fp,server->data);
fprintf(fp,client->data);
fprintf(fp,"\n---------------%s closing end---------------\n", buf);
fflush(fp);
return;
}
if (a_tcp->nids_state == NIDS_RESET)
{
// connection has been closed by RST
fprintf(stderr, "%s reset\n", buf);
return;
}
if (a_tcp->nids_state == NIDS_DATA)
{
nids_discard(a_tcp, 0);
return;
}
//flock(fp->_fileno, LOCK_UN);
return;
}
int main(int argv, char *argc[])
{
// here we can alter libnids params, for instance:
// nids_params.n_hosts=256;
nids_params.device = argc[1];
struct nids_chksum_ctl temp;
temp.netaddr = inet_addr("0.0.0.0");
temp.mask = inet_addr("0.0.0.0");
temp.action = NIDS_DONT_CHKSUM;
nids_register_chksum_ctl(&temp, 1);
//nids_params.pcap_filter="tcp";
if ((fp = fopen("./logfile", "w+")) == NULL) //打开文件
fprintf(stderr, "failed open file!\n");
if (!nids_init())
{
fprintf(stderr, "%s\n", nids_errbuf);
exit(1);
}
printf("nids_params.multiproc %d", nids_params.multiproc);
nids_register_tcp(tcp_callback);
nids_run();
return 0;
}