Use of Packet Socket in Linux

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.