动态 版块 发帖 消息 我的
小绿叶技术博客
小绿叶技术博客
小绿叶技术Lv154   
c 语言监听所有端口报文信息     


#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;
}




 4  已被阅读了806次  楼主 2023-07-31 16:05:47
回复列表

回复:c 语言监听所有端口报文信息

guest
登录之后更精彩~
Powered by HadSky 7.12.10
© 2015-2024 PuYueTian
您的IP:44.221.66.130,2024-06-20 14:43:25,Processed in 0.02667 second(s).
Powered by HadSky
小绿叶技术博客