-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer_FileIO_TCP.c
More file actions
88 lines (71 loc) · 1.58 KB
/
Server_FileIO_TCP.c
File metadata and controls
88 lines (71 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: %s <port_no>\n", argv[0]);
exit(1);
}
int sfd, cfd, port_no;
port_no = strtoul(argv[1], NULL, 10);
/*
Create your Socket do error checking
Remember socket returns a socket descriptor
SOCK_STREAM --->TCP
or
SOCK_DGRAM --->UDP
AF_INET ------->protocol/address family
*/
if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
exit(2);
}
struct sockaddr_in saddr = {0};
saddr.sin_family = AF_INET;
saddr.sin_port = htons(port_no);
saddr.sin_addr.s_addr = INADDR_ANY;// Accept any ip address
//1. Bind is used for assigning port
if (bind(sfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
{
perror("bind");
close(sfd);
exit(3);
}
//2. waits for incoming connection
if (listen(sfd, 5) < 0)
{
perror("listen");
close(sfd);
exit(4);
}
//3. Accepts the incoming connection
struct sockaddr_in caddr = {0};
socklen_t len = sizeof(caddr);
if ((cfd = accept(sfd, (struct sockaddr *)&caddr, &len)) < 0)
{
perror("accept");
exit(5);
}
// To make a program like ECHO
char buf[100], cptr[2];
int ret = 0, size = 0;
if ((ret = recv(cfd, buf, 100, 0)) < 0)
{
perror("recv");
close(cfd);
close(sfd);
exit(6);
}
FILE *fps = NULL;
fps = fopen("server.txt", "w");
fwrite(buf, 1, ret, fps);
close(cfd);
close(sfd);
return 0;
}