I made a client in C#, and I would like to have a server build under Linux, in C.
I use a prefix with “message” length for every “message”.
I encode it to byte[] array by using BitConverter.GetBytes() (4 bytes array).
After that I send it by
socket.Send(prefix, prefix.Length, 0);
The C server on Linux can’t read the number. It displays a strange character, despite it read 4 bytes.
Linux side looks like
char prefix[4];
int bytes = 0;
bytes = recv(s, prefix, 4, 0);
printf("%s", prefix);
If I encode the number by using Encoding.UTF8.GetBytes(), Linux understands it correctly.
I tested it, and it looks the problem is only when the programs are coded in these 2 different languages.
What’s going on?
BitConverter.GetBytes()will give you a binary representation – something that is not a printable character in most cases (try the int 0x20202020, this should give you one or more spaces), but perfect for processing purpouses. You can print it with something likeprintf("%d",the_int_variable)Encoding.UTF8.GetBytes()will give you s string representation – something, that is nice for printing it to the console, but suboptimal for processing.Edit
After your updated question, change
printf("%s", prefix);toprintf("%d", prefix);after changing prefix to type int and retry.