gpt4 book ai didi

c - 在 tcp header 中设置最大段大小

转载 作者:可可西里 更新时间:2023-11-01 02:36:50 24 4
gpt4 key购买 nike

我正在组装一个端口扫描器作为学习练习。我的问题是我试图在 TCP header 中设置最大段大小选项 (MSS)。我查看了 tcp.h,但我不知道如何设置它。我希望有这样的选项:

tcp_header->mss(32000);

tcp.h 中有与上述类似的内容,但不在正确的结构中。不可否认,我对阅读结构定义还是很陌生,我对 tcp.h 没有太大的了解,所以最后我尝试将必要的字节添加到 TCP header 的末尾:

struct tcphdr *CreateTcpHeader()
{
struct tcphdr *tcp_header;

tcp_header = (struct tcphdr *)malloc(sizeof(struct tcphdr)+4*sizeof(int));


tcp_header->source = htons(SRC_PORT);
tcp_header->dest = htons(DST_PORT);
tcp_header->seq = htonl(0);
tcp_header->ack_seq = htonl(0);
tcp_header->res1 = 0;
tcp_header->doff = (sizeof(struct tcphdr))/4;
tcp_header->syn = 1;
tcp_header->window = htons(4096);
tcp_header->check = 0; /* Will calculate the checksum with pseudo-header later */
tcp_header->urg_ptr = 0;


/*memcpy the mss data onto the end of the tcp header. */
int mssCode = 2;
int mssLength = 4;
uint16_t mss = htonl(32000);
int offset = sizeof(struct tcphdr);
memcpy( (tcp_header+offset), &mssCode, 1 );
memcpy( (tcp_header+offset+1), &mssLength, 1 );
memcpy( (tcp_header+offset+2), &mss, 2);

return (tcp_header);
}

但是在我写完之后很明显这不是一个真正的解决方案,而且它仍然不起作用 :P 那么有没有更好的方法?

最佳答案

tcp.h 中的struct tcphdr 定义了TCP header 的必需部分。 (查看 TCP header,您可以将 struct tcphdr 中的定义与 header 中出现的实际位相匹配。)C 中的结构具有恒定大小,但 TCP 允许可选数据。 header 长度字段(结构中的doff)是 header 的总长度,包括选项,因此您需要添加一个词来说明 MSS 选项:

tcp_header->doff = (sizeof(struct tcphdr))/4 + 1;

让我们为 MSS 选项定义一个结构:

struct tcp_option_mss {
uint8_t kind; /* 2 */
uint8_t len; /* 4 */
uint16_t mss;
} __attribute__((packed));

现在您可以按照正确的顺序填充结构:

/*memcpy the mss data onto the end of the tcp header. */
struct tcp_option_mss mss;
mss.kind = 2;
mss.len = 4;
mss.mss = htons(32000);

让我们更进一步,为你的数据包定义一个结构,让编译器帮助我们:

struct tcphdr_mss {
struct tcphdr tcp_header;
struct tcp_option_mss mss;
};

(你可能需要在末尾添加一个end-of-option-list选项,nop options将选项列表填充到8字节。)

现在我们可以把所有的部分放在一起:

struct tcphdr *CreateTcpHeader()
{
struct tcphdr_mss *tcp_header;

tcp_header = malloc(sizeof(struct tcphdr_mss));

tcp_header->tcp_header.source = htons(SRC_PORT);
tcp_header->tcp_header.dest = htons(DST_PORT);
tcp_header->tcp_header.seq = htonl(0);
tcp_header->tcp_header.ack_seq = htonl(0);
tcp_header->tcp_header.res1 = 0;
tcp_header->tcp_header.doff = (sizeof(struct tcphdr_mss))/4;
tcp_header->tcp_header.syn = 1;
tcp_header->tcp_header.window = htons(4096);
tcp_header->tcp_header.check = 0; /* Will calculate the checksum with pseudo-header later */
tcp_header->tcp_header.urg_ptr = 0;

tcp_header->mss.kind = 2;
tcp_header->mss.len = 2;
tcp_header->mss.mss = htons(32000);

return (tcp_header);
}

关于c - 在 tcp header 中设置最大段大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1295921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com