Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #define PORT htons(12221)
- void ServeConnection(int sock)
- {
- char path[512];
- long dl_of_the_file, sent, sent_in_total, read;
- struct stat fileinfo;
- unsigned char buffer[1024];
- FILE* file;
- printf("Give the path to the file: \n");
- memset(path, 0, 512);
- scanf("%s",path);
- if (stat(path, &fileinfo) < 0)
- {
- printf("Child: I can't obtain information about a file\n");
- return;
- }
- if (fileinfo.st_size == 0)
- {
- printf("Child: filesize 0\n");
- return;
- }
- printf("Child: filesize : %d\n", fileinfo.st_size);
- dl_of_the_file = fileinfo.st_size;
- sent_in_total = 0;
- file = fopen(path, "rb");
- if (file == NULL)
- {
- printf("Child: error at opening a file\n");
- return;
- }
- while (sent_in_total < dl_of_the_file)
- {
- read = fread(buffer, 1, 1024, file);
- sent = send(sock, buffer, read, 0);
- if (read != sent)
- break;
- sent_in_total += sent;
- printf("Child: total sent %ld\n", sent_in_total);
- }
- if (sent_in_total == dl_of_the_file)
- {
- printf("Child: file sent ok\n");
- }
- else
- {
- printf("Child: error at sending a file\n");
- }
- fclose(file);
- return;
- }
- int main()
- {
- struct sockaddr_in adr;
- socklen_t dladr = sizeof(struct sockaddr_in);
- int sock_listen, sock_client;
- sock_listen = socket(PF_INET, SOCK_STREAM, 0);
- adr.sin_family = AF_INET;
- adr.sin_port = PORT;
- adr.sin_addr.s_addr = INADDR_ANY;
- memset(adr.sin_zero, 0, sizeof(adr.sin_zero));
- if (bind(sock_listen, (struct sockaddr*) &adr, dladr) < 0)
- {
- printf("Parent: bind failed\n");
- return 1;
- }
- listen(sock_listen, 10);
- printf("Server running...\n");
- while(1)
- {
- dladr = sizeof(struct sockaddr_in);
- sock_client = accept(sock_listen, (struct sockaddr*) &adr, &dladr);
- if (sock_client < 0)
- {
- printf("Parent: accept error\n");
- continue;
- }
- printf("Parent: connection from %s:%u\n",
- inet_ntoa(adr.sin_addr),
- ntohs(adr.sin_port));
- printf("Parent: I'm creating child process\n");
- if (fork() == 0)
- {
- //child
- printf("Child: start serving)\n");
- ServeConnection(sock_client);
- printf("Child: closing socket\n");
- close(sock_client);
- printf("Child: end of the process\n");
- exit(0);
- }
- else
- {
- //parent
- printf("Parent: return to listening)\n");
- continue;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement