-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer_Chat_TCP.c
More file actions
104 lines (86 loc) · 1.83 KB
/
Server_Chat_TCP.c
File metadata and controls
104 lines (86 loc) · 1.83 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#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
while(1){
char rcbuf[50] = {0}, trbuf[50] = {0}, ch;
int ret = 0;
if ((ret = recv(cfd, rcbuf, sizeof(rcbuf), 0)) < 0)
{
perror("recv");
close(cfd);
close(sfd);
exit(6);
}
printf("%s\n", rcbuf);
int i =0;
while((ch = getchar())!= '\n'){
trbuf[i] = ch;
i++;
}
trbuf[i] = '\0';
if (send(cfd, trbuf, ret, 0) < 0)
{
perror("send");
close(cfd);
close(sfd);
exit(7);
}
memset(rcbuf, 0, 50);
memset(trbuf, 0, 50);
}
close(cfd);
close(sfd);
return 0;
}