使用linux c语言编写文件传输工具,使用
时间: 2024-02-17 16:02:25 浏览: 216
使用c语言实现文件传输
Linux C语言编写文件传输工具,可以使用Socket编程实现。下面是一个简单的例子,演示了如何使用Socket在客户端和服务器之间传输文件。
1. 服务器端:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define BUF_SIZE 1024
int main()
{
int sockfd, newsockfd, len;
struct sockaddr_in server_addr, client_addr;
char buffer[BUF_SIZE];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
if (listen(sockfd, 5) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("Server started, waiting for client...\n");
while (1) {
len = sizeof(client_addr);
newsockfd = accept(sockfd, (struct sockaddr *)&client_addr, &len);
if (newsockfd == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
printf("Accepted connection from %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
FILE *fp = fopen("test.txt", "w");
if (fp == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while (1) {
int n = recv(newsockfd, buffer, BUF_SIZE, 0);
if (n == -1) {
perror("recv");
exit(EXIT_FAILURE);
} else if (n == 0) {
printf("Connection closed by client\n");
break;
}
fwrite(buffer, sizeof(char), n, fp);
}
fclose(fp);
close(newsockfd);
}
close(sockfd);
return 0;
}
```
2. 客户端:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8888
#define BUF_SIZE 1024
int main()
{
int sockfd, len;
struct sockaddr_in server_addr;
char buffer[BUF_SIZE];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(EXIT_FAILURE);
}
printf("Connected to server\n");
FILE *fp = fopen("test.txt", "r");
if (fp == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while (1) {
int n = fread(buffer, sizeof(char), BUF_SIZE, fp);
if (n == 0) {
break;
}
int m = send(sockfd, buffer, n, 0);
if (m == -1) {
perror("send");
exit(EXIT_FAILURE);
}
}
fclose(fp);
close(sockfd);
return 0;
}
```
注意,这只是一个简单的示例代码,实际使用中还需要处理异常、关闭资源等。同时,需要注意的是,这种方式只适用于小文件传输,如果需要传输大文件,需要使用分块传输或者其他方式。
阅读全文