收藏文章 楼主

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

版块:C/C++语言开发   类型:普通   作者:小绿叶技术博客   查看:1101   回复:0   获赞:4   时间:2023-07-31 16:05:47


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




有些梦虽然遥不可及,但并不是不可能实现。 
回复列表
默认   热门   正序   倒序

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

Powered by ddoss.cn 12.0

©2015 - 2024 ddoss

头像

用户名:

粉丝数:

签名:

资料 关注 好友 消息