Use of Packet Socket in Linux
Hanse 2009-4-3
Linux supports PF_PACKET Sockets for user-layer network protocols. With this SOCK_RAW Packet socket, the application can directly receive a data frame with a complete Layer 2 data frame, and then use this socket to send a Layer 2 data frame. Therefore, the underlying network protocol can be implemented. You can also use this type of Socket to capture packets. Of course, if you want to capture packets that are not your own, you also need to set the NIC to the hybrid mode.
1. Create a Packet Socket
<Pre>
# Include <sys/socket. h>
# Include <netpacket/packet. h>
# Include <net/ethernet. h>/* the L2 protocols */
Packet_socket = socket (PF_PACKET, int socket_type, int protocol );
</Pre>
Socket_type can be SOCK_DGRAM or SOCK_RAW. If it is set to SOCK_RAW, the received message contains the Layer 2 protocol header. Otherwise, only the Layer 2 data frame content is available.
For example:
Int skfd;
Skfd = socket (pf_packet, sock_raw, htons (Protocol ));
2. bind to a network interface
This step is optional. If not bound, layer-2 data frames on all interfaces will be received.
Struct sockaddr_ll;
Struct ifreq IFR;
Strncpy (IFR. ifr_name, L2-> ifname, sizeof (IFR. ifr_name ));
Memset (L2, 0, sizeof (* l2 ));
Strncpy (L2-> ifname, ifname, sizeof (L2-> ifname ));
Memset (& LL, 0, sizeof (LL ));
Ll. sll_family = pf_packet;
Ll. sll_ifindex = IFR. ifr_ifindex;
Ll. sll_protocol = htons (Protocol );
If (BIND (L2-> FD, (struct sockaddr *) & LL, sizeof (LL) <0 ){
Perror ("bind [pf_packet]");
Close (L2-> FD );
Free (L2 );
Return NULL;
}
Protocol is the protocol type to be monitored. If it is ETH_P_ALL, all data frames are received.
Note:
The bridge cannot receive the forwarded non-self-forwarded packets.
Ssize_t recvfrom (int s, void * buf, size_t len, int flags,
Struct sockaddr * from, socklen_t * fromlen );
If fromlen is 0, the from parameter is not filled.
Reference:
1. Linux Man: packet (7)