Hi guys, I'm trying to learn a bit about sockets programming, so I made a little sniffer.
Here is the code:
Code:
#include <netinet/in.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/tcp.h>
// Creating socket and declaring struct of IP protocol
int main(void) {
int s;
struct sockaddr_in dir = {AF_INET, 0, 0 };
char buff[1024];
int len = sizeof(dir);
struct ip *ip1 = (struct ip* ) (buff+ sizeof (dir));
//Not necesary, it tells that you must to be root
if (geteuid() != 0) {
printf("You have to be root!\n");
exit(0);
}
//Error
if ((s = socket(AF_INET, SOCK_RAW, 6)) < 0){
printf ("Error creating socket\n");
exit (0);
}
// It starts to listen for packets
printf("Waiting for packets...\n");
while (1) {
bzero(buff, 1024);
//If it recieves a packet, the user will be informed
while (recvfrom(s, buff, 1024, 0, (struct sockaddr_in*) &dir,
&len) > 0){
unsigned char *srcBytes = (unsigned char*)&ip1->ip_src;
printf ("I got a packet!\t ip: %s", inet_ntoa(ip1->ip_src));
}
}
}
So, I have a notification when a packet is recieved, but the IP I got is wrong. What can I do to get the real IP of every packet?
Thanks