Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
apsrcreatix
GitHub Repository: apsrcreatix/Socket-Programming-With-C
Path: blob/master/08-file-transfer-protocol/server.c
137 views
1
/*
2
* Title : File Transfer Protocol
3
* Name : Aditya Pratap Singh Rajput
4
* Subject : Network Protocols And Programming using C
5
*
6
Note : Please consider the TYPOS in comments.
7
Thanks.
8
*/
9
10
#include "stdio.h"
11
#include "stdlib.h"
12
#include "string.h"
13
//headers for socket and related functions
14
#include <sys/types.h>
15
#include <sys/socket.h>
16
#include <sys/stat.h>
17
//for including structures which will store information needed
18
#include <netinet/in.h>
19
#include <unistd.h>
20
//for gethostbyname
21
#include "netdb.h"
22
#include "arpa/inet.h"
23
24
// defining constants
25
#define PORT 9002
26
#define BACKLOG 5
27
int main()
28
{
29
int size;
30
int socketDescriptor = socket(AF_INET, SOCK_STREAM, 0);
31
struct sockaddr_in serverAddress, clientAddress;
32
33
socklen_t clientLength;
34
35
struct stat statVariable;
36
37
char buffer[100], file[1000];
38
39
FILE *filePointer;
40
bzero(&serverAddress, sizeof(serverAddress));
41
42
serverAddress.sin_family = AF_INET;
43
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
44
serverAddress.sin_port = htons(PORT);
45
46
bind(socketDescriptor, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
47
48
listen(socketDescriptor,BACKLOG);
49
50
printf("Server has started working ...");
51
int clientDescriptor = accept(socketDescriptor,(struct sockaddr*)&clientAddress,&clientLength);
52
53
while(1){
54
bzero(buffer,sizeof(buffer));
55
bzero(file,sizeof(file));
56
recv(clientDescriptor,buffer,sizeof(buffer),0);
57
filePointer = fopen(buffer,"r");
58
stat(buffer,&statVariable);
59
size=statVariable.st_size;
60
fread(file,sizeof(file),1,filePointer);
61
send(clientDescriptor,file,sizeof(file),0);
62
}
63
return 0;
64
}
65