通过 C 套接字发送原始二进制数据? [英] Send raw binary data over C socket?

查看:69
本文介绍了通过 C 套接字发送原始二进制数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 C 语言的套接字发送加密数据.一切正常,直到我意识到发送的数据大小比预期的大得多.下面的一段代码描述了这种情况:

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);
}

问题是原来的数字存储为一个4字节的整数,而缓冲区是逐个字符存储的,所以通过socket发送的不是4个字节,而是一个字节的10个字符.

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?

推荐答案

检查 send(2) 系统调用更加小心.它接受 const void *buf.它的NOT char*.从 void * 开始,您可以发送任何类型的数据.

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.

这应该可行,

int n = 1234567890;
int net_n = hton(n);
send(sockfd, const (void *)(&net_n), sizeof(n), 0)

这篇关于通过 C 套接字发送原始二进制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆