-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.cpp
More file actions
76 lines (72 loc) · 2.35 KB
/
Copy pathClient.cpp
File metadata and controls
76 lines (72 loc) · 2.35 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
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/time.h>
#include<bits/stdc++.h>
using namespace std;
//Client side
int main(int argc, char *argv[])
{
//we need 2 things: ip address and port number, in that order
if(argc != 3)
{
cerr << "Usage: ip_address port" << endl; exit(0);
} //grab the IP address and port number
char *serverIp = argv[1]; int port = atoi(argv[2]);
//create a message buffer
char * msg=(char*)malloc(sizeof(char)*100);
memset(msg,'\0',sizeof(char)*100);
//setup a socket and connection tools
struct hostent* host = gethostbyname(serverIp);
sockaddr_in sendSockAddr;
bzero((char*)&sendSockAddr, sizeof(sendSockAddr));
sendSockAddr.sin_family = AF_INET;
sendSockAddr.sin_addr.s_addr =
inet_addr(inet_ntoa(*(struct in_addr*)*host->h_addr_list));
sendSockAddr.sin_port = htons(port);
int clientSd = socket(AF_INET, SOCK_STREAM, 0);
int status = connect(clientSd,(sockaddr*) &sendSockAddr, sizeof(sendSockAddr));
if(status < 0)
{
cout<<"Error connecting to socket!"<<endl;
}
cout << "Connected to the server!" << endl;
int bytesRead, bytesWritten = 0;
struct timeval start1, end1;
gettimeofday(&start1, NULL);
while(1)
{
cout << ">";
string data;
getline(cin, data);
memset(msg, '\0', sizeof(char)*100);
strcpy(msg, data.c_str());
if(data == "exit")
{
send(clientSd, msg, 5, 0);
break;
}
bytesWritten += send(clientSd, msg, data.length() , 0);
memset(msg, '\0', sizeof(char)*100);
cout << "Awaiting server response..." << endl;
bytesRead += recv(clientSd, msg, sizeof(char)*100, 0);
if(strcmp(msg, "exit")==0)
{
cout << "Server has quit the session" << endl;
break;
}
cout << "Server: " << msg << endl;
}
gettimeofday(&end1, NULL);
close(clientSd);
cout << "********Session********" << endl;
cout << "Bytes written: " << bytesWritten <<
" Bytes read: " << bytesRead << endl;
cout << "Elapsed time: " << (end1.tv_sec- start1.tv_sec)
<< " secs" << endl;
cout << "Connection closed" << endl;
return 0;
}