用c写一个局域网传文件的程序
时间: 2023-05-17 18:03:18 浏览: 62
可以使用socket库来实现局域网传文件的程序,以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <file_path>\n", argv[0]);
return 1;
}
char *file_path = argv[1];
FILE *fp = fopen(file_path, "rb");
if (fp == NULL) {
printf("Failed to open file %s\n", file_path);
return 1;
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Failed to create socket\n");
return 1;
}
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
printf("Failed to bind socket\n");
return 1;
}
if (listen(sockfd, 5) < 0) {
printf("Failed to listen on socket\n");
return 1;
}
printf("Waiting for client...\n");
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_sockfd < 0) {
printf("Failed to accept client connection\n");
return 1;
}
printf("Client connected: %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
char buffer[BUFFER_SIZE];
int bytes_read;
while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, fp)) > 0) {
if (send(client_sockfd, buffer, bytes_read, 0) < 0) {
printf("Failed to send data\n");
return 1;
}
}
printf("File sent successfully\n");
fclose(fp);
close(client_sockfd);
close(sockfd);
return 0;
}
```
这个程序会监听本地的8888端口,等待客户端连接。当客户端连接后,程序会读取指定的文件并将其内容发送给客户端。注意,这个程序只是一个简单的示例,没有进行任何错误处理和安全性检查,实际使用时需要进行相应的改进。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)