Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send raw binary data over C socket?

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?

like image 255
Max Avatar asked Jan 16 '23 06:01

Max


1 Answers

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)
like image 125
Shiplu Mokaddim Avatar answered Jan 22 '23 15:01

Shiplu Mokaddim