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

C语言Socket发送SYN包后未收到RST包问题求助

问题:手动构造TCP SYN包后未收到预期的RST/SYN-ACK响应

我用C语言手动构造SYN包,通过Socket发送到关闭的端口,原本应该收到对应的RST包,但Wireshark抓包确认:既看不到目标服务器发出RST包,本地也没收到响应。即使在服务器端执行nc -l -p 9999打开目标端口,也收不到SYN-ACK包。

另外,Wireshark抓取的SYN包显示:ECN、CWR及Reserved位被意外置位,我无法手动关闭这些位。

以下是SYN包的配置代码:

char packet[BUF_SIZE];
struct iphdr* ip_h = (struct iphdr*) packet;
struct tcphdr* tcp_h = (struct tcphdr*) (packet + sizeof(struct iphdr));
struct pseudo_header ps_h;

ip_h->ihl = 5;
ip_h->version = 4;
ip_h->tos = 0;
ip_h->tot_len = sizeof (struct iphdr) + sizeof (struct tcphdr);
ip_h->id = htons(54321);
ip_h->frag_off = 0;
ip_h->ttl = 255;
ip_h->protocol = IPPROTO_TCP;
ip_h->check = 0;
ip_h->saddr = inet_addr(cf->src_ip);
ip_h->daddr = inet_addr(cf->server_ip);

tcp_h->source = htons(12345);
tcp_h->dest = htons(dest_port);
tcp_h->seq = 0;
tcp_h->ack_seq = 0;
tcp_h->doff = 5;
tcp_h->fin = 0;
tcp_h->syn = 1;
tcp_h->rst = 0;
tcp_h->psh = 0;
tcp_h->ack = 0;
tcp_h->urg = 0;
tcp_h->check = 0;
tcp_h->window = htons (5840);
tcp_h->urg_ptr = 0;

memset(&ps_h, 0, sizeof(ps_h));
ps_h.source_address = inet_addr("192.168.128.2");
ps_h.dest_address = inet_addr(cf->server_ip);
ps_h.placeholder = 0;
ps_h.protocol = IPPROTO_TCP;
ps_h.tcp_length = htons(sizeof(struct tcphdr));

int pseudo_size = sizeof(struct pseudo_header) + sizeof(struct tcphdr);
char *pseudo_packet = malloc(pseudo_size);
memcpy(pseudo_packet, (char *) &ps_h, sizeof(struct pseudo_header));
memcpy(pseudo_packet + sizeof(struct pseudo_header), tcp_h, sizeof(struct tcphdr));

tcp_h->check = checksum(pseudo_packet, pseudo_size);
ip_h->check = checksum(packet, ip_h->tot_len);

伪头部定义

struct pseudo_header {
    u_int32_t source_address;
    u_int32_t dest_address;
    u_int8_t placeholder;
    u_int8_t protocol;
    u_int16_t tcp_length;
};

校验和算法

unsigned short checksum(const char *buf, unsigned size) {
    unsigned sum = 0, i;
    /* Accumulate checksum */
    for (i = 0; i < size - 1; i += 2) {
        unsigned short word16 = *(unsigned short *) &buf[i];
        sum += word16;
    }
    /* Handle odd-sized case */
    if (size & 1) {
        unsigned short word16 = (unsigned char) buf[i];
        sum += word16;
    }
    /* Fold to get the ones-complement result */
    while (sum >> 16) sum = (sum & 0xFFFF)+(sum >> 16);
    /* Invert to get the negative in ones-complement arithmetic */
    return ~sum;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:30:15