source: libcf++/trunk/src/network.cpp@ 14

Last change on this file since 14 was 14, checked in by cheese, 9 years ago

#1 interface for connection with address/port

File size: 11.5 KB
Line 
1/**
2 * @file network.cpp
3 * @author myusgun@gmail.com
4 * @brief network
5 */
6#include "cf/network.h"
7
8#include <iostream>
9#include <sstream>
10#include <string.h>
11
12#ifdef _ON_WINDOWS
13# include <WinSock2.h>
14# pragma comment(lib, "ws2_32.lib")
15#else
16# include <netinet/in.h>
17# include <sys/socket.h>
18# include <arpa/inet.h>
19# include <netdb.h>
20# include <unistd.h>
21# include <sys/un.h>
22# include <fcntl.h>
23# include <errno.h>
24# include <sys/types.h>
25# include <sys/time.h>
26#endif
27
28#ifdef _ON_WINDOWS
29typedef cf::int32_t socklen_t;
30# define sa_family_t cf::uint16_t
31# define ERROR_INTR WSAEINTR
32# define ERROR_CONNECTING WSAEWOULDBLOCK
33# define SOCKET_API_CALL __stdcall
34#else
35# define closesocket(__sock) ::close(__sock)
36# define ERROR_INTR EINTR
37# define ERROR_CONNECTING EINPROGRESS
38# define SOCKET_API_CALL
39#endif
40
41/*--------------------------------------------------------------*/
42/**
43 * do not include "cf/macaddr.[ch]pp"
44 * just declare and call
45 */
46long GetMACAddress(cf::char_t *addr);
47
48static std::string convertAddressToString(struct sockaddr_in & addr)
49{
50 cf::uint8_t * bytes = NULL;
51 cf::char_t str[32] = {0x00};
52
53 bytes = reinterpret_cast<cf::uint8_t *>(&addr.sin_addr.s_addr);
54 snprintf(str, sizeof(str) - 1, "%u.%u.%u.%u", bytes[0],
55 bytes[1],
56 bytes[2],
57 bytes[3]);
58
59 return str;
60}
61
62static cf::void_t waitForTimeout(const cf::socket_t sock,
63 const cf::int32_t timeout,
64 const cf::bool_t checkWriteFD)
65 throw (cf::exception)
66{
67 cf::int32_t result = 0;
68 fd_set rfds;
69 fd_set wfds;
70 fd_set * wfdsPtr = checkWriteFD ? &wfds : NULL;
71
72 struct timeval tv;
73
74 if (timeout <= 0)
75 return;
76
77 FD_ZERO(&rfds);
78 FD_SET(sock, &rfds);
79
80 FD_ZERO(&wfds);
81 FD_SET(sock, &wfds);
82
83 tv.tv_sec = timeout;
84 tv.tv_usec = 0;
85
86 result = select(sock + 1, &rfds, wfdsPtr, NULL, &tv);
87 if (result < 0)
88 THROW_EXCEPTION("select error");
89 else if (result == 0)
90 THROW_EXCEPTION("socket timed out");
91
92 if (!FD_ISSET(sock, &rfds))
93 {
94 if (!checkWriteFD)
95 THROW_EXCEPTION("read fd is not set");
96 else if (!FD_ISSET(sock, &wfds))
97 THROW_EXCEPTION("write fd is not set");
98 }
99}
100
101static cf::void_t setReuseAddress(const cf::network::tcp & tcp)
102 throw (cf::exception)
103{
104 try
105 {
106 cf::int32_t reuseaddr = 1;
107
108 tcp.setOption(SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
109 }
110 catch (cf::exception & e)
111 {
112 FORWARD_EXCEPTION(e);
113 }
114}
115
116typedef cf::int32_t (SOCKET_API_CALL * getSocketNameAPI)(cf::socket_t sock,
117 struct sockaddr * addr,
118 socklen_t *len);
119
120static cf::network::host getSocketNameFromFunction(const cf::socket_t sock,
121 getSocketNameAPI api)
122 throw (cf::exception)
123{
124 cf::int32_t result = 0;
125 struct sockaddr_in addr;
126 socklen_t len = sizeof(struct sockaddr_in);
127
128 result = api(sock, (struct sockaddr *)&addr, &len);
129 if (result < 0)
130 THROW_EXCEPTION("cannot get sockket or peer name ("
131 << cf::exception::systemCode()
132 << ")");
133
134 return cf::network::host(convertAddressToString(addr), addr.sin_port);
135}
136/*--------------------------------------------------------------*/
137
138cf::network::host::host(const std::string & address,
139 const cf::uint16_t port)
140 : mAddress(address),
141 mPort(port)
142{
143}
144
145const std::string & cf::network::host::address() const
146{
147 return mAddress;
148}
149
150cf::uint16_t cf::network::host::port() const
151{
152 return mPort;
153}
154
155cf::bool_t cf::network::host::empty() const
156{
157 return (address().empty() || port() == 0) ? true : false;
158}
159
160cf::network::tcp::tcp(const cf::socket_t attachedSocket)
161 throw (cf::exception)
162 : mSocket (attachedSocket),
163 mTimeout(0)
164{
165 static cf::bool_t isInitialized = false;
166
167 /* initialize socket */
168 if (!isInitialized)
169 {
170#if defined(_WIN32) || defined(_WIN64)
171 WSADATA winsockData;
172 cf::int32_t result = WSAStartup(MAKEWORD(2, 0), &winsockData);
173 if (result)
174 THROW_EXCEPTION("cannot start-up winsock");
175#endif
176
177 isInitialized = true;
178 }
179
180 if (mSocket == UNUSED_SOCKET)
181 mSocket = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
182
183 if (mSocket < 0)
184 THROW_EXCEPTION("cannot create a socket");
185}
186
187cf::network::tcp::~tcp()
188{
189 close();
190}
191
192cf::socket_t cf::network::tcp::descriptor() const
193{
194 return mSocket;
195}
196
197cf::void_t cf::network::tcp::close()
198{
199 if (mSocket == UNUSED_SOCKET)
200 return;
201
202 closesocket(mSocket);
203
204 mSocket = UNUSED_SOCKET;
205}
206
207cf::void_t cf::network::tcp::connect(const cf::network::host & peer,
208 const cf::int32_t timeout)
209 throw (cf::exception)
210{
211 connect(peer.address(), peer.port(), timeout);
212}
213
214cf::void_t cf::network::tcp::connect(const std::string & address,
215 const cf::uint16_t port,
216 const cf::int32_t timeout)
217 throw (cf::exception)
218{
219 cf::int32_t result = 0;
220 cf::int32_t retval = 0;
221 cf::int32_t length = 0;
222 struct sockaddr_in addr;
223 struct hostent * hostEnt;
224
225 const cf::char_t * host = address.c_str();
226
227 /* 1. set data */
228 addr.sin_family = AF_INET;
229 addr.sin_port = htons(port);
230 addr.sin_addr.s_addr = inet_addr(host);
231
232 /* 2. get ip from hostname if inet_addr() is failed */
233 if (addr.sin_addr.s_addr == (unsigned int)-1)
234 {
235 hostEnt = gethostbyname(host);
236 if (hostEnt == NULL)
237 THROW_EXCEPTION("cannot get host by name");
238
239 addr.sin_family = (sa_family_t)hostEnt->h_addrtype;
240 memcpy(&(addr.sin_addr.s_addr),
241 hostEnt->h_addr,
242 (size_t)hostEnt->h_length);
243 }
244
245 setTimeout(timeout);
246
247 /* 3. connect */
248 result = ::connect(mSocket, (struct sockaddr *)&addr, sizeof(addr));
249 if (result < 0)
250 {
251 if (timeout > 0)
252 {
253 if (cf::exception::systemCode() != ERROR_CONNECTING)
254 THROW_EXCEPTION("socket connect error");
255
256 try
257 {
258 length = sizeof(retval);
259 waitForTimeout(mSocket, timeout, true);
260 getOption(SO_ERROR, &retval, &length);
261 }
262 catch (cf::exception & e)
263 {
264 FORWARD_EXCEPTION(e);
265 }
266
267 if (retval)
268 THROW_EXCEPTION("SO_ERROR: " << retval);
269 }
270 else
271 {
272 THROW_EXCEPTION("cannot connect to " << host << ":" << port);
273 }
274 }
275}
276
277cf::void_t cf::network::tcp::bind(const cf::uint16_t port) const
278 throw (cf::exception)
279{
280 if (!port)
281 THROW_EXCEPTION("invalid port number");
282
283 cf::int32_t result = 0;
284 struct sockaddr_in addr;
285
286 /* 1. set data */
287 addr.sin_family = AF_INET;
288 addr.sin_addr.s_addr = htonl(INADDR_ANY);
289 addr.sin_port = htons(port);
290
291 /* 2. set options */
292 try
293 {
294 setReuseAddress(*this);
295 }
296 catch (cf::exception & e)
297 {
298 FORWARD_EXCEPTION(e);
299 }
300
301 result = ::bind(mSocket, (struct sockaddr *)&addr, sizeof(struct sockaddr));
302 if (result < 0)
303 THROW_EXCEPTION("cannot bind to " << port);
304}
305
306cf::void_t cf::network::tcp::listen(const cf::int32_t backlog) const
307 throw (cf::exception)
308{
309 cf::int32_t result = ::listen(mSocket, backlog);
310 if (result < 0)
311 THROW_EXCEPTION("cannot listen");
312}
313
314cf::network::tcp cf::network::tcp::accept() const
315 throw (cf::exception)
316{
317 cf::socket_t sock = 0;
318 struct sockaddr_in addr;
319 socklen_t len = sizeof(addr);
320
321 sock = ::accept(mSocket, (struct sockaddr *)&addr, /* in/out */&len);
322 if (sock < 0)
323 THROW_EXCEPTION("cannot accept client");
324
325 return cf::network::tcp(sock).detach();
326}
327
328cf::void_t cf::network::tcp::attach(const cf::socket_t sock)
329 throw (exception)
330{
331 if (sock == UNUSED_SOCKET)
332 THROW_EXCEPTION("has invalid socket");
333
334 mSocket = sock;
335}
336
337cf::socket_t cf::network::tcp::detach()
338 throw (exception)
339{
340 if (mSocket == UNUSED_SOCKET)
341 THROW_EXCEPTION("has invalid socket");
342
343 cf::socket_t sock = mSocket;
344
345 mSocket = UNUSED_SOCKET;
346
347 return sock;
348}
349
350cf::void_t cf::network::tcp::send(const cf::bin & in) const
351 throw (cf::exception)
352{
353 if (in.empty())
354 THROW_EXCEPTION("send data is null or zero-bytes");
355
356 cf::char_t * buf = reinterpret_cast<cf::char_t *>(in.buffer());
357 cf::int32_t size = static_cast<cf::int32_t>(in.size());
358
359 cf::int32_t sentSize = (cf::int32_t)::send(mSocket, buf, size, 0);
360 if (sentSize != size)
361 THROW_EXCEPTION("cannot send (" << cf::exception::systemCode() << ")");
362}
363
364cf::void_t cf::network::tcp::receive(cf::bin & out) const
365 throw (cf::exception)
366{
367 if (out.size() == 0)
368 THROW_EXCEPTION("binary buffer is not created");
369
370 try
371 {
372 waitForTimeout(mSocket, mTimeout, false);
373 }
374 catch (cf::exception & e)
375 {
376 FORWARD_EXCEPTION(e);
377 }
378
379 cf::char_t * buf = reinterpret_cast<cf::char_t *>(out.buffer());
380 cf::int32_t size = static_cast<cf::int32_t>(out.size());
381
382 cf::int32_t receivedSize = (cf::int32_t)::recv(mSocket, buf, size, 0);
383 if (receivedSize < 0)
384 THROW_EXCEPTION("cannot receive (" << cf::exception::systemCode() << ")");
385 else if (receivedSize == 0)
386 THROW_EXCEPTION("connection closed");
387 else if (receivedSize < size)
388 out.resize(receivedSize);
389}
390
391cf::bin cf::network::tcp::receive(const cf::int32_t size) const
392 throw (cf::exception)
393{
394 cf::bin out;
395
396 out.resize(size);
397 receive(out);
398
399 return out;
400}
401
402cf::bin cf::network::tcp::receive() const
403 throw (cf::exception)
404{
405 const cf::size_t bufferSize = 1024;
406
407 cf::bin buffer;
408 cf::bin out;
409
410 buffer.resize(bufferSize);
411
412 do
413 {
414 receive(buffer);
415 out.append(buffer);
416 } while (buffer.size() == bufferSize);
417
418 return out;
419}
420
421cf::void_t cf::network::tcp::getOption(const cf::int32_t optname,
422 cf::void_t * optval,
423 cf::int32_t * optlen) const
424 throw (cf::exception)
425{
426 cf::int32_t result = getsockopt(mSocket,
427 SOL_SOCKET,
428 optname,
429#ifdef _ON_WINDOWS
430 (cf::char_t *)optval,
431#else
432 optval,
433#endif
434 (socklen_t *)optlen);
435 if (result < 0)
436 THROW_EXCEPTION("cannot get socket option ("
437 << cf::exception::systemCode()
438 << ")");
439}
440
441cf::void_t cf::network::tcp::setOption(const cf::int32_t optname,
442 const cf::void_t * optval,
443 const cf::int32_t optlen) const
444 throw (cf::exception)
445{
446 cf::int32_t result = setsockopt(mSocket,
447 SOL_SOCKET,
448 optname,
449#ifdef _ON_WINDOWS
450 (cf::char_t *)optval,
451#else
452 optval,
453#endif
454 (socklen_t)optlen);
455 if (result < 0)
456 THROW_EXCEPTION("cannot set socket option ("
457 << cf::exception::systemCode()
458 << ")");
459}
460
461cf::void_t cf::network::tcp::setNonBlocking(const cf::bool_t flag)
462{
463#ifdef _ON_WINDOWS
464 cf::ulong_t mode = flag ? 1 : 0;
465 ioctlsocket(mSocket, FIONBIO, &mode);
466#else
467 cf::int32_t mode = fcntl(mSocket, F_GETFL, 0);
468
469 if (flag) mode |= O_NONBLOCK;
470 else mode &= ~O_NONBLOCK;
471
472 fcntl(mSocket, F_SETFL, mode);
473#endif
474}
475
476cf::void_t cf::network::tcp::setTimeout(const cf::int32_t seconds)
477{
478 setNonBlocking(seconds > 0 /*? true : false*/);
479 mTimeout = seconds;
480}
481
482cf::network::host cf::network::tcp::peer() const
483 throw (cf::exception)
484{
485 try
486 {
487 return getSocketNameFromFunction(mSocket, getpeername);
488 }
489 catch (cf::exception & e)
490 {
491 FORWARD_EXCEPTION(e);
492 }
493}
494
495cf::network::host cf::network::tcp::local() const
496 throw (cf::exception)
497{
498 try
499 {
500 return getSocketNameFromFunction(mSocket, getsockname);
501 }
502 catch (cf::exception & e)
503 {
504 FORWARD_EXCEPTION(e);
505 }
506}
507
508std::string cf::network::nic::getMACAddress()
509 throw (cf::exception)
510{
511 static const cf::int32_t macSize = 6; /* = 48-bits */
512 static cf::bool_t isDone = false;
513 static cf::uint8_t bytes[macSize] = {0x00,};
514 static cf::char_t asciiz[macSize * 2 + 1] = {0x00,};
515
516 if (!isDone)
517 {
518 long result = 0;
519
520 result = GetMACAddress(reinterpret_cast<cf::char_t *>(bytes));
521 if (result)
522 THROW_EXCEPTION("cannot get mac-address");
523
524 for (cf::int32_t iter = 0 ; iter < macSize ; iter++)
525 snprintf(asciiz + (iter * 2), sizeof(asciiz) - 1,
526 "%02x",
527 bytes[iter]);
528
529 isDone = true;
530 }
531
532 return std::string(asciiz);
533}
534
535
536cf::uint32_t cf::network::byteOrder::htonl(cf::uint32_t in)
537{
538 return ::htonl(in);
539}
540
541cf::uint16_t cf::network::byteOrder::htons(cf::uint16_t in)
542{
543 return ::htons(in);
544}
545
546cf::uint32_t cf::network::byteOrder::ntohl(cf::uint32_t in)
547{
548 return ::ntohl(in);
549}
550
551cf::uint16_t cf::network::byteOrder::ntohs(cf::uint16_t in)
552{
553 return ::ntohs(in);
554}
Note: See TracBrowser for help on using the repository browser.