You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C语言Raw Socket中发送十六进制数据的实现难题

问题解决:C语言Raw Socket发送十六进制对应的二进制数据

核心问题

你的C代码错误地将十六进制字符串直接作为ASCII字符发送,而没有先把字符串解析成对应的二进制字节流。比如输入"1A2B"时,实际发送的是0x31 0x41 0x32 0x42(ASCII字符'1'、'A'、'2'、'B'),但需求是发送0x1A 0x2B这两个二进制字节。

解决方案步骤

1. 实现十六进制字符串转二进制字节流的函数

先写一个工具函数,把输入的十六进制字符串转换成对应的二进制数组:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// 将十六进制字符串转为二进制字节流,返回字节长度,失败返回-1
int hex_str_to_bytes(const char *hex_str, unsigned char *out_bytes, size_t max_out_len) {
    size_t str_len = strlen(hex_str);
    // 十六进制字符串长度必须是偶数
    if (str_len % 2 != 0) return -1;
    
    size_t byte_count = str_len / 2;
    if (byte_count > max_out_len) return -1;
    
    for (size_t i = 0; i < byte_count; i++) {
        // 每次取两个字符
        char hex_byte[3] = {0};
        strncpy(hex_byte, hex_str + i*2, 2);
        // 转换为unsigned char
        char *end_ptr;
        out_bytes[i] = strtoul(hex_byte, &end_ptr, 16);
        if (end_ptr != hex_byte + 2) {
            // 非法十六进制字符
            return -1;
        }
    }
    return byte_count;
}

2. 修改Raw Socket发送逻辑

在Raw Socket代码中,不要直接发送十六进制字符串,而是先调用上面的函数转换成二进制字节,再发送这个字节数组。示例整合代码(简化版,需补充自身的IP/TCP头部构造逻辑):

#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>

int main() {
    // 创建Raw Socket
    int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
    if (sockfd < 0) {
        perror("socket create failed");
        exit(1);
    }

    // 目标十六进制字符串
    const char *target_hex = "1A3F0C";
    unsigned char payload[1024];
    int payload_len = hex_str_to_bytes(target_hex, payload, sizeof(payload));
    if (payload_len < 0) {
        fprintf(stderr, "Invalid hex string\n");
        close(sockfd);
        exit(1);
    }

    // 构造数据包缓冲区
    unsigned char packet[4096];
    struct iphdr *ip_hdr = (struct iphdr *)packet;
    struct tcphdr *tcp_hdr = (struct tcphdr *)(packet + sizeof(struct iphdr));
    
    // 初始化IP头部(根据实际需求修改字段)
    ip_hdr->version = 4;
    ip_hdr->ihl = 5;
    ip_hdr->tos = 0;
    ip_hdr->tot_len = htons(sizeof(struct iphdr) + sizeof(struct tcphdr) + payload_len);
    ip_hdr->id = htons(12345);
    ip_hdr->frag_off = 0;
    ip_hdr->ttl = 64;
    ip_hdr->protocol = IPPROTO_TCP;
    ip_hdr->saddr = inet_addr("源IP"); // 替换为实际源IP
    ip_hdr->daddr = inet_addr("目标IP"); // 替换为实际目标IP
    ip_hdr->check = 0; // 若系统不自动计算,需自行实现校验和逻辑

    // 初始化TCP头部(根据实际需求修改字段)
    tcp_hdr->source = htons(本地端口); // 替换为实际本地端口
    tcp_hdr->dest = htons(目标端口); // 替换为实际目标端口
    tcp_hdr->seq = htons(1000); // 替换为实际序列号
    tcp_hdr->ack_seq = htons(2000); // 替换为实际确认号
    tcp_hdr->doff = 5; // TCP头部长度(无选项时为5*4=20字节)
    tcp_hdr->psh = 1; // 置PSH标志位
    tcp_hdr->ack = 1; // 置ACK标志位
    tcp_hdr->window = htons(65535);
    tcp_hdr->check = 0; // 若系统不自动计算,需自行实现校验和逻辑
    tcp_hdr->urg_ptr = 0;

    // 将负载复制到TCP头部之后
    memcpy(packet + sizeof(struct iphdr) + sizeof(struct tcphdr), payload, payload_len);
    int total_len = sizeof(struct iphdr) + sizeof(struct tcphdr) + payload_len;

    // 发送数据包
    struct sockaddr_in dest_addr;
    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.sin_family = AF_INET;
    dest_addr.sin_addr.s_addr = ip_hdr->daddr;

    ssize_t send_len = sendto(sockfd, packet, total_len, 0, (struct sockaddr *)&dest_addr, sizeof(dest_addr));
    if (send_len < 0) {
        perror("send failed");
    } else {
        printf("Sent %zd bytes, payload binary: ", send_len);
        for (int i = 0; i < payload_len; i++) {
            printf("%02X ", payload[i]);
        }
        printf("\n");
    }

    close(sockfd);
    return 0;
}

3. 关键注意事项

  • 标志位设置:必须确保TCP头部的psh和ack标志位被置1,否则不符合防火墙校验的PSH.ACK包要求
  • 校验和计算:Raw Socket发送的IP/TCP包,多数系统不会自动计算校验和,需要自行实现校验和逻辑,否则数据包会被网络设备丢弃
  • 权限要求:创建Raw Socket需要root权限,运行程序时需加sudo
  • 字符串合法性:输入的十六进制字符串必须是偶数长度,且仅包含0-9、A-F/a-F的合法字符

内容的提问来源于stack exchange,提问作者CoreBot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 12:39:51