views:

405

answers:

3

I have created a raw socket which takes all IPv4 packets from data link layer (with data link layer header removed). And for reading the packets I use recvfrom.

My doubt is: Suppose due to some scheduling done by OS, my process was asleep for 1 sec. When it woke up,it did recvfrom (with number of bytes to be received say 1000) on this raw socket (with the intention of receiving only one IPv4 packet and say the size of this packet is 380 bytes). And suppose many network applications were also running simultaneously during this time, so all IPv4 packets must have been queued in the receive buffer of this socket. So now recvfrom will return all 1000 bytes (with other IPv4 packets from 381th byte onwards) bcoz it has enough data in its buffer to return. Although my program was meant to understand only one IPv4 packet

So how to prevent this thing? Should I read byte by byte and parse each byte but it is very inefficient.

+1  A: 

IIRC, recvfrom() will only return one packet at a time, even if there are more in the queue.

abyx
A: 

can you please post your code !!!!

neeraj
A: 

Raw sockets operate at the packet layer, there is no concept of data streams.

You might be interested in recvmmsg() if you want to read multiple packets in one system call. Recent Linux kernels only, there is no equivalent send side implementation.

Steve-o