网络文件传输 自定义协议二进制传输C语言
时间: 2023-07-21 10:09:05 浏览: 195
文件传输协议的C语言实现
4星 · 用户满意度95%
您好!对于网络文件传输,您可以使用自定义协议进行二进制传输。使用C语言可以实现这一功能。以下是一个简单的示例代码,用于在客户端和服务器之间传输文件的二进制数据:
服务器端代码(server.c):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
FILE *file;
// 创建套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// 绑定套接字到指定端口
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// 接受连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 接收文件名
valread = read(new_socket, buffer, BUFFER_SIZE);
printf("Received file name: %s\n", buffer);
// 打开文件
file = fopen(buffer, "wb");
if (file == NULL) {
perror("failed to open file");
exit(EXIT_FAILURE);
}
// 接收并写入文件内容
while ((valread = read(new_socket, buffer, BUFFER_SIZE)) > 0) {
fwrite(buffer, 1, valread, file);
}
printf("File received successfully.\n");
fclose(file);
close(new_socket);
close(server_fd);
return 0;
}
```
客户端代码(client.c):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int sock = 0, valread;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
FILE *file;
// 创建套接字
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 将IP地址从字符串转换为网络地址
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
// 连接到服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
// 发送文件名
char *filename = "file.txt";
send(sock, filename, strlen(filename), 0);
// 打开文件
file = fopen(filename, "rb");
if (file == NULL) {
perror("failed to open file");
exit(EXIT_FAILURE);
}
// 读取文件内容并发送
while ((valread = fread(buffer, 1, BUFFER_SIZE, file)) > 0) {
send(sock, buffer, valread, 0);
}
printf("File sent successfully.\n");
fclose(file);
close(sock);
return 0;
}
```
请注意,这只是一个简单的示例代码,仅用于演示如何使用C语言进行网络文件传输。在实际应用中,您可能需要添加错误处理、完整性校验等功能来提高安全性和可靠性。
阅读全文