Sending a C char array over a socket

I want to send an array of characters via a tcp socket to unix.

My first idea was to use a regular char array for the structure to be sent over the socket:

typedef struct __attribute__((packed)) { uint8_t type; uint8_t id_index; char char_value[STR_MSG_MAX]; } a_msg; 

Just because C char is always 8 bits. However, after some googling, I found that even if char is always 8 bits longer, the underlying representation may actually be a 32-bit integer. So I feel that char may not be the best way to represent a string in a message that will be sent over a socket from FreeBSd to Linux (or type some other unixes if you want =) ...).

stdint.h is present in all modern unixes for the day (I hope), and my thoughts are that perhaps an uint8_t or int8_t array could do the trick.

 typedef struct __attribute__((packed)) { uint8_t type; uint8_t id_index; uint8_t char_value[STR_MSG_MAX]; } a_msg; 

or

 typedef struct __attribute__((packed)) { uint8_t type; uint8_t id_index; int8_t char_value[STR_MSG_MAX]; } a_msg; 

However, uint8_t is an unsigned char, and int8_t is a signed char. The C char standard is neither the implementation of undefined, as I understand it.

My questions: What is the best way to represent a character array (string) in C that will be sent via tcp / ip in a platform independent nix (Linux, FreeBSD, etc.).

+4
source share
4 answers

Although char can be wider than 8 bits wide, it should always be the (equal) narrowest type. (Since among other reasons, sizeof(char) is defined as 1).

So, if the platform provides int8_t , then char should also be exactly 8 bits (since char separately limited to at least 8 bits). That means you can use char .

+4
source

I personally would like something like:

 typedef struct __attribute__((packed)) { uint8_t type; uint8_t id_index; uint8_t padding[2]; //this is to align to 32bit boundary uint8_t char_value[STR_MSG_MAX]; } a_msg; 

But it will work without filling.

In C a char always 8 bits. Thus, a char array is always an array of bytes. However, the character literal 'x' is 32 bits. This can be verified using the sizeof operator in a character literal. You will also see that all functions that return a single character of type getch return int . The reason is that we need a way to specify End of File EOF. This can only be done using a value outside the 8-bit range.

+1
source

You cannot say that you are sending whit c. This information is not transmitted.

All you have to do is:

 char* buffer = (char*)(&a_msg); 

The safest way is to use unsigned characters, if possible.

0
source

I think the idea of โ€‹โ€‹packing a structure is the way to go. I would write test code to make sure it works. Make sizeof (a_msg) to see what size it has. You should be able to determine if the package worked without sending messages through the socket.

0
source

All Articles