# packet(7) - man - phpMan

[PACKET(7)](https://www.chedong.com/phpMan.php/man/PACKET/7/markdown)                             Linux Programmer's Manual                            [PACKET(7)](https://www.chedong.com/phpMan.php/man/PACKET/7/markdown)



## NAME
       packet - packet interface on device level

## 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_**);**

## DESCRIPTION
       Packet  sockets  are  used  to receive or send raw packets at the device driver (OSI Layer 2)
       level.  They allow the user to implement protocol modules in user space on top of the  physi‐
       cal layer.

       The  _socket_type_  is  either  **SOCK**___**RAW**  for  raw  packets  including the link-level header or
       **SOCK**___**DGRAM** for cooked packets with the link-level header removed.  The link-level header  in‐
       formation  is  available in a common format in a _sockaddr_ll_ structure.  _protocol_ is the IEEE
       802.3 protocol number in network byte order.  See the _<linux/if_ether.h>_ include file  for  a
       list  of allowed protocols.  When protocol is set to **htons(ETH**___**P**___**ALL)**, then all protocols are
       received.  All incoming packets of that protocol type will be passed to the packet socket be‐
       fore they are passed to the protocols implemented in the kernel.

       In  order  to  create  a packet socket, a process must have the **CAP**___**NET**___**RAW** capability in the
       user namespace that governs its network namespace.

       **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 _sock__‐
       _addr_ll_ address structure.  When transmitting a packet, the user-supplied buffer should  con‐
       tain  the physical-layer header.  That packet is then queued unmodified to the network driver
       of the interface defined by the destination address.  Some device drivers  always  add  other
       headers.   **SOCK**___**RAW** is similar to but not compatible with the obsolete **AF**___**INET/SOCK**___**PACKET** of
       Linux 2.0.

       **SOCK**___**DGRAM** operates on a slightly higher level.  The physical header is  removed  before  the
       packet is passed to the user.  Packets sent through a **SOCK**___**DGRAM** packet socket get a suitable
       physical-layer header based on the information in the _sockaddr_ll_ destination address  before
       they are queued.

       By default, all packets of the specified protocol type are passed to a packet socket.  To get
       packets only from a specific interface use [**bind**(2)](https://www.chedong.com/phpMan.php/man/bind/2/markdown) specifying an address in  a  _struct_  _sock__‐
       _addr_ll_  to  bind  the packet socket to an interface.  Fields used for binding are _sll_family_
       (should be **AF**___**PACKET**), _sll_protocol_, and _sll_ifindex_.

       The [**connect**(2)](https://www.chedong.com/phpMan.php/man/connect/2/markdown) operation is not supported on packet sockets.

       When the **MSG**___**TRUNC** flag is passed to [**recvmsg**(2)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown), [**recv**(2)](https://www.chedong.com/phpMan.php/man/recv/2/markdown), or [**recvfrom**(2)](https://www.chedong.com/phpMan.php/man/recvfrom/2/markdown), the real length  of
       the packet on the wire is always returned, even when it is longer than the buffer.

### Address types
       The _sockaddr_ll_ structure is a device-independent physical-layer address.

           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;    /* Length of address */
               unsigned char  sll_addr[8];  /* Physical-layer address */
           };

       The fields of this structure are as follows:

       *  _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.

       *  _sll_ifindex_ is the interface index of the interface (see [**netdevice**(7)](https://www.chedong.com/phpMan.php/man/netdevice/7/markdown)); 0 matches any  in‐
          terface  (only  permitted  for  binding).   _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** for a packet  addressed
          to  the  local host, **PACKET**___**BROADCAST** for a physical-layer broadcast packet, **PACKET**___**MULTI**‐‐
          **CAST** for a packet sent to a  physical-layer  multicast  address,  **PACKET**___**OTHERHOST**  for  a
          packet to some other host that has been caught by a device driver in promiscuous mode, and
          **PACKET**___**OUTGOING** for a packet originating from the local host that  is  looped  back  to  a
          packet socket.  These types make sense only for receiving.

       *  _sll_addr_  and  _sll_halen_  contain  the  physical-layer  (e.g., IEEE 802.3) address and its
          length.  The exact interpretation depends on the device.

       When you send packets, it is enough to specify _sll_family_, _sll_addr_, _sll_halen_,  _sll_ifindex_,
       and  _sll_protocol_.   The other fields should be 0.  _sll_hatype_ and _sll_pkttype_ are set on re‐
       ceived packets for your information.

### Socket options
       Packet socket options are configured by calling [**setsockopt**(2)](https://www.chedong.com/phpMan.php/man/setsockopt/2/markdown) with level **SOL**___**PACKET**.

       **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 argument:

                  struct packet_mreq {
                      int            mr_ifindex;    /* interface index */
                      unsigned short mr_type;       /* action */
                      unsigned short mr_alen;       /* address length */
                      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** en‐
              ables 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_, and **PACKET**___**MR**___**ALLMULTI** sets the socket up  to  receive  all
              multicast packets arriving at the interface.

              In  addition,  the  traditional ioctls **SIOCSIFFLAGS**, **SIOCADDMULTI**, **SIOCDELMULTI** can be
              used for the same purpose.

       **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)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown) control field.  The structure can be read with
              [**cmsg**(3)](https://www.chedong.com/phpMan.php/man/cmsg/3/markdown).  It is defined as

                  struct tpacket_auxdata {
                      __u32 tp_status;
                      __u32 tp_len;      /* packet length */
                      __u32 tp_snaplen;  /* captured length */
                      __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)](https://www.chedong.com/phpMan.php/man/setsockopt/2/markdown)  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 success‐
              fully join an existing group, subsequent packet sockets must have the  same  protocol,
              device settings, fanout mode and flags (see below).  Packet sockets can leave a fanout
              group only by closing the socket.  The group  is  deleted  when  the  last  socket  is
              closed.

              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 tak‐
                 ing  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 in‐
              teger option value.  The flag **PACKET**___**FANOUT**___**FLAG**___**ROLLOVER** enables the roll over mecha‐
              nism  as  a  backup  strategy:  if  the original fanout algorithm selects a backlogged
              socket, the packet rolls over to the next available one.

       **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 mal‐
              formed 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)](https://www.chedong.com/phpMan.php/man/send/2/markdown).  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.

       **PACKET**___**RESERVE** (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.

       **PACKET**___**RX**___**RING**
              Create  a  memory-mapped  ring  buffer  for asynchronous packet reception.  The packet
              socket reserves a contiguous region of application address space, lays it 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  pro‐
              tocol  fields  encode  the  offset  to the data from the start of the metadata header.
              _tp_net_ stores the offset to the network layer.   If  the  packet  socket  is  of  type
              **SOCK**___**DGRAM**,  then  _tp_mac_  is  the  same.   If it is of type **SOCK**___**RAW**, then that field
              stores the offset to the link-layer frame.  Packet socket and application  communicate
              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 of the slot to transfer ownership to the application.  During normal operation,
              the new _tp_status_ value has at least the **TP**___**STATUS**___**USER** bit set to signal that  a  re‐
              ceived packet has been stored.  When the application has finished processing a packet,
              it transfers ownership of the slot back to the socket by setting  _tp_status_  equal  to
              **TP**___**STATUS**___**KERNEL**.

              Packet sockets implement multiple variants of the packet ring.  The implementation de‐
              tails 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.  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,
              this  is  a  software generated timestamp generated when the packet is copied into the
              ring.  This integer option selects the type of timestamp.   Besides  the  default,  it
              support  the  two  hardware  formats  described in _Documentation/networking/timestamp__‐
              _ing.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.  The application 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 trans‐
              mitted, the application calls [**send**(2)](https://www.chedong.com/phpMan.php/man/send/2/markdown) or a variant thereof.  The _buf_ and _len_ fields of
              this  call  are  ignored.  If an address is passed using [**sendto**(2)](https://www.chedong.com/phpMan.php/man/sendto/2/markdown) or [**sendmsg**(2)](https://www.chedong.com/phpMan.php/man/sendmsg/2/markdown), 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 un‐
              less **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.

       **PACKET**___**QDISC**___**BYPASS** (since Linux 3.14)
              By default, packets sent through packet sockets pass through the kernel's qdisc (traf‐
              fic  control)  layer,  which  is fine for the vast majority of use cases.  For traffic
              generator appliances using packet sockets that intend to brute-force  flood  the  net‐
              work—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 net‐
              work device transmit queues are busy; therefore, use at your own risk.

### 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)](https://www.chedong.com/phpMan.php/man/netdevice/7/markdown) and [**socket**(7)](https://www.chedong.com/phpMan.php/man/socket/7/markdown) are valid on packet
       sockets.

### 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.

## 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.

## VERSIONS
       **AF**___**PACKET** is a new feature in Linux 2.2.  Earlier Linux versions supported only **SOCK**___**PACKET**.

## NOTES
       For portable programs it is suggested to use **AF**___**PACKET** via [**pcap**(3)](https://www.chedong.com/phpMan.php/man/pcap/3/markdown); although this covers only
       a subset of the **AF**___**PACKET** features.

       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 length 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 Eth‐
       ernet DIX encapsulation with the protocol filled in.

       Packet sockets are not subject to the input or output firewall chains.

### 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 be‐
       tween the two methods is that **SOCK**___**PACKET** uses the old _struct_ _sockaddr_pkt_ to specify an  in‐
       terface, 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 de‐
       fined 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
       The IEEE 802.2/803.3 LLC handling could be considered as a bug.

       Socket filters are not documented.

       The  **MSG**___**TRUNC**  [**recvmsg**(2)](https://www.chedong.com/phpMan.php/man/recvmsg/2/markdown) extension is an ugly hack and should be replaced by a control mes‐
       sage.  There is currently no way to get the  original  destination  address  of  packets  via
       **SOCK**___**DGRAM**.

## SEE ALSO
       [**socket**(2)](https://www.chedong.com/phpMan.php/man/socket/2/markdown), [**pcap**(3)](https://www.chedong.com/phpMan.php/man/pcap/3/markdown), [**capabilities**(7)](https://www.chedong.com/phpMan.php/man/capabilities/7/markdown), [**ip**(7)](https://www.chedong.com/phpMan.php/man/ip/7/markdown), [**raw**(7)](https://www.chedong.com/phpMan.php/man/raw/7/markdown), [**socket**(7)](https://www.chedong.com/phpMan.php/man/socket/7/markdown)

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

       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_ con‐
       tains example source code for all available versions of **PACKET**___**RX**___**RING** and **PACKET**___**TX**___**RING**.

## COLOPHON
       This page is part of release 5.10 of the Linux  _man-pages_  project.   A  description  of  the
       project,  information about reporting bugs, and the latest version of this page, can be found
       at <https://www.kernel.org/doc/man-pages/>.



Linux                                        2020-12-21                                    [PACKET(7)](https://www.chedong.com/phpMan.php/man/PACKET/7/markdown)
