
Socket::Packet - interface to Linux's PF_PACKET socket family

use Socket qw( SOCK_DGRAM );
use Socket::Packet qw(
PF_PACKET
ETH_P_ALL
pack_sockaddr_ll unpack_sockaddr_ll
);
socket( my $sock, PF_PACKET, SOCK_DGRAM, 0 )
or die "Cannot socket() - $!\n";
bind( $sock, pack_sockaddr_ll( ETH_P_ALL, 0, 0, 0, "" ) )
or die "Cannot bind() - $!\n";
while( my $addr = recv( $sock, my $packet, 8192, 0 ) ) {
my ( $proto, $ifindex, $hatype, $pkttype, $addr )
= unpack_sockaddr_ll( $addr );
...
}

To quote packet(7):
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 physical layer.
Sockets in the PF_PACKET family get direct link-level access to the underlying hardware (i.e. Ethernet or similar). They are usually used to implement packet capturing, or sending of specially-constructed packets or to implement protocols the underlying kernel does not recognise.
The use of PF_PACKET sockets is usually restricted to privileged users only.

The following constants are exported
The packet family (for socket() calls)
The address family
This packet is inbound unicast for this host.
This packet is inbound broadcast.
This packet is inbound multicast.
This packet is inbound unicast for another host.
This packet is outbound.
Pseudo-protocol number to capture all protocols.

The following pair of functions operate on AF_PACKET address structures. The meanings of the parameters are:
An ethertype protocol number. When using an address with bind(), the constant ETH_P_ALL can be used instead, to capture any protocol. The pack_sockaddr_ll() and unpack_sockaddr_ll() functions byte-swap this value to or from network endian order.
The index number of the interface on which the packet was sent or received. When using an address with bind(), the value 0 can be used instead, to watch all interfaces.
The hardware ARP type of hardware address.
The type of the packet; indicates if it was sent or received. Will be one of the PACKET_* values.
The underlying hardware address, in the type given by hatype.
Returns a sockaddr_ll structure with the fields packed into it.
Takes a sockaddr_ll structure and returns the unpacked fields from it.

packet(7) - packet, AF_PACKET - packet interface on device level
Paul Evans <leonerd@leonerd.org.uk>