乐闻世界logo
搜索文章和话题

Send and Receive a file in socket programming in Linux with C/ C ++ ( GCC / G ++)

4个答案

1
2
3
4

In Linux systems, C/C++ can be used for socket programming to send and receive files via TCP or UDP protocols. Below, I'll demonstrate a simple example of using the TCP protocol (which provides reliable, connection-oriented data transmission) for file transfer.

1. Server-side Program

The server-side task is to listen on a port, accept client connections, read the file data sent by the client, and write it to local storage. Below is a simple server-side example code:

c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #define PORT 8080 #define BUFFER_SIZE 1024 int main() { int server_fd, new_socket; struct sockaddr_in address; int addrlen = sizeof(address); char buffer[BUFFER_SIZE] = {0}; char *filename = "received_file.txt"; // Create socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Bind socket to localhost's 8080 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 on this port if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } // Accept an incoming connection if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } // Read data and write to file FILE *file = fopen(filename, "wb"); int bytes_read; while ((bytes_read = read(new_socket, buffer, BUFFER_SIZE)) > 0) { fwrite(buffer, 1, bytes_read, file); } fclose(file); close(new_socket); close(server_fd); return 0; }

2. Client-side Program

The client-side task is to connect to the server, read local file data, and send the data to the server. Below is the corresponding client-side example code:

c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #define PORT 8080 #define BUFFER_SIZE 1024 int main() { int sock = 0; struct sockaddr_in serv_addr; char *filename = "file_to_send.txt"; char buffer[BUFFER_SIZE] = {0}; // Create socket file descriptor 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); // Convert IPv4 address 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; } // Read and send file content FILE *file = fopen(filename, "rb"); int bytes_read; while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, file)) > 0) { write(sock, buffer, bytes_read); } fclose(file); close(sock); return 0; }

Explanation

  • Server-side uses the socket(), bind(), listen(), and accept() functions to set up the TCP server and accept client connections.
  • Client-side uses the socket() and connect() functions to establish a connection to the server.
  • File data is transmitted through sockets in binary format.
  • The read() and write() functions facilitate data transfer between sockets and files.

This is a basic example; in practical applications, you may need to handle errors, enhance security, or improve performance.

2024年6月29日 12:07 回复

In Linux systems, using C/C++ for socket programming is a common approach to handle network communication. In socket programming, sending and receiving files involves steps such as creating sockets, establishing connections to servers, reading file content, and transmitting data over the network. Next, I will provide a detailed explanation of the main steps for implementing file transfer in Linux using C/C++ (GCC/G++) and provide code examples.

1. Creating Sockets

First, a socket must be created for network communication. We typically use the socket() function to create the socket.

c
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int sockfd; struct sockaddr_in servaddr; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { perror("socket creation failed"); exit(EXIT_FAILURE); } // Set server address servaddr.sin_family = AF_INET; servaddr.sin_port = htons(12345); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

2. Connecting to the Server

After creating the socket, use the connect() function to establish a connection to the server.

c
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0) { perror("connection with the server failed"); exit(EXIT_FAILURE); }

3. Reading and Sending Files

After connecting to the server, you can start reading the local file and sending it through the socket.

c
#include <stdio.h> #include <unistd.h> #include <fcntl.h> int fd; ssize_t read_bytes, sent_bytes; char buffer[1024]; fd = open("example.txt", O_RDONLY); if (fd < 0) { perror("failed to open file"); close(sockfd); exit(EXIT_FAILURE); } while ((read_bytes = read(fd, buffer, sizeof(buffer))) > 0) { sent_bytes = send(sockfd, buffer, read_bytes, 0); if (sent_bytes < 0) { perror("failed to send file"); close(fd); close(sockfd); exit(EXIT_FAILURE); } } close(fd);

4. Receiving Files

The server-side code is similar, but it uses the recv() function to receive data and writes the received data to a file.

c
ssize_t recv_bytes, write_bytes; int fd = open("received.txt", O_WRONLY | O_CREAT, 0666); if (fd < 0) { perror("failed to open file for writing"); exit(EXIT_FAILURE); } while ((recv_bytes = recv(sockfd, buffer, sizeof(buffer), 0)) > 0) { write_bytes = write(fd, buffer, recv_bytes); if (write_bytes < 0) { perror("failed to write to file"); close(sockfd); close(fd); exit(EXIT_FAILURE); } } close(fd);

5. Closing Sockets and Cleaning Resources

After file transfer is complete, close the socket and file descriptors, and release any occupied resources.

c
close(sockfd);

This is the basic process for sending and receiving files using C/C++ in the Linux environment. By properly managing error handling and resource cleanup, you can ensure the robustness and efficiency of the program.

2024年6月29日 12:07 回复

When using C/C++ (GCC/G++) for socket programming in Linux to send and receive files, the basic steps include establishing a connection, sending file information, sending file data, and closing the connection. The following is a simple example demonstrating how to implement these steps.

1. Creating Sockets

First, create a socket on both the sender and receiver ends. Sockets serve as the fundamental building blocks for network communication.

c
#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int sockfd; struct sockaddr_in servaddr; // Create socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket creation failed"); exit(EXIT_FAILURE); } // Set server address servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // Connect to server if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("connect failed"); exit(EXIT_FAILURE); }

2. Sending File Information

Before transmitting file content, send preliminary file information such as file size or filename to enable the receiver to prepare appropriately.

c
#include <stdio.h> #include <stdlib.h> void send_file_info(int sockfd, const char* filename) { char buffer[1024]; FILE *file = fopen(filename, "rb"); if (file == NULL) { perror("File opening failed"); return; } // Get file size fseek(file, 0L, SEEK_END); long filesize = ftell(file); rewind(file); // Send file size sprintf(buffer, "%ld", filesize); send(sockfd, buffer, sizeof(buffer), 0); }

3. Sending File Data

After sending file information, proceed to transmit the actual file data.

c
void send_file_data(int sockfd, const char* filename) { char buffer[1024]; FILE *file = fopen(filename, "rb"); if (file == NULL) { perror("File opening failed"); return; } int bytes_read; while ((bytes_read = fread(buffer, 1, sizeof(buffer), file)) > 0) { send(sockfd, buffer, bytes_read, 0); } fclose(file); }

4. Receiving Files

On the receiver side, receive file data based on the file information provided by the sender.

c
void receive_file(int sockfd, const char* out_filename) { char buffer[1024]; FILE *file = fopen(out_filename, "wb"); if (file == NULL) { perror("File opening failed"); return; } int bytes_received; while ((bytes_received = recv(sockfd, buffer, sizeof(buffer), 0)) > 0) { fwrite(buffer, 1, bytes_received, file); } fclose(file); }

5. Closing Sockets

After data transmission completes, ensure the socket is properly closed.

c
close(sockfd);

Notes

  • Implement thorough error handling, including appropriate cleanup when network operations fail.
  • Account for network latency and interruptions to handle partial reads and writes.
  • Security is a critical consideration, especially when transmitting sensitive data.

The above provides a basic framework and example code for file transfer using C/C++ in Linux.

2024年6月29日 12:07 回复

Socket programming in Linux with C/C++ utilizes the POSIX socket API. In this example, we'll demonstrate sending and receiving files via a simple TCP connection. The implementation is divided into two parts: the server side and the client side.

1. Server Side

The server listens for incoming client connections, receives files, and saves them to disk.

c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <netinet/in.h> #include <sys/socket.h> #define PORT 8080 #define BUFFER_SIZE 4096 int main() { int server_fd, new_socket; struct sockaddr_in address; int addr_len = sizeof(address); char buffer[BUFFER_SIZE] = {0}; FILE *file_ptr; // Create socket if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Define socket type address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); // Bind socket if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } // Listen for connections if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } // Accept client connection if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addr_len)) < 0) { perror("accept"); exit(EXIT_FAILURE); } // Open file for writing file_ptr = fopen("received_file", "wb"); if (file_ptr == NULL) { perror("Failed to open file"); exit(EXIT_FAILURE); } // Read data from socket and write to file int bytes_read; while ((bytes_read = recv(new_socket, buffer, BUFFER_SIZE, 0)) > 0) { fwrite(buffer, 1, bytes_read, file_ptr); } // Close file fclose(file_ptr); // Close socket close(new_socket); close(server_fd); return 0; }

2. Client Side

The client connects to the server, reads the file, and sends the data.

c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #define SERVER_IP "127.0.0.1" #define PORT 8080 #define BUFFER_SIZE 4096 int main() { int sock = 0; struct sockaddr_in serv_addr; char buffer[BUFFER_SIZE] = {0}; FILE *file_ptr; // Create socket if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Socket creation error"); exit(EXIT_FAILURE); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // Convert IP address to binary if(inet_pton(AF_INET, SERVER_IP, &serv_addr.sin_addr) <= 0) { perror("Invalid address/ Address not supported"); exit(EXIT_FAILURE); } // Connect to server if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { perror("Connection Failed"); exit(EXIT_FAILURE); } // Open file for reading file_ptr = fopen("file_to_send", "rb"); if (file_ptr == NULL) { perror("Failed to open file"); exit(EXIT_FAILURE); } // Read file and send data int bytes_read; while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, file_ptr)) > 0) { send(sock, buffer, bytes_read, 0); } // Close file fclose(file_ptr); // Close socket close(sock); return 0; }

The provided code illustrates basic file transfer in Linux using C/C++. On the server side, it sets up the socket, accepts connections, and saves received data to a file. The client connects to the server, reads a local file, and transmits the data. This is a fundamental example; for practical applications, additional error handling and security measures are recommended.

2024年6月29日 12:07 回复

你的答案