Reputation: 5386
I'm trying to figure out what an IP packet contains using raw sockets. I'm writing in C++ and so far I've been able to print out an entire packet using the following code:
int CreateRawSocket(int protocol_to_sniff)
{
int s
if(s = socket(PF_PACKET, SOCK_RAW, htons(protocol_to_sniff)
{
perror("Error creating raw socket");
exit(1);
}
return s;
}
void PrintPacket(unsigned char *packet, int len)
{
unsigned char *p = packet;
printf("\n--Packet start--\n");
while(len--)
{
printf("%.2x ", *p);
p++;
}
printf("\n--Packet end--\n");
}
int main()
{
int length, s, packets_to_sniff;
unsigned char *packet_buffer;
s = CreateRawSocket(ETH_P_ALL);
if(s == -1)
{
perror("Error creating socket");
exit(1);
}
packet_buffer = (unsigned char *)malloc(1518);
printf("Number of packets to sniff?: ");
cin >> packets_to_sniff;
while(packets_to_sniff--)
{
length = recvfrom(s, packet_buffer, ETH_FRAME_LEN, 0, NULL, NULL);
if(length == -1)
{
perror("Error recieving packet");
exit(1);
}
else
{
printf("Packet number: " + packets_to_sniff);
PrintPacket(packet_buffer, length);
}
}
}
I have a Virtual Machine pinging the one I'm programming on and all my program seems to print is the MAC frames of the packet which I think are in Hex..
I would like to be able to read the the IP Header and find out which fields of the Header contains what information.
Something a little like:
printf(packet_buffer[0]);
printf(packet_buffer[1]);
I've tried that without getting any output which seems wierd.
Best of regards!
Upvotes: 0
Views: 2969
Reputation: 4312
as you know the size of IP header, you could print each byte as hex:
for (int i = 0; i < ip_header_length; i++)
printf("%02x ", packet_buffer[i]);
Upvotes: 1
Reputation:
Have you tried dumping the contents of packet_buffer in hex, rather than treating it as a string consisting of printable characters?
Upvotes: 0