/***************************************
* Author : xxx
* Time : 2006-00-00
* function: 检测本机网络
****************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <linux/in.h>
#include <linux/if_ether.h>
#include <net/if.h>
#include <sys/ioctl.h>
#define INTERFACE "eth0"
int Set_Promisc(char *interface,int sock);
void Write_File(FILE *fp,unsigned char *buf,int len);
int main()
{
int sock,size,i,j;
FILE *fp;
unsigned char buffer[2048];
unsigned char *data;
fp = fopen("sniffer.txt","w");
if(!fp)
{
printf("can not open the file/n");
return;
}
if((sock = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_IP))) < 0)
{
printf("socket init error/n");
return -1;
}
Set_Promisc(INTERFACE,sock);
while(1)
{
printf("-------------------/n");
size = recvfrom(sock,buffer,2048,0,NULL,NULL);
printf("%d bytes read/n",size);
if(size < 14)
{
printf("recv error/n");
close(sock);
return -1;
}
Write_File(fp, buffer,size);
printf("the dst MAC is %02x:%02x:%02x:%02x:%02x:%02x/n",buffer[0],buffer[1],buffer[2],
buffer[3],buffer[4],buffer[5]);
printf("the source MAC is %02x:%02x:%02x:%02x:%02x:%02x/n",buffer[6],buffer[7],buffer[8],
buffer[9],buffer[10],buffer[11]);
printf("Packet type is %02x%02x/n",buffer[12],buffer[13]);
data = buffer+14;
size = size - 14;
for(i=0;i<size;i+=16)
{
for(j=i;j<i+16;j++)
{
if(j<size)
printf("%02x ",data[j]);
else
break;
}
printf("/n");
}
}
fclose(fp);
return 0;
}
//设置网卡为混杂模式,使其可以接收到非发往本机的数据包
int Set_Promisc(char *interface,int sock)
{
struct ifreq ifr;
strncpy(ifr.ifr_name,interface,strnlen(interface)+1);
if((ioctl(sock,SIOCGIFFLAGS,&ifr) == -1))
{
printf("Couldn't retrive flags for the interface/n");
exit(0);
}
printf("The interface is ::%s/n",interface);
printf("Retrieved flags from the interface successly/n");
ifr.ifr_flags |= IFF_PROMISC;
if(ioctl(sock,SIOCSIFFLAGS,&ifr) == -1)
{
printf("Could not set the PROMISC flag/n");
exit(0);
}
printf("Setting interface::%s::to promisc/n",interface);
return(0);
}
//写文件
void Write_File(FILE *fp,unsigned char *buf,int len)
{
int i;
int base;
/*
fp = fopen("sniffer.txt","a");
if(!fp)
{
printf("can not open the file/n");
return;
}
*/
fprintf(fp,"%s:%d/n","receive packet:",len);
if(buf[12] == 0x88 && buf[13] == 0x63)
{
fprintf(fp,"%s/n""the PPPoE discovery packet found");
}
for (base=0; base<len; base += 16)
{
for (i=base; i<base+16; i++)
{
if (i < len)
{
fprintf(fp, "%02x ", (unsigned) buf[i]);
}
else
{
fprintf(fp, " ");
}
}
fprintf(fp, " ");
for (i=base; i<base+16; i++)
{
if (i < len)
{
if (isprint(buf[i]))
{
fprintf(fp, "%c", buf[i]);
}
else
{
fprintf(fp, ".");
}
}
else {
break;
}
}
fprintf(fp, "/n");
}
fprintf(fp, "/n");
//fclose(fp);
}