Tuesday, September 21, 2010

Packet Capturing using Raw Socket Program

Question

Program using Raw Sockets(like Packet Capturing)

Note

You must have root privilege in order to run this program.

Download Source Code(preferred than viewing it Live on blog)

program

output

Program

(rawudp.c)

#include "unistd.h"
#include "stdio.h"
#include "sys/socket.h"
#include "netinet/ip.h"
#include "netinet/udp.h"

#define PCKT_LEN 8192

// The IP header's structure
struct ipheader {
unsigned char iph_ihl:5, iph_ver:4;
unsigned char iph_tos;
unsigned short int iph_len;
unsigned short int iph_ident;
unsigned char iph_flag;
unsigned short int iph_offset;
unsigned char iph_ttl;
unsigned char iph_protocol;
unsigned short int iph_chksum;
unsigned int iph_sourceip;
unsigned int iph_destip;
};

// UDP header's structure
struct udpheader {
unsigned short int udph_srcport;
unsigned short int udph_destport;
unsigned short int udph_len;
unsigned short int udph_chksum;
};

// Function for checksum calculation.
unsigned short csum(unsigned short *buf, int nwords)
{ //
unsigned long sum;
for(sum=0; nwords>0; nwords--)
sum += *buf++;
sum = (sum >> 16) + (sum &0xffff);
sum += (sum >> 16);
return (unsigned short)(~sum);
}

int main(int argc, char *argv[])
{
int sd;
char buffer[PCKT_LEN];
// Our own headers' structures
struct ipheader *ip = (struct ipheader *) buffer;
struct udpheader *udp = (struct udpheader *) (buffer + sizeof(struct ipheader));
// Source and destination addresses: IP and port
struct sockaddr_in sin, din;
int one = 1;
const int *val = &one;

memset(buffer, 0, PCKT_LEN);

// Create a raw socket with UDP protocol
sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
if(sd < sin_family =" AF_INET;" sin_family =" AF_INET;" sin_port =" htons(atoi(argv[2]));" sin_port =" htons(atoi(argv[4]));" s_addr =" inet_addr(argv[1]);" s_addr =" inet_addr(argv[3]);">iph_ihl = 5;
ip->iph_ver = 4;
ip->iph_tos = 16;
ip->iph_len = sizeof(struct ipheader) + sizeof(struct udpheader);
ip->iph_ident = htons(54321);
ip->iph_ttl = 64; // hops
ip->iph_protocol = 17; // UDP
ip->iph_sourceip = inet_addr(argv[1]);//Source IP address
ip->iph_destip = inet_addr(argv[3]);// destination IP address

// Fabricate the UDP header.
udp->udph_srcport = htons(atoi(argv[2]));//source port
udp->udph_destport = htons(atoi(argv[4]));//destination port
udp->udph_len = htons(sizeof(struct udpheader));
// Calculate the checksum
ip->iph_chksum = csum((unsigned short *)buffer, sizeof(struct ipheader) + sizeof(struct udpheader));

if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < count =" 1;">iph_len, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0)
{
perror("sendto() error");
exit(-1);
}
else
{
printf("Count #%u - sendto() is OK.\n", count);
sleep(2);
}
}
close(sd);
return 0;
}

No comments: