How to Flush Raw Af_Packet Socket to Get Correct Filtered Packets

How to flush raw AF_PACKET socket to get correct filtered packets

The "bug" you're describing is real and I've seen it at multiple companies in my career. There is something like an "oral tradition" around this bug that is passed from one network engineer to another. Here are the common fixes:

  1. Just call recv on the socket until it is empty
  2. Double-filter by filtering packets in usermode as well as using the bpf
  3. Use the zero-bpf technique just like libpcap where you apply an empty bpf first, then empty the socket, and then apply the real bpf.

I've written about this problem extensively on my blog to try and codify the oral tradition around this bug into a concrete recommendation and best-practice.

AF_PACKET raw IP packets with SOCK_DGRAM require fragmenting?

After development, I can confirm that if you are using an AF_PACKET socket with SOCK_DGRAM for IP packets, you do have to manually handle the fragmenting. I tried to write a 4000 byte UDP datagram, and received a "message size too long" error.

sending raw eth packets. when should i close sockets?

Keep that socket open as long as you have frames to send or receive. Close the socket with normal close(2). Here's another raw sockets tutorial for you - http://www.tenouk.com/Module43a.html

shutdown(2) only makes sense with TCP, not at all relevant here.

Edit 0:

There's no connection, you are talking ethernet here.

Do yourself a favor and read this book - TCP/IP Illustrated, Volume 1: The Protocols. by W. Richard Stevens - will save you ton of confusion.

Is ethernet checksum exposed via AF_PACKET?

No, you do not need to include the CRC.

When using a packet socket in Linux using socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL) ), you must provide the layer 2 header when sending. This is defined by struct ether_header in netinet/if_ether.h and includes the destination host, source host, and type. The frame check sequence is not included, nor is the preamble, start of frame delimiter, or trailer. These are added by the hardware.



Related Topics



Leave a reply



Submit