如何在不改变格式的情况下在C ++中安全地预置字符串? [英] How can I prepend a string safely in C++ without changing the format?

查看:66
本文介绍了如何在不改变格式的情况下在C ++中安全地预置字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的UDP服务器和客户端对,我需要在0到255之间添加一个数字到c字符串,为了做到这一点,我需要将数字转换为c字符串。 />


但是,我不确定这是如何安全地完成的,好像我在数字和c字符串之间得到一个空字符,当我发生时会产生很多副作用通过网络发送整个C字符串,我在另一边读取它。



如果我得到数字0并将其转换为c字符串将我在char nb [3]数组中得到1和NULL,我将在char mess [256]之前加入?如果是这样的话,你能建议一个安全的方法吗?





格式如下:前3个字节必须包含一个数字,其余的将包含一个字符串后跟一个空字符。




I am making a simple UDP server and client pair and I need to prepend a number between 0 and 255 to a c-string, and in order to do that I need to convert the number into a c-string.

However, I am not sure how this can be safely done as if I get a null char between the number and the c-string, it will cause numerous side effects when I send the entire c-string through the network and I read it on the other side.

If I get the number 0 and I convert it to a c-string will I get 1 and NULL inside the char nb[3] array, which I will prepend to char mess[256]? If it is the case, can you suggest a safe way to do it?


The format is as follows: the first 3 bytes must contain a number, the rest will contain a string followed by a null char.


int main ()
{
    char number[3]; //if I put 1 in there I will have 1 null and null
    char message[256];
    char packet[259]; //first 3 bytes contain a number
    ...
    strcat(number, message);
    sendto(s, packet, 259, 0, to, tolen);


}

推荐答案

你的代码看起来比C ++更多C 。



我看到的一个问题是你的strcat参数是倒退的。将消息[256]连接到数字[3]是不安全的。



不要使用strcat。计算长度并使用memcpy。



由于数字前缀有三个字节,请考虑使用前导零。



sprintf(或sprintf_s)可以在这里工作。



You code looks to be more C than C++.

One problem I see is your parameters to strcat are backwards. Concatenating message[256] to number[3] isn't safe.

Don't use strcat. Calculate the length and use memcpy.

Since you have three bytes for the numeric prefix, consider using leading zeroes.

sprintf (or sprintf_s) would work here.

char packet[259] = {0};
int number = 13;
const char payload[] = "Payload";
int length = sizeof payload;
// 3 for header, 1 for terminating nul.
if ( (length + 4) >= sizeof packet)
    fprintf(stderr, "too long!\n");
sprintf(packet, "%03d%-0.*s", number, length - 1, payload);
sendto(s, packet, sizeof packet, 0, to, tolen);





如果您的消息设计允许可变长度数据包,请使用sprintf返回的值作为数据包的大小。



If your message design allows variable length packets, use the value returned by sprintf as the size of the packet.

这篇关于如何在不改变格式的情况下在C ++中安全地预置字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆