gpt4 book ai didi

c - 如何创建自己的数据包以通过 UDP 发送?

转载 作者:行者123 更新时间:2023-12-01 13:01:35 25 4
gpt4 key购买 nike

我正在用实现 TFTP 协议(protocol)的 C 编写自己的客户端-服务器应用程序。在阅读了 TFTP 的 RFC 并制作了一个简单的套接字客户端-服务器应用程序之后,现在我对如何创建必须为 TFTP 协议(protocol)创建的特定数据包感到有些困惑。

比如WRQ包就得这样:

        2 bytes     string    1 byte     string   1 byte
------------------------------------------------
| Opcode | Filename | 0 | Mode | 0 |
------------------------------------------------

摘自官方RFC

我有一个 .h 文件,我在其中定义了数据包的所有结构,但我不确定我是否做对了,而且我在网上找到信息也不是很幸运。

我为这个数据包创建的结构是:

    struct WRQ {
signed short int opcode; //2 bytes
char * filename; // N bytes
char zero_0; // 1 byte
char * mode; // N Bytes
char zero_1; // 1 byte
};

我有两个疑惑:

a) 当我创建一个 sizeof(struct WRQ) 时,它返回 20 个字节。这不是我想要的尺寸。为什么会这样?

b) 我必须如何定义字符串?因为我希望服务器自己接收字符串,而且我认为,这样,它将接收指向客户端机器中的字符串的指针。

我希望一切都清楚,你可以帮助我,因为我现在被困住了!

最佳答案

以下代码(没有错误检查)是构建数据包并发送它的一种可能方法。请注意,它假定 filenamemode 都不为 NULL。我不知道这是否是一个有效的假设。即使是,在实际代码中使用它们之前检查 NULL 也是明智的做法:

struct WRQ *p;
int packetLen;
char *buf;
char *pos;
int ret;

// compute packet length. Start with fixed size data
packetLen = sizeof( p->opcode ) + sizeof( p->zero_0 ) + sizeof( p->zero_1 );
// This assumes (possibly incorrectly) that filename and mode are not null
packetLen += strlen( p->filename ) + 1;
packetLen += strlen( p->mode ) + 1;

// allocate the buffer
buf = malloc( packetLen );
pos = buf;

// and start filling it in
// I am assuming (but didn't study the RFC that it should be network byte order)
*(signed short int*)pos = htons( p->opcode );
pos += sizeof( p->opcode );
strcpy( pos, p->filename );
pos += strlen( p->filename ) + 1;
*pos = p->zero_0;
strcpy( pos, p->mode );
pos += strlen( p->mode ) + 1;
*pos = p->zero_1;

ret = send( s, buf, packetLen, flags );

free( buf );

关于c - 如何创建自己的数据包以通过 UDP 发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5612673/

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