Click here to Skip to main content
15,893,814 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
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.


C++
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);


}
Posted
Comments
Sergey Alexandrovich Kryukov 7-Nov-14 14:43pm    
What's the problem? For example, consider using std::string.
—SA

1 solution

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.

C++
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);


If your message design allows variable length packets, use the value returned by sprintf as the size of the packet.
 
Share this answer
 
v2
Comments
nv3 7-Nov-14 17:38pm    
Your approach looks good. But watch what happens when the payload is larger than 256 bytes! I guess, you should subtract 3 from the "length -1" argument. Also the -3 has to be applied in the comparison to "sizeof packet".
[no name] 10-Nov-14 12:08pm    
Good point about the comparison. -3 not needed for sprintf.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900