I'm working on sending encrypted data over sockets in C. Everything works fine until I realized that the size of the data being sent is much larger than what it supposed to be. The piece of code below describes the situation:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
char temp[100], buffer[100];
int n = 1234567890;
sprintf(temp, "%d", n);
printf("Original n has size: %d\n", sizeof(n)); // 4
printf("Buffer size: %d\n", strlen(temp)); //10
printf("Buffer: %s", temp);
}
The problem is the original number is stored as a 4-byte integer, while the buffer is stored character by character, so what is going to be sent through the socket is not 4 bytes, but 10s of one byte character.
I wonder is there any way to send binary data as raw?
Check the send(2) system call more carefully. It accepts const void *buf
. Its NOT char*
. As of being void *
you can send any type of data.
This should work,
int n = 1234567890;
int net_n = hton(n);
send(sockfd, const (void *)(&net_n), sizeof(n), 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With