- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPracticalSocket.cpp
More file actions
Latest commit
291 lines (240 loc) · 8.99 KB
/
Copy pathPracticalSocket.cpp
File metadata and controls
291 lines (240 loc) · 8.99 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
* C++ sockets on Unix and Windows
* Copyright (C) 2002
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include"PracticalSocket.h"
#ifdef WIN32
#include<winsock.h>// For socket(), connect(), send(), and recv()
typedefintsocklen_t;
typedefchar raw_type; // Type used for raw data on this platform
#else
#include<sys/socket.h>// For socket(), connect(), send(), and recv()
#include<netdb.h>// For gethostbyname()
#include<arpa/inet.h>// For inet_addr()
#include<unistd.h>// For close()
typedefvoid raw_type; // Type used for raw data on this platform
#endif
#include<cstring>
#include<sstream>
#include<iostream>
#include<cassert>
//using namespace std;
#ifdef WIN32
staticbool initialized = false;
#endif
// SocketException Code
SocketException::SocketException(const std::string &message, bool inclSysMsg)
throw() : userMessage(message) {
if (inclSysMsg) {
userMessage.append(": ");
userMessage.append(strerror(errno));
}
}
SocketException::~SocketException() throw() {
}
constchar *SocketException::what() const throw() {
return userMessage.c_str();
}
// Function to fill in address structure given an address and port
staticvoidfillAddr(const std::string &address, unsignedshort port, addrinfo **addr) {
structaddrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
hints.ai_socktype = SOCK_STREAM;
std::stringstream p;
p << port;
int rv;
if ((rv = getaddrinfo(address.c_str(), p.str().c_str(), &hints, addr)) != 0) {
std::cout << gai_strerror(rv) << std::endl;
throwSocketException("Failed to resolve name (gethostbyname())");
}
std::cout << "Address filled" << std::endl;
//freeaddrinfo(&hints);
}
// Socket Code
Socket::Socket(int type, int protocol) throw(SocketException) {
#ifdef WIN32
if (!initialized) {
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 0); // Request WinSock v2.0
if (WSAStartup(wVersionRequested, &wsaData) != 0) { // Load WinSock DLL
throwSocketException("Unable to load WinSock DLL");
}
initialized = true;
}
#endif
// Make a new socket
if ((sockDesc = socket(PF_INET, type, protocol)) < 0) {
throwSocketException("Socket creation failed (socket())", true);
}
}
Socket::Socket(int sockDesc) {
this->sockDesc = sockDesc;
}
Socket::~Socket() {
#ifdef WIN32
::closesocket(sockDesc);
#else
::close(sockDesc);
#endif
sockDesc = -1;
}
std::string Socket::getLocalAddress() throw(SocketException) {
sockaddr_in addr;
unsignedint addr_len = sizeof(addr);
if (getsockname(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
throwSocketException("Fetch of local address failed (getsockname())", true);
}
returninet_ntoa(addr.sin_addr);
}
unsignedshortSocket::getLocalPort() throw(SocketException) {
sockaddr_in addr;
unsignedint addr_len = sizeof(addr);
if (getsockname(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
throwSocketException("Fetch of local port failed (getsockname())", true);
}
returnntohs(addr.sin_port);
}
voidSocket::setLocalPort(unsignedshort localPort) throw(SocketException) {
// Bind the socket to its port
sockaddr_in localAddr;
memset(&localAddr, 0, sizeof(localAddr));
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(localPort);
if (bind(sockDesc, (sockaddr *) &localAddr, sizeof(sockaddr_in)) < 0) {
throwSocketException("Set of local port failed (bind())", true);
}
}
voidSocket::setLocalAddressAndPort(const std::string &localAddress,
unsignedshort localPort) throw(SocketException) {
// Get the address of the requested host
addrinfo *localAddr;
fillAddr(localAddress, localPort, &localAddr);
if (bind(sockDesc, localAddr->ai_addr, localAddr->ai_addrlen) < 0) {
throwSocketException("Set of local address and port failed (bind())", true);
}
freeaddrinfo(localAddr);
}
voidSocket::cleanUp() throw(SocketException) {
#ifdef WIN32
if (WSACleanup() != 0) {
throwSocketException("WSACleanup() failed");
}
#endif
}
unsignedshortSocket::resolveService(const std::string &service,
const std::string &protocol) {
structservent *serv; /* Structure containing service information */
if ((serv = getservbyname(service.c_str(), protocol.c_str())) == NULL)
returnatoi(service.c_str()); /* Service is port number */
else
returnntohs(serv->s_port); /* Found port (network byte order) by name */
}
// CommunicatingSocket Code
CommunicatingSocket::CommunicatingSocket(int type, int protocol)
throw(SocketException) : Socket(type, protocol) {
}
CommunicatingSocket::CommunicatingSocket(int newConnSD) : Socket(newConnSD) {
}
voidCommunicatingSocket::connect(const std::string &foreignAddress,
unsignedshort foreignPort) throw(SocketException) {
// Get the address of the requested host
structaddrinfo *servinfo, *p;
fillAddr(foreignAddress, foreignPort, &servinfo);
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockDesc = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
std::cerr << "Socket" << std::endl;
continue;
}
if (::connect(sockDesc, p->ai_addr, p->ai_addrlen) == -1) {
std::cerr << "Error connecting" << std::endl;
close(sockDesc);
// throw SocketException("Connect failed (connect())", true);
continue;
}
break;
}
freeaddrinfo(servinfo);
}
voidCommunicatingSocket::send(constvoid *buffer, int bufferLen)
throw(SocketException) {
if (::send(sockDesc, (raw_type *) buffer, bufferLen, 0) < 0) {
throwSocketException("Send failed (send())", true);
}
}
intCommunicatingSocket::recv(void *buffer, int bufferLen)
throw(SocketException) {
int rtn;
if ((rtn = ::recv(sockDesc, (raw_type *) buffer, bufferLen, 0)) < 0) {
throwSocketException("Received failed (recv())", true);
}
return rtn;
}
std::string CommunicatingSocket::getForeignAddress()
throw(SocketException) {
sockaddr_in addr;
unsignedint addr_len = sizeof(addr);
if (getpeername(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
throwSocketException("Fetch of foreign address failed (getpeername())", true);
}
returninet_ntoa(addr.sin_addr);
}
unsignedshortCommunicatingSocket::getForeignPort() throw(SocketException) {
sockaddr_in addr;
unsignedint addr_len = sizeof(addr);
if (getpeername(sockDesc, (sockaddr *) &addr, (socklen_t *) &addr_len) < 0) {
throwSocketException("Fetch of foreign port failed (getpeername())", true);
}
returnntohs(addr.sin_port);
}
// TCPSocket Code
TCPSocket::TCPSocket()
throw(SocketException) : CommunicatingSocket(SOCK_STREAM,
IPPROTO_TCP) {
}
TCPSocket::TCPSocket(const std::string &foreignAddress, unsignedshort foreignPort)
throw(SocketException) : CommunicatingSocket(SOCK_STREAM, IPPROTO_TCP) {
connect(foreignAddress, foreignPort);
}
TCPSocket::TCPSocket(int newConnSD) : CommunicatingSocket(newConnSD) {
}
// TCPServerSocket Code
TCPServerSocket::TCPServerSocket(unsignedshort localPort, int queueLen)
throw(SocketException) : Socket(SOCK_STREAM, IPPROTO_TCP) {
setLocalPort(localPort);
setListen(queueLen);
}
TCPServerSocket::TCPServerSocket(const std::string &localAddress,
unsignedshort localPort, int queueLen)
throw(SocketException) : Socket(SOCK_STREAM, IPPROTO_TCP) {
setLocalAddressAndPort(localAddress, localPort);
setListen(queueLen);
}
TCPSocket *TCPServerSocket::accept() throw(SocketException) {
int newConnSD;
if ((newConnSD = ::accept(sockDesc, NULL, 0)) < 0) {
throwSocketException("Accept failed (accept())", true);
}
returnnewTCPSocket(newConnSD);
}
voidTCPServerSocket::setListen(int queueLen) throw(SocketException) {
if (listen(sockDesc, queueLen) < 0) {
throwSocketException("Set listening socket failed (listen())", true);
}
}