gpt4 book ai didi

C 创建原始 UDP 数据包

转载 作者:太空宇宙 更新时间:2023-11-04 04:16:36 26 4
gpt4 key购买 nike

我有兴趣创建一个 DNS(使用 UDP 协议(protocol)发送它)响应数据包,但是我发现关于如何创建您自己的数据包的信息有限。

大部分教程都是这样https://opensourceforu.com/2015/03/a-guide-to-using-raw-sockets/

他们使用结构来填充字段并将它们连接成 1 个序列。但我担心编译器可以填充结构,使其“损坏”(使数据包比应有的长度更长)

我完全知道有一些结构属性不允许编译器填充结构,但我不想使用它们

谁能给我一些关于数据包创建的资源。我可以使用 Libpcap 和原始套接字

最佳答案

你这样做:

// helper function to add uint32_t to a buffer
char *append_uint32(char *buf_position, uint32_t value) {
// network protocols usually use network byte order for numbers,
// htonl is POSIX function so you may have to make your own on other platform
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/htonl.html
value = htonl(value);
memcpy(buf_postion, &value, sizeof value);
return buf_position + sizeof value;
}

// example code using the function:
// generate packet with numbers 0...9 in network byte order
void func() {
char buf[sizeof(int32_t) * 10];
char *bptr = buf;
for(uint32_t i=0; i<10; ++i) {
bptr = append_uint32(bptr, i);
}
// do something with buf (use malloc instead of stack if you want return it!)
}

关于C 创建原始 UDP 数据包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51435806/

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