Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <stdint.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- int main() {
- const int PORT = 8080;
- const int BUFFER_SIZE = 1024;
- int client_socket;
- struct sockaddr_in server_addr, client_addr;
- char buffer[BUFFER_SIZE];
- socklen_t addr_len = sizeof(client_addr);
- int sock = socket(AF_INET, SOCK_STREAM, 0);
- if (sock < 0) {
- perror("Socket failed");
- exit(EXIT_FAILURE);
- }
- server_addr.sin_family = AF_INET;
- server_addr.sin_addr.s_addr = INADDR_ANY;
- server_addr.sin_port = htons(PORT);
- if (bind(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
- perror("Bind failed");
- exit(EXIT_FAILURE);
- }
- if (listen(sock, 1) < 0) {
- perror("Listening failed");
- exit(EXIT_FAILURE);
- }
- printf("Server listening on port %d...\n", PORT);
- client_socket = accept(sock, (struct sockaddr *)&client_addr, &addr_len);
- if (client_socket < 0) {
- perror("Accept failed");
- exit(EXIT_FAILURE);
- }
- printf("Client connected.\n");
- uint32_t argc;
- if (read(client_socket, &argc, sizeof(argc)) < 0) {
- perror("Failed to read argc");
- close(client_socket);
- close(sock);
- exit(EXIT_FAILURE);
- }
- argc = ntohl(argc);
- printf("%zu file(s) will be received.\n", (unsigned long)argc);
- char title_list[argc][BUFFER_SIZE];
- for (int i = 0; i < argc;) {
- if (read(client_socket, title_list[i], BUFFER_SIZE) <= 0) {
- perror("Failed to read file name");
- close(client_socket);
- close(sock);
- exit(EXIT_FAILURE);
- }
- if (title_list[i][0]) {
- i++;
- }
- }
- for (int i = 0; i < argc; i++) {
- FILE *f = fopen(title_list[i], "wb");
- printf("Receiving file %d: %s\n", i + 1, title_list[i]);
- if (f == NULL) {
- perror("Error opening file for writing");
- close(client_socket);
- close(sock);
- exit(EXIT_FAILURE);
- }
- while (1) {
- memset(buffer, 0, BUFFER_SIZE);
- ssize_t bytes_read = read(client_socket, buffer, BUFFER_SIZE);
- if (bytes_read < 0) {
- perror("Error reading from client socket");
- fclose(f);
- close(client_socket);
- close(sock);
- exit(EXIT_FAILURE);
- }
- if (bytes_read == 0) {
- break;
- }
- if (fwrite(buffer, sizeof(char), bytes_read, f) != bytes_read) {
- perror("Error writing to file");
- fclose(f);
- close(client_socket);
- close(sock);
- exit(EXIT_FAILURE);
- }
- }
- fclose(f);
- }
- close(client_socket);
- close(sock);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement