1. The original socket (SOCK_RAW) [It is more biased towards the Internet of Things, but I still introduce it, and those who are interested can learn about it ]
- A socket different from SOCK_STREAM and SOCK_DGRAM, which is implemented in the core of the system .
- It can introduce all the data frames (data packets) on the local network card, which is very useful for monitoring network traffic and analyzing network data .
- Developers can send their own assembled data packets [the relevant protocols have been introduced before] to the network.
- Widely used in advanced network programming.
- Network experts, hackers usually use this to write peculiar network programs.
Streaming sockets can only send and receive data: TCP SCTP protocol data
Report socket can only send and receive: UDP protocol data
The original socket can send and receive: 1. The kernel kernel has not processed the data packet, so you need to access other protocols, 2. The sent data needs to be used, the original socket (SOCK_RAW) 3. The send and receive function uses recvfrom sendto as shown in the figure
That's it, the original socket directly takes the data from the network card directly through the green channel .
2. Original socket (SOCK_RAW) creation
int socket(PF_PACKET, SOCK_RAW, protocol)
Features:
Create the original socket of the link layer
parameter:
protocol: Specify the type of data packets that can be received or sent
ETH_P_IP: IPV4 packet
ETH_P_ARP: ARP packet
ETH_P_ALL: Any protocol type data packet
return value:
Success (>0): link layer socket, failure (<0): error
sock_raw_fd = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_ALL));
Obsolete, no longer use sock_raw_fd = socket(AF_INET, SOCK_PACKET, htons(ETH_P_ALL));
head File:
#include <sys/socket.h>
#include <netinet/ether.h>
Simple packet capture realization [Code Demo]
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/ether.h>
#include <unistd.h>
#include <stdio.h>
using namespace std;
int32_t
main(int argc, const char* argv[])
{
unsigned char buf[1519]; // 1518 + 1
int sock_raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
while(1) {
unsigned char src_mac[18] = "";
unsigned char dst_mac[18] = "";
recvfrom(sock_raw_fd, buf, sizeof(buf), 0, NULL, NULL);
//"%x:%x:%x:%x:%x:%x"
sprintf((char*)dst_mac, "%02x:%02x:%02x:%02x:%02x:%02x",
buf[0],buf[1],buf[2],buf[3],buf[4],buf[5]);
// dst_mac[18] = '\0';
sprintf((char*)src_mac, "%02x:%02x:%02x:%02x:%02x:%02x",
buf[6],buf[7],buf[8],buf[9],buf[10],buf[11]);
// src_mac[18] = '\0';
printf("dst_mac: %s\nsrc_mac: %s\n", dst_mac, src_mac);
}
return 0;
}
effect: