我在ubuntu linux上用C做一个简单的套接字示例。我知道send()
和recv()
函数不一定要等待发送/接收整个消息。我正在尝试发送一个简单的hello world消息。我知道它的大小(至少我认为是这样),所以我想知道可以添加到我的send()
和recv()
实现中以等待已知消息大小的内容。
阅读send()
和recv()
的手册页时,函数原型看起来像这样:ssize_t send(int sockfd, const void* buf, size_t len, int flags)
和recv()使用相同的原型。我的问题是它们返回什么-字节数或字符数?无论哪种方式,为什么总是8?
测试消息的大小时,无论我使用char* message = "test";
还是char* message = "Hello world, I clearly do not understand what is going on here";
,sizeof()运算符始终返回8
客户代码
fprintf(stdout, "client connected to %s:%d\n", hostname, portno);
printf("Size of %s is : %lu\n", message, sizeof(message));
printf("other size of %s is %lu, message, sizeof(message)/sizeof(char));
ssize_t written_bytes = send(socket_fd, message, sizeof(message),0);
assert(written_bytes == sizeof(message)); //Shouldn't the code fail here?
printf("written bytes: %lu\n", written_bytes);
我会添加服务器代码,但是毫无疑问的是,如果它从不发送信息,为什么它不接收所有信息。
最佳答案
send
和recv
返回分别发送和接收的字节数。当您使用sizeof
运算符测试消息的大小时,实际上是在计算计算机上8
字节的指针大小。