NS2 MATERIALS:
Wireless
Packet Sniffer,
Wireless
cards, drivers in Linux,
Wireless
tutorials -- (1), (2)
INTERESTING MATERIALS
How
to construct packets and store in PCAP format?
In this tutorial, first I will discuss on how to create an ethernet-ip
packet in C and then store the packet in PCAP format.
Packet
Construction
Step
1:Create ethernet and ip frame structures
ETHERNET
FRAME STRUCTURE:
Destination
MAC --> Source MAC -->Type --> Payload
(6bytes)
(6 bytes)
(2bytes) (46-1500bytes)
The
destination MAC address and Source MAC address are of 6 bytes. The
type field is of
2
bytes and protocol type of the packet.
Now
we define the ethernet structure as follows:
/**ethernet.h**/
struct
ethernet {
unsigned
char dst_mac[6]; //6 bytes
unsigned
char src_mac[6]; //6 bytes
uint16_t
type; //2 bytes
}__attribute__(__packed__);
IP
FRAME STRUCTURE:
/**ip.h**/
struct
ipheader{
uint8_t
vhl; //version and IHL
uint8_t
tos;
uint16_t
tlen;
uint16_t
id;
uint16_t
flag_offset; // flags and offset
uint8_t
ttl;
uint8_t
protocol;
uint16_t
checksum;
unsigned
char dip[4];
unsigned
char sip[4];
}__attribute__(__packed__);
Step
2: Copy the data into these structures
For
example, let
unsigned
char DestMAC = {0x00,0xff,0xaa,0xab,0xfe,0x11};
we
can use memcpy to copy this DestMAC into dst_mac in ethernet structure
memcpy(eth.dst_mac,
DestMAC,6);
Similarly
copy the data into each field of the structure
Step
3: Encapsulate the IP structure in the payload area of ethernet frame.
Destination
MAC --> Source MAC -->Type --> Payload
(6bytes)
(6 bytes)
(2bytes) (46-1500bytes)
IP header \
PCAP:
PCAP
format is the main capture file format used in Tcpdump, Wireshark
(ethereal), snort etc. The file format is very simple and the file has
a Global Header followed by the Packet Header and Packet Data.
/**Global
Header Structure**/
struct pcap_header
{
unsigned int magic;
//0xa1b2c3d4
unsigned short int ver_major; //
value = 2;
unsigned short int ver_minor;
//value =4
unsigned int thiszone;
unsigned int sigfigs;
unsigned int snaplen;
unsigned int network; // if 1 =
Ethernet
};
struct pcap_recordhdr {
unsigned int ts_sec;
unsigned int ts_usec;
unsigned int in_len;
unsigned int or_len;
};
.
.
//
write_pcap_header() is called once to write the Global header.
write_pcap_header();
while(1)
{
write_pcap_data
(buffer,length);
}
void
write_pcap_header
{
struct pcap_header fh;
//
Fill the structure with data and copy into the file.
fwrite(&fh, sizeof(fh), 1, file);
}
void
write_pcap_data(data,length)
{
struct pcap_recordhdr
ph;
//
Fill the structure with data and copy into the file.
fwrite(&ph,1,sizeof(ph),file);
//Writing the data onto File using fwrite
fwrite(data,1,length,file);
}
data
is the pointer to the buffer that contains packet headers and packet data.
The pcap file can be opened by Hex editor, ethereal, tcpdump etc.
References: