#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <netinet/udp.h> #include <netinet/ip_icmp.h> #define BUFFER_SIZE 4096 void process_packet(unsigned char *buffer, int size) { struct iphdr *ip_header = (struct iphdr *)(buffer); unsigned short ip_header_length = ip_header->ihl * 4; struct tcphdr *tcp_header = (struct tcphdr *)(buffer + ip_header_length); unsigned short tcp_header_length = tcp_header->doff * 4; unsigned char *payload = buffer + ip_header_length + tcp_header_length; int payload_length = size - ip_header_length - tcp_header_length; // 在这里处理报文内容,可以打印报文信息或对报文进行其他操作 printf("Received packet with size: %d\n", size); } int main() { int raw_socket; unsigned char buffer[BUFFER_SIZE]; struct sockaddr_in server_address; int data_size; // 创建原始套接字 raw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_TCP); if (raw_socket < 0) { perror("Failed to create socket"); return 1; } // 绑定地址 server_address.sin_family = AF_INET; server_address.sin_port = 0; server_address.sin_addr.s_addr = INADDR_ANY; if (bind(raw_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) { perror("Failed to bind"); return 1; } // 开始监听 while (1) { data_size = recvfrom(raw_socket, buffer, BUFFER_SIZE, 0, NULL, NULL); if (data_size < 0) { perror("Failed to receive"); return 1; } process_packet(buffer, data_size); } return 0; }
Powered by ddoss.cn 12.0
©2015 - 2024 ddoss
渝公网安备50011302222260号 渝ICP备2024035333号 【实验平台安全承诺书】 小绿叶技术社区,优化网络中,点击查看配置信息
您的IP:192.168.122.82,2024-09-20 19:03:33,Processed in 0.02876 second(s).