-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_tcp.cpp
More file actions
78 lines (59 loc) · 1.75 KB
/
server_tcp.cpp
File metadata and controls
78 lines (59 loc) · 1.75 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
#include "common.h"
using namespace std;
int main(int argc, char *argv[])
{
if(argc == 1)
{
cout << "Expected execution : ./server port" <<endl;
return 0;
}
int sckt,client,data_len;
int portNumber = atoi(argv[1]);
int bufferSize = 1024;
char buffer[bufferSize];
struct sockaddr_in server_addr,client_addr;
socklen_t size;
sckt = socket(AF_INET, SOCK_STREAM, 0);
if (sckt < 0)
{
perror("Error establishing a socket !!");
return 0;
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(portNumber);
if ((bind(sckt, (struct sockaddr*)&server_addr,sizeof(server_addr))) < 0)
{
perror("Error binding the connection !!");
return 0;
}
size = sizeof(server_addr);
cout << "Waiting for clients to connect..." << endl;
listen(sckt , 0);
client = accept(sckt,(struct sockaddr *)&client_addr, &size);
if(client < 0)
{
perror("Error accepting the connection..!!");
return 1;
}
cerr << "Connected to client: IP " << inet_ntoa(client_addr.sin_addr) << " Port :" << client_addr.sin_port << endl;
data_len = 1;
while(data_len)
{
data_len = recv(client, buffer, bufferSize, 0);
if(data_len)
{
cout << buffer << endl;
}
if(buffer[sizeof(buffer)]==EOF)
{
close(client);
close(sckt);
return 0;
}
memset(buffer,0,bufferSize);
}
cout << "Client disconnected !! Closing the server socket" << endl;
close(client);
close(sckt);
}