This is a mirror of official site: http://jasper-net.blogspot.com/

Packet Sniffer Code in C using Linux Sockets (BSD)

| Thursday, April 5, 2012
To code a sniffer in C (Linux) the steps would be :

1. Create a Raw Socket.
2. Put it in a recvfrom loop.

A raw socket when put in recvfrom receives all incoming packets. The following code shows an example of such a sniffer. Note that it sniffs only incoming packets. For sniffing all traffic on a network a packet capture library like libpcap can be used.

Code : sniffer.c

#include<stdio.h> //For standard things
#include<stdlib.h> //malloc
#include<string.h> //memset
#include<netinet/ip_icmp.h> //Provides declarations for icmp header
#include<netinet/udp.h> //Provides declarations for udp header
#include<netinet/tcp.h> //Provides declarations for tcp header
#include<netinet/ip.h> //Provides declarations for ip header
#include<sys/socket.h>
#include<arpa/inet.h>

void ProcessPacket(unsigned char* , int);
void print_ip_header(unsigned char* , int);
void print_tcp_packet(unsigned char* , int);
void print_udp_packet(unsigned char * , int);
void print_icmp_packet(unsigned char* , int);
void PrintData (unsigned char* , int);

int sock_raw;
FILE *logfile;
int tcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;
struct sockaddr_in source,dest;

int main()
{
int saddr_size , data_size;
struct sockaddr saddr;
struct in_addr in;

unsigned char *buffer = (unsigned char *)malloc(65536); //Its Big!

logfile=fopen("log.txt","w");
if(logfile==NULL) printf("Unable to create file.");
printf("Starting...\n");
//Create a raw socket that shall sniff
sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
if(sock_raw < 0)
{
printf("Socket Error\n");
return 1;
}
while(1)
{
saddr_size = sizeof saddr;
//Receive a packet

Read more: BinaryTides
QR: Inline image 1

Posted via email from Jasper-net

0 comments: