#include <errno.h>
#include <linux/if_ether.h>
#include <net/if.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <time.h>
int main(){
int sock,n; char buffer[2048]; unsigned char *iphead, *ethhead; struct ifreq ethreq;
if((sock=socket(PF_PACKET,SOCK_RAW,htons(ETH_P_IP)))==-1){
perror("socket"); exit(1);
}
ethreq.ifr_flags|=IFF_PROMISC;
strncpy(ethreq.ifr_name,"eth0",IFNAMSIZ);
if (ioctl(sock,SIOCSIFFLAGS,ðreq)==-1){
perror("ioctl"); close(sock); exit(1);
}
while(1){
n=recvfrom(sock,buffer,2048,0,NULL,NULL);
if(n<42){
printf("recvfrom() error\n");exit(0);
}
ethhead = buffer;
printf("Source MAC address: %x:%x:%x:%x:%x:%x\n",ethhead[0],ethhead[1],ethhead[2],ethhead[3],ethhead[4],ethhead[5]);
printf("Destination MAC address: %x:%x:%x:%x:%x:%x\n",ethhead[6],ethhead[7],ethhead[8],ethhead[9],ethhead[10],ethhead[11]);
iphead = buffer+14;
if (*iphead==0x45) {
printf("Source host %d.%d.%d.%d\n",iphead[12],iphead[13],iphead[14],iphead[15]);
printf("Dest host %d.%d.%d.%d\n",iphead[16],iphead[17],iphead[18],iphead[19]);
printf("Source,Dest ports %d,%d\n",(iphead[20]<<8)+iphead[21],(iphead[22]<<8)+iphead[23]);
printf("Layer-4 protocol %d\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n",iphead[9]);
}
}
}
This Post was from: https://www.centos.org/newbb/viewtopic.php?forum=58&topic_id=36585&post_id=158705