|
/**********************************结果如下:********************/
2005-8-24 15:25:58
length:216
Source host : 218.193.10.123
Dest host : 218.193.10.255
Source,Dest ports : 138,138
Layer-4 protocol : 17
2
2005-8-24 15:25:59
length:92
Source host : 218.193.10.123
Dest host : 218.193.10.255
Source,Dest ports : 137,137
Layer-4 protocol : 17
3
2005-8-24 15:25:59
length:92
Source host : 218.193.10.20
Dest host : 218.193.10.255
Source,Dest ports : 137,137
Layer-4 protocol : 17
/***************************************源代码:*******************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/in.h>
#include <linux/if_ether.h>
#include <net/if.h>
#include <time.h>
int
main(int argc, char **argv) {
int wholength;
int sock, n,step=0;
char buffer[4096];
unsigned char *iphead , *ethhead;
struct ifreq ethreq; /* the strcut of the ether */
time_t timep; /*get the system time */
int td[11];
struct tm *p;
FILE *fp;/*store the data*/
void settd(struct tm *p,int *td);
/* open the file */
if( ( fp=fopen("hh.log","a") ) == NULL)
{
fprintf(stderr, "can not open log\n");
exit(0);
}
/* open a socket to get the data */
if ( (sock=socket(PF_PACKET, SOCK_RAW,htons(ETH_P_IP)))<0) {
perror("socket");
exit(1);
}
/* Set the network card in promiscuos mode */
strncpy(ethreq.ifr_name,"eth0",IFNAMSIZ);
if (ioctl(sock,SIOCGIFFLAGS,ðreq)==-1) {
perror("ioctl");
close(sock);
exit(1);
}
ethreq.ifr_flags|=IFF_PROMISC;
if (ioctl(sock,SIOCSIFFLAGS,ðreq)==-1) {
perror("ioctl");
close(sock);
exit(1);
}
while (1) {
time(&timep);
p=gmtime(&timep);
settd(p,td);
fprintf(fp,"%d-%d-%d %d:%d:%d\n",td[0],td[1],td[2],td[3],td[4],td[5]);
n = recvfrom(sock,buffer,4096,0,NULL,NULL);
fprintf(fp,"length:%d \n",n);
/* Check to see if the packet contains at least
* complete Ethernet (14), IP (20) and TCP/UDP
* (8) headers.
*/
if (n<42) {
perror("recvfrom():");
printf("Incomplete packet (errno is %d)\n",errno);
close(sock);
exit(0
}
/* get the data from buffer[4996] */
iphead = buffer+14; /* Skip Ethernet header */
if (*iphead==0x45) { /* Double check for IPv4
* and no options presnt */
fprintf(fp,"Source host : %d.%d.%d.%d\n",
iphead[12],iphead[13],
iphead[14],iphead[15]);
fprintf(fp,"Dest host : %d.%d.%d.%d\n",
iphead[16],iphead[17],
iphead[18],iphead[19]);
fprintf(fp,"Source,Dest ports : %d,%d\n",
(iphead[20]<<8)+iphead[21],
(iphead[22]<<8)+iphead[23]);
fprintf(fp,"Layer-4 protocol : %d\n",iphead[9]);
}
}
fclose(fp);
return 0;
}
void settd(struct tm *p,int *td)
{
int i;
td[0]=p->tm_year+1900;
td[1]=p->tm_mon+1;
if(p->tm_hour>15)
{
td[2]=p->tm_mday+1;
td[3]=p->tm_hour-16;
}
else
{
td[2]=p->tm_mday;
td[3]=p->tm_hour+8;
}
td[4]=p->tm_min;
td[5]=p->tm_sec;
td[6]=p->tm_wday+1;
} |
|