-
Notifications
You must be signed in to change notification settings - Fork 1
/
tcp.cpp
121 lines (98 loc) · 2.51 KB
/
tcp.cpp
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
C++ client example using sockets
http://www.binarytides.com/code-a-simple-socket-client-class-in-c/
Modified - GBG 9/2013 - CpSc6120
**/
#include "tcp.h"
using namespace std;
tcp_client::tcp_client()
{
sock = -1;
port = 0;
address = "";
}
/**
Connect to a host on a certain port number
**/
bool tcp_client::conn(string address , int port)
{
//create socket if it is not already created
if(sock == -1)
{
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
perror("Could not create socket");
}
//cout<<"Socket created\n";
}
else { /* OK , nothing */ }
//setup address structure
if(inet_addr(address.c_str()) == -1)
{
struct hostent *he;
struct in_addr **addr_list;
//resolve the hostname, its not an ip address
if ( (he = gethostbyname( address.c_str() ) ) == NULL)
{
//gethostbyname failed
herror("gethostbyname");
cout<<"Failed to resolve hostname\n";
return false;
}
//Cast the h_addr_list to in_addr , since h_addr_list also has the ip address in long format only
addr_list = (struct in_addr **) he->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++)
{
//strcpy(ip , inet_ntoa(*addr_list[i]) );
server.sin_addr = *addr_list[i];
cout<<address<<" resolved to "<<inet_ntoa(*addr_list[i])<<endl;
break;
}
}
//plain ip address
else
{
server.sin_addr.s_addr = inet_addr( address.c_str() );
}
server.sin_family = AF_INET;
server.sin_port = htons( port );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
cout<<"Connected to Maya\n";
return true;
}
/**
Send data to the connected host
**/
bool tcp_client::send_data(string data)
{
//Send some data
if( send(sock , data.c_str() , strlen( data.c_str() ) , 0) < 0)
{
perror("Send failed : ");
return false;
}
//cout<<"Data send\n";
return true;
}
/**
Receive data from the connected host
**/
string tcp_client::receive(int size)
{
char buffer[size];
string reply;
//Receive a reply from the server
if( recv(sock , buffer , sizeof(buffer) , 0) < 0)
{
puts("recv failed");
}
reply = buffer;
return reply;
}