packet(7)

๐Ÿ’– packet(7) โ€” the packet interface, but make it device level ๐Ÿ’–

okay so bestie, welcome to the packet manual page, and no cap this one is a banger. it's giving raw sockets, it's giving layer 2 energy, it's giving "i talk directly to the driver" main character vibes. let's get into it. ๐Ÿฆ‹


โœจ NAME โœจ

packet โ€” packet interface on device level. periodt. that's the whole name, that's the whole vibe. ๐Ÿ’…


๐ŸŒธ SYNOPSIS ๐ŸŒธ

#include <sys/socket.h>
#include <linux/if_packet.h>
#include <net/ethernet.h> /* the L2 protocols */

packet_socket = socket(AF_PACKET, int socket_type, int protocol);

look at her. AF_PACKET, a socket_type, a protocol, and boom โ€” you're building sockets at the physical layer like it's nothing. iconic. ๐Ÿ”ฅ


๐Ÿ‘‘ DESCRIPTION ๐Ÿ‘‘

so, packet sockets? they're how you receive or send raw packets at the device driver level, aka OSI Layer 2. the way that lets you implement protocol modules in user space, sitting right on top of the physical layer? obsessed. that's the whole point. ๐Ÿ˜Œ

the socket_type is one of two things:

  • SOCK_RAW โ€” for raw packets including the link-level header
  • SOCK_DGRAM โ€” for cooked packets with the link-level header removed

either way, the link-level header info is available in a common format inside a sockaddr_ll structure. cute.

protocol is the IEEE 802.3 protocol number in network byte order, and you can peep the <linux/if_ether.h> include file for the list of allowed protocols. if you set protocol to htons(ETH_P_ALL), then all protocols are received โ€” yes, all of them, she's greedy ๐Ÿ’–. every incoming packet of that protocol type gets passed to the packet socket before it's passed to the protocols implemented in the kernel. and if protocol is set to zero? no packets are received, bestie. zero. zilch. ๐Ÿ™ˆ you can optionally call bind(2) with a nonzero sll_protocol to start receiving packets for the protocols you specified.

to actually create a packet socket, a process must have the CAP_NET_RAW capability in the user namespace that governs its network namespace. that's not a suggestion, that's the law. โœ‹

ngl if you're missing CAP_NET_RAW, nothing here is happening. no socket for you. ๐Ÿ’€

SOCK_RAW packets are passed to and from the device driver without any changes in the packet data. when receiving a packet, the address is still parsed and passed in a standard sockaddr_ll address structure. when transmitting, the user-supplied buffer should contain the physical-layer header โ€” you're the one writing it, bestie. that packet then gets queued unmodified to the network driver of the interface defined by the destination address. some device drivers always add other headers (rude, but okay). and heads up: SOCK_RAW is similar to but not compatible with the obsolete AF_INET/SOCK_PACKET of Linux 2.0. do not conflate them. ๐Ÿšซ

SOCK_DGRAM operates on a slightly higher level. the physical header is removed before the packet is passed to the user, and packets you send through a SOCK_DGRAM packet socket get a suitable physical-layer header built from the info in the sockaddr_ll destination address before they're queued. so you get to skip the header homework and she assembles it for you. slay. โœจ

by default, all packets of the specified protocol type are passed to a packet socket. want packets from only one specific interface? call bind(2) with an address in a struct sockaddr_ll to bind the socket to that interface. the fields used for binding are sll_family (should be AF_PACKET), sll_protocol, and sll_ifindex.

also, very important: the connect(2) operation is not supported on packet sockets. she said no. ๐Ÿ™…

and when the MSG_TRUNC flag is passed to recvmsg(2), recv(2), or recvfrom(2), the real size of the packet on the wire is always returned, even when it's longer than your buffer. so you'll never be lied to about how big the packet actually was. ๐Ÿซถ


๐ŸŽ€ Address types ๐ŸŽ€

the sockaddr_ll structure is a device-independent physical-layer address. here she is in all her glory:

struct sockaddr_ll {
    unsigned short sll_family;   /* Always AF_PACKET */
    unsigned short sll_protocol; /* Physical-layer protocol */
    int            sll_ifindex;  /* Interface number */
    unsigned short sll_hatype;   /* ARP hardware type */
    unsigned char  sll_pkttype;  /* Packet type */
    unsigned char  sll_halen;    /* Size of address */
    unsigned char  sll_addr[8];  /* Physical-layer address */
};

let's do a vibe check on each field, one by one:

sll_protocol is the standard ethernet protocol type in network byte order, as defined in the <linux/if_ether.h> include file. it defaults to the socket's protocol. so if you don't say anything, she just uses the socket's own. โœจ

sll_ifindex is the interface index of the interface (see netdevice(7)); 0 matches any interface, but โ€” and this is the catch โ€” that's only permitted for binding. also sneaking in here: sll_hatype is an ARP type as defined in the <linux/if_arp.h> include file. ๐Ÿฆ‹

sll_pkttype contains the packet type. valid types are:

  • PACKET_HOST โ€” a packet addressed to the local host
  • PACKET_BROADCAST โ€” a physical-layer broadcast packet
  • PACKET_MULTICAST โ€” a packet sent to a physical-layer multicast address
  • PACKET_OTHERHOST โ€” a packet to some other host that's been caught by a device driver in promiscuous mode ๐Ÿ‘€
  • PACKET_OUTGOING โ€” a packet originating from the local host that's looped back to a packet socket

these types make sense only for receiving. so don't try to send with them, bestie, it's not that kind of party. ๐Ÿ’…

sll_addr and sll_halen contain the physical-layer (e.g., IEEE 802.3) address and its size. the exact interpretation depends on the device. ymmv, as always. ๐Ÿ™ˆ

when you send packets, it's enough to specify sll_family, sll_addr, sll_halen, sll_ifindex, and sll_protocol. the other fields should be 0. and sll_hatype and sll_pkttype are set on received packets just for your information, so read them, don't fight them. ๐Ÿซถ


๐ŸŒˆ Socket options ๐ŸŒˆ

packet socket options are configured by calling setsockopt(2) with level SOL_PACKET. remember that, it's the whole key to this section. ๐Ÿ”‘


  • PACKET_ADD_MEMBERSHIP, PACKET_DROP_MEMBERSHIP โ€” packet sockets can be used to configure physical-layer multicasting and promiscuous mode. PACKET_ADD_MEMBERSHIP adds a binding and PACKET_DROP_MEMBERSHIP drops it. they both expect a packet_mreq structure as their argument:
struct packet_mreq {
    int            mr_ifindex;    /* interface index */
    unsigned short mr_type;       /* action */
    unsigned short mr_alen;       /* address size */
    unsigned char  mr_address[8]; /* physical-layer address */
};

mr_ifindex contains the interface index for the interface whose status should be changed. the mr_type field specifies which action to perform:

  • PACKET_MR_PROMISC โ€” enables receiving all packets on a shared medium (often known as "promiscuous mode" ๐Ÿ‘€)
  • PACKET_MR_MULTICAST โ€” binds the socket to the physical-layer multicast group specified in mr_address and mr_alen
  • PACKET_MR_ALLMULTI โ€” sets the socket up to receive all multicast packets arriving at the interface

and in addition, the traditional ioctls SIOCSIFFLAGS, SIOCADDMULTI, SIOCDELMULTI can be used for the same purpose. the old ways still work, iykyk. ๐Ÿงš

  • PACKET_AUXDATA (since Linux 2.6.21) โ€” if this binary option is enabled, the packet socket passes a metadata structure along with each packet in the recvmsg(2) control field. the structure can be read with cmsg(3). it's defined as:
struct tpacket_auxdata {
    __u32 tp_status;
    __u32 tp_len;      /* packet size */
    __u32 tp_snaplen;  /* captured size */
    __u16 tp_mac;
    __u16 tp_net;
    __u16 tp_vlan_tci;
    __u16 tp_vlan_tpid; /* Since Linux 3.14; earlier, these
                           were unused padding bytes */
};
  • PACKET_FANOUT (since Linux 3.1) โ€” to scale processing across threads, packet sockets can form a fanout group. in this mode, each matching packet is enqueued onto only one socket in the group. a socket joins a fanout group by calling setsockopt(2) with level SOL_PACKET and option PACKET_FANOUT. each network namespace can have up to 65536 independent groups. a socket selects a group by encoding the ID in the first 16 bits of the integer option value. the first packet socket to join a group implicitly creates it. to successfully join an existing group, subsequent packet sockets must have the same protocol, device settings, fanout mode, and flags (see below). and plot twist: packet sockets can leave a fanout group only by closing the socket, and the group is deleted when the last socket is closed. no dramatic exits here. ๐Ÿ’€

fanout supports multiple algorithms to spread traffic between sockets, as follows:

  • the default mode, PACKET_FANOUT_HASH, sends packets from the same flow to the same socket to maintain per-flow ordering. for each packet, it chooses a socket by taking the packet flow hash modulo the number of sockets in the group, where a flow hash is a hash over network-layer address and optional transport-layer port fields.
  • the load-balance mode PACKET_FANOUT_LB implements a round-robin algorithm.
  • PACKET_FANOUT_CPU selects the socket based on the CPU that the packet arrived on.
  • PACKET_FANOUT_ROLLOVER processes all data on a single socket, moving to the next when one becomes backlogged.
  • PACKET_FANOUT_RND selects the socket using a pseudo-random number generator.
  • PACKET_FANOUT_QM (available since Linux 3.14) selects the socket using the recorded queue_mapping of the received skb.

fanout modes can take additional options. IP fragmentation causes packets from the same flow to have different flow hashes. the flag PACKET_FANOUT_FLAG_DEFRAG, if set, causes packets to be defragmented before fanout is applied, to preserve order even in this case. fanout mode and options are communicated in the second 16 bits of the integer option value. the flag PACKET_FANOUT_FLAG_ROLLOVER enables the roll over mechanism as a backup strategy: if the original fanout algorithm selects a backlogged socket, the packet rolls over to the next available one. the way that's just good design, honestly. โœจ

  • PACKET_LOSS (with PACKET_TX_RING) โ€” when a malformed packet is encountered on a transmit ring, the default is to reset its tp_status to TP_STATUS_WRONG_FORMAT and abort the transmission immediately. the malformed packet blocks itself and subsequently enqueued packets from being sent. the format error must be fixed, the associated tp_status reset to TP_STATUS_SEND_REQUEST, and the transmission process restarted via send(2). however, if PACKET_LOSS is set, any malformed packet will be skipped, its tp_status reset to TP_STATUS_AVAILABLE, and the transmission process continued. so basically: panic mode, or skip-and-carry-on mode. your call. ๐ŸŽ€
seriously though, if you're not setting PACKET_LOSS, one little malformed packet will hold up the whole queue. it's giving "one bad apple ruins the group chat." ๐Ÿ“
  • PACKET_RESERERVE (with PACKET_RX_RING) โ€” by default, a packet receive ring writes packets immediately following the metadata structure and alignment padding. this integer option reserves additional headroom. extra breathing room, bestie, we love to see it. ๐Ÿซถ

that's where part one leaves us โ€” the saga continues, and there's more coming up in the next part. don't go anywhere. ๐ŸŒˆโœจ

๐ŸŽ€ PACKET_RX_RING ๐ŸŽ€

Okay bestie, this one's the big one. It's literally setting up a memory-mapped ring buffer for asynchronous packet reception. The packet socket reserves a contiguous region of your application's address space, lays it all out into an array of packet slots, and copies packets (up to tp_snaplen) into subsequent slots. Each packet is preceded by a metadata structure similar to tpacket_auxdata. โœจ

The protocol fields encode the offset to the data from the start of the metadata header. tp_net stores the offset to the network layer. Here's the tea, and it depends on your socket type:

  • if the packet socket is of type SOCK_DGRAM, then tp_mac is the same as tp_net
  • if it's of type SOCK_RAW, then that field stores the offset to the link-layer frame

The socket and your app talk back and forth about the head and tail of the ring through the tp_status field. ๐Ÿซถ The packet socket owns all slots with tp_status equal to TP_STATUS_KERNEL. After filling a slot, it changes the status to hand ownership over to the application. During normal operation, that new tp_status value has at least the TP_STATUS_USER bit set, signalling that a received packet has been stored. And when the app is done processing a packet, it gives ownership of the slot back to the socket by setting tp_status equal to TP_STATUS_KERNEL. Passing notes in class but make it kernel. ๐Ÿ’…

Packet sockets implement multiple variants of the packet ring. The implementation details are described in Documentation/networking/packet_mmap.rst in the Linux kernel source tree.


๐Ÿ“Š PACKET_STATISTICS ๐Ÿ“Š

Retrieve packet socket statistics in the form of a structure:

struct tpacket_stats {
    unsigned int tp_packets;  /* Total packet count */
    unsigned int tp_drops;    /* Dropped packet count */
};

Receiving statistics resets the internal counters. And heads up โ€” the statistics structure differs when using a ring of variant TPACKET_V3. ๐Ÿ˜ญ


โฐ PACKET_TIMESTAMP (with PACKET_RX_RING; since Linux 2.6.36) โฐ

The packet receive ring always stores a timestamp in the metadata header. By default, that's a software generated timestamp, made when the packet is copied into the ring. This integer option selects the type of timestamp. Besides the default, it supports the two hardware formats described in Documentation/networking/timestamping.rst in the Linux kernel source tree. ๐Ÿฆ‹


๐Ÿ“ค PACKET_TX_RING (since Linux 2.6.31) ๐Ÿ“ค

Create a memory-mapped ring buffer for packet transmission. This option is similar to PACKET_RX_RING and takes the same arguments. Your app writes packets into slots with tp_status equal to TP_STATUS_AVAILABLE and schedules them for transmission by changing tp_status to TP_STATUS_SEND_REQUEST.

When packets are ready to be transmitted, the application calls send(2) or a variant thereof. The buf and len fields of this call are ignored. If an address is passed using sendto(2) or sendmsg(2), then that overrides the socket default. On successful transmission, the socket resets tp_status to TP_STATUS_AVAILABLE. It immediately aborts the transmission on error unless PACKET_LOSS is set. โšก


๐Ÿ”ข PACKET_VERSION (with PACKET_RX_RING; since Linux 2.6.27) ๐Ÿ”ข

By default, PACKET_RX_RING creates a packet receive ring of variant TPACKET_V1. To create another variant, configure the desired variant by setting this integer option before creating the ring. Do it in the right order, babe, order matters. ๐Ÿ™ˆ


๐Ÿšฆ PACKET_QDISC_BYPASS (since Linux 3.14) ๐Ÿšฆ

By default, packets sent through packet sockets pass through the kernel's qdisc (traffic control) layer, which is genuinely fine for the vast majority of use cases. But for traffic generator appliances using packet sockets that intend to brute-force flood the network โ€” for example, to test devices under load in a similar fashion to pktgen โ€” this layer can be bypassed by setting this integer option to 1.

๐Ÿ˜ญ A side effect is that packet buffering in the qdisc layer is avoided, which will lead to increased drops when network device transmit queues are busy; therefore, use at your own risk. Not a drill, bestie.

๐ŸŽ›๏ธ Ioctls ๐ŸŽ›๏ธ

SIOCGSTAMP can be used to receive the timestamp of the last received packet. Argument is a struct timeval variable.

In addition, all standard ioctls defined in netdevice(7) and socket(7) are valid on packet sockets. All of them. Yes, really. โœจ


๐Ÿšจ Error handling ๐Ÿšจ

Packet sockets do no error handling other than errors occurred while passing the packet to the device driver. They don't have the concept of a pending error. That's just... not a thing they do. ๐Ÿ’€


๐Ÿ’ฅ ERRORS ๐Ÿ’ฅ

  • EADDRNOTAVAIL โ€” Unknown multicast group address passed.
  • EFAULT โ€” User passed invalid memory address.
  • EINVAL โ€” Invalid argument.
  • EMSGSIZE โ€” Packet is bigger than interface MTU.
  • ENETDOWN โ€” Interface is not up.
  • ENOBUFS โ€” Not enough memory to allocate the packet.
  • ENODEV โ€” Unknown device name or interface index specified in interface address.
  • ENOENT โ€” No packet received.
  • ENOTCONN โ€” No interface address passed.
  • ENXIO โ€” Interface address contained an invalid interface index.
  • EPERM โ€” User has insufficient privileges to carry out this operation.

In addition, other errors may be generated by the low-level driver. Not our fault, bestie. ๐Ÿคท


๐Ÿ•ฐ๏ธ VERSIONS ๐Ÿ•ฐ๏ธ

AF_PACKET is a new feature in Linux 2.2. Earlier Linux versions supported only SOCK_PACKET. Yes, ancient. We don't talk about it. ๐Ÿ˜ญ


๐Ÿ“ NOTES ๐Ÿ“

For portable programs it is suggested to use AF_PACKET via pcap(3); although this covers only a subset of the AF_PACKET features. iykyk.

The SOCK_DGRAM packet sockets make no attempt to create or parse the IEEE 802.2 LLC header for a IEEE 802.3 frame. When ETH_P_802_3 is specified as protocol for sending, the kernel creates the 802.3 frame and fills out the size field; the user has to supply the LLC header to get a fully conforming packet. Incoming 802.3 packets are not multiplexed on the DSAP/SSAP protocol fields; instead they are supplied to the user as protocol ETH_P_802_2 with the LLC header prefixed. It is thus not possible to bind to ETH_P_802_3; bind to ETH_P_802_2 instead and do the protocol multiplex yourself. The default for sending is the standard Ethernet DIX encapsulation with the protocol filled in. ๐Ÿ’…

Packet sockets are not subject to the input or output firewall chains. Wild, right? ๐Ÿซถ


๐Ÿ”„ Compatibility ๐Ÿ”„

In Linux 2.0, the only way to get a packet socket was with the call:

socket(AF_INET, SOCK_PACKET, protocol)

This is still supported, but deprecated and strongly discouraged. The main difference between the two methods is that SOCK_PACKET uses the old struct sockaddr_pkt to specify an interface, which doesn't provide physical-layer independence. ๐Ÿ‘‘

struct sockaddr_pkt {
    unsigned short spkt_family;
    unsigned char  spkt_device[14];
    unsigned short spkt_protocol;
};

spkt_family contains the device type, spkt_protocol is the IEEE 802.3 protocol type as defined in <sys/if_ether.h> and spkt_device is the device name as a null-terminated string, for example, eth0.

โš ๏ธ This structure is obsolete and should not be used in new code.

๐Ÿ› BUGS ๐Ÿ›

๐Ÿ“Ž LLC header handling ๐Ÿ“Ž

The IEEE 802.2/803.3 LLC handling could be considered as a bug. Yeah. It's giving "known issue." ๐Ÿ’€


โœ‚๏ธ MSG_TRUNC issues โœ‚๏ธ

The MSG_TRUNC recvmsg(2) extension is an ugly hack and should be replaced by a control message. There is currently no way to get the original destination address of packets via SOCK_DGRAM. Tragic, honestly. ๐Ÿ˜ญ


๐Ÿช“ spkt_device device name truncation ๐Ÿช“

The spkt_device field of sockaddr_pkt has a size of 14 bytes, which is less than the constant IFNAMSIZ defined in <net/if.h> which is 16 bytes and describes the system limit for a network interface name. This means the names of network devices longer than 14 bytes will be truncated to fit into spkt_device. All these sizes include the terminating null byte ('\0'). ๐ŸŒธ

Issues from this with old code typically show up with very long interface names used by the Predictable Network Interface Names feature enabled by default in many modern Linux distributions.

The preferred solution is to rewrite code to avoid SOCK_PACKET. Possible user solutions are to disable Predictable Network Interface Names or to rename the interface to a name of at most 13 bytes, for example using the ip(8) tool. โœจ


๐Ÿ“š Documentation issues ๐Ÿ“š

Socket filters are not documented. That's it, that's the issue. ๐Ÿ™ˆ


๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

socket(2), pcap(3), capabilities(7), ip(7), raw(7), socket(7), ip(8),

RFC 894 for the standard IP Ethernet encapsulation. RFC 1700 for the IEEE 802.3 IP encapsulation.

The <linux/if_ether.h> include file for physical-layer protocols.

The Linux kernel source tree. Documentation/networking/filter.rst describes how to apply Berkeley Packet Filters to packet sockets. tools/testing/selftests/net/psock_tpacket.c contains example source code for all available versions of PACKET_RX_RING and PACKET_TX_RING. Go read it, it's free and it slays. ๐Ÿ“–๐Ÿ’–


And that's the whole page, bestie! ๐Ÿ’… This one came from the Linux man-pages 6.20, dated 2026-02-08 โ€” packet(7) section, main character energy as always. Go forth and AF_PACKET responsibly. ๐Ÿฆ‹๐ŸŒˆ

๐Ÿ“ฆ where this page comes from
  • arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
  • nixpkgs unstable: man-pages 6.20
  • ๐Ÿ“œ the page's license: Linux-man-pages-1-para
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms