Using the original socket to implement a simple acquisition network packet and reverse parsing IP,MAC address # include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#define BUFFER_MAX 2048
int main (int argc, char **argv)
{
int rawsock;
Char Buffer[buffer_max];
Char *ethhead;
Char *iphead;
Char *phead;
Creating the original socket
if ((Rawsock=socket (Pf_packet,sock_raw,htons (ETH_P_IP))) <0) {
printf ("Error:create raw socket!\n");
Exit (0);
}
Long Framecount = 0;
while (1) {
int readnum = Recvfrom (rawsock,buffer,2048,0,null,null);
if (readnum<42) {
printf ("Error:header is incomplete!\n");
Exit (0);
}
ethhead= (char*) buffer;
Phead=ethhead;
int ethernetmask=0xff;
framecount++;
printf ("---------------analysisipacket[%d]---------------\ n", Framecount);
printf ("MAC:");
int i=6;
for (; i<=11;i++)
printf ("%.2x:", phead[i]ðernetmask);
printf ("------->");
for (i=0;i<=5;i++)
printf ("%.2x:", phead[i]ðernetmask);
printf ("\ n");
iphead=ethhead+14;
phead=iphead+12;
printf ("IP:");
for (i=0;i<=3;i++) {
printf ("%d", phead[i]ðernetmask);
if (i!=3)
printf (".");
}
printf ("------->");
for (i=4;i<=7;i++) {
printf ("%d", phead[i]ðernetmask);
if (i!=7)
printf (".");
}
printf ("\ n");
int prototype= (IPHEAD+9) [0];
phead=iphead+20;
printf ("Protocol:");
Switch (prototype) {
Case IPPROTO_ICMP:
printf ("icmp\n");
Break
Case IPPROTO_IGMP:
printf ("igmp\n");
Break
Case IPPROTO_IPIP:
printf ("IP");
Break
Case IPPROTO_TCP:
printf ("Tcp|source Port:%u |", (PHEAD[0]<<8) &0xff00|phead[1]&0xff);
printf ("Destport:%u\n", (phead[2]<<8) &0xff00|phead[3]&0xff);
Break
Case IPPROTO_UDP:
printf ("Udp|source Port:%u |", (PHEAD[0]<<8) &0xff00|phead[1]&0xff);
printf ("Destport:%u\n", (phead[2]<<8) &0xff00|phead[3]&0xff);
Break
Case Ipproto_raw:
printf ("raw\n");
Break
Default
printf ("unkown\n");
}
printf ("-----------------end--------------------");
}
return 0;
}
Using raw sockets to implement a simple acquisition network packet