socket以C语音实现linux和windows文件传输
时间: 2023-06-23 10:10:20 浏览: 104
在C语言中实现文件传输可以使用socket编程来完成。下面是一个简单的例子,演示如何在Linux和Windows系统之间传输文件。
首先,我们需要在服务器端创建一个socket,然后监听客户端的连接请求。当有客户端连接时,我们可以接收客户端发送的文件,并将其保存到本地。
服务器端代码如下:
```c
// server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
int main(int argc, char const *argv[]) {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
// create socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// set socket options
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt))) {
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
// bind socket to port
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);
}
// listen for incoming connections
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("Waiting for connections...\n");
// accept incoming connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
printf("Connection established\n");
// receive file from client
FILE *fp;
fp = fopen("output.txt", "w");
while ((valread = read(new_socket, buffer, 1024)) > 0) {
fwrite(buffer, sizeof(char), valread, fp);
}
fclose(fp);
printf("File received and saved as output.txt\n");
// close socket
close(new_socket);
close(server_fd);
return 0;
}
```
接下来是客户端代码,我们需要创建一个socket并连接到服务器,然后将本地文件发送给服务器。
```c
// client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
int main(int argc, char const *argv[]) {
int sock = 0, valread;
struct sockaddr_in serv_addr;
char buffer[1024] = {0};
// create socket file descriptor
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
// set server address and port
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
// connect to server
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
printf("Connected to server\n");
// send file to server
FILE *fp;
fp = fopen("input.txt", "r");
while (!feof(fp)) {
int n = fread(buffer, sizeof(char), 1024, fp);
send(sock, buffer, n, 0);
}
fclose(fp);
printf("File sent\n");
// close socket
close(sock);
return 0;
}
```
这两个程序可以在Linux和Windows系统上编译和运行。为了在Windows上编译,您需要使用Winsock库,例如使用MinGW环境。
阅读全文