write函数发送结构体数据
时间: 2024-05-16 15:17:18 浏览: 12
要发送结构体数据,可以将结构体数据转换为字符数组,然后使用write函数发送。
以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
typedef struct {
int id;
char name[20];
float salary;
} Employee;
int main() {
int sockfd, bytes_sent;
struct sockaddr_in server_addr;
// 创建套接字
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("Failed to create socket.\n");
return 1;
}
// 设置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
server_addr.sin_addr.s_addr = INADDR_ANY;
// 连接服务器
if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
printf("Failed to connect to server.\n");
return 1;
}
// 准备结构体数据
Employee emp;
emp.id = 123;
strcpy(emp.name, "John");
emp.salary = 5000.0f;
// 将结构体转换为字符数组
char buffer[sizeof(Employee)];
memcpy(buffer, &emp, sizeof(Employee));
// 发送数据
bytes_sent = write(sockfd, buffer, sizeof(Employee));
if (bytes_sent == -1) {
printf("Failed to send data.\n");
return 1;
}
printf("Sent %d bytes of data.\n", bytes_sent);
// 关闭套接字
close(sockfd);
return 0;
}
```
在上面的代码中,我们定义了一个Employee结构体,然后将其转换为字符数组buffer,最后使用write函数发送。注意,在发送时,需要指定发送的数据长度为sizeof(Employee)。
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)