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

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

#1 remove unused interface

File size: 11.4 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::network::tcp::tcp(const cf::socket_t attachedSocket)
156 throw (cf::exception)
157 : mSocket (attachedSocket),
158 mTimeout(0)
159{
160 static cf::bool_t isInitialized = false;
161
162 /* initialize socket */
163 if (!isInitialized)
164 {
165#if defined(_WIN32) || defined(_WIN64)
166 WSADATA winsockData;
167 cf::int32_t result = WSAStartup(MAKEWORD(2, 0), &winsockData);
168 if (result)
169 THROW_EXCEPTION("cannot start-up winsock");
170#endif
171
172 isInitialized = true;
173 }
174
175 if (mSocket == UNUSED_SOCKET)
176 mSocket = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
177
178 if (mSocket < 0)
179 THROW_EXCEPTION("cannot create a socket");
180}
181
182cf::network::tcp::~tcp()
183{
184 close();
185}
186
187cf::socket_t cf::network::tcp::descriptor() const
188{
189 return mSocket;
190}
191
192cf::void_t cf::network::tcp::close()
193{
194 if (mSocket == UNUSED_SOCKET)
195 return;
196
197 closesocket(mSocket);
198
199 mSocket = UNUSED_SOCKET;
200}
201
202cf::void_t cf::network::tcp::connect(const cf::network::host & peer,
203 const cf::int32_t timeout)
204 throw (cf::exception)
205{
206 connect(peer.address(), peer.port(), timeout);
207}
208
209cf::void_t cf::network::tcp::connect(const std::string & address,
210 const cf::uint16_t port,
211 const cf::int32_t timeout)
212 throw (cf::exception)
213{
214 cf::int32_t result = 0;
215 cf::int32_t retval = 0;
216 cf::int32_t length = 0;
217 struct sockaddr_in addr;
218 struct hostent * hostEnt;
219
220 const cf::char_t * host = address.c_str();
221
222 /* 1. set data */
223 addr.sin_family = AF_INET;
224 addr.sin_port = htons(port);
225 addr.sin_addr.s_addr = inet_addr(host);
226
227 /* 2. get ip from hostname if inet_addr() is failed */
228 if (addr.sin_addr.s_addr == (unsigned int)-1)
229 {
230 hostEnt = gethostbyname(host);
231 if (hostEnt == NULL)
232 THROW_EXCEPTION("cannot get host by name");
233
234 addr.sin_family = (sa_family_t)hostEnt->h_addrtype;
235 memcpy(&(addr.sin_addr.s_addr),
236 hostEnt->h_addr,
237 (size_t)hostEnt->h_length);
238 }
239
240 setTimeout(timeout);
241
242 /* 3. connect */
243 result = ::connect(mSocket, (struct sockaddr *)&addr, sizeof(addr));
244 if (result < 0)
245 {
246 if (timeout > 0)
247 {
248 if (cf::exception::systemCode() != ERROR_CONNECTING)
249 THROW_EXCEPTION("socket connect error");
250
251 try
252 {
253 length = sizeof(retval);
254 waitForTimeout(mSocket, timeout, true);
255 getOption(SO_ERROR, &retval, &length);
256 }
257 catch (cf::exception & e)
258 {
259 FORWARD_EXCEPTION(e);
260 }
261
262 if (retval)
263 THROW_EXCEPTION("SO_ERROR: " << retval);
264 }
265 else
266 {
267 THROW_EXCEPTION("cannot connect to " << host << ":" << port);
268 }
269 }
270}
271
272cf::void_t cf::network::tcp::bind(const cf::uint16_t port) const
273 throw (cf::exception)
274{
275 if (!port)
276 THROW_EXCEPTION("invalid port number");
277
278 cf::int32_t result = 0;
279 struct sockaddr_in addr;
280
281 /* 1. set data */
282 addr.sin_family = AF_INET;
283 addr.sin_addr.s_addr = htonl(INADDR_ANY);
284 addr.sin_port = htons(port);
285
286 /* 2. set options */
287 try
288 {
289 setReuseAddress(*this);
290 }
291 catch (cf::exception & e)
292 {
293 FORWARD_EXCEPTION(e);
294 }
295
296 result = ::bind(mSocket, (struct sockaddr *)&addr, sizeof(struct sockaddr));
297 if (result < 0)
298 THROW_EXCEPTION("cannot bind to " << port);
299}
300
301cf::void_t cf::network::tcp::listen(const cf::int32_t backlog) const
302 throw (cf::exception)
303{
304 cf::int32_t result = ::listen(mSocket, backlog);
305 if (result < 0)
306 THROW_EXCEPTION("cannot listen");
307}
308
309cf::network::tcp cf::network::tcp::accept() const
310 throw (cf::exception)
311{
312 cf::socket_t sock = 0;
313 struct sockaddr_in addr;
314 socklen_t len = sizeof(addr);
315
316 sock = ::accept(mSocket, (struct sockaddr *)&addr, /* in/out */&len);
317 if (sock < 0)
318 THROW_EXCEPTION("cannot accept client");
319
320 return cf::network::tcp(sock).detach();
321}
322
323cf::void_t cf::network::tcp::attach(const cf::socket_t sock)
324 throw (exception)
325{
326 if (sock == UNUSED_SOCKET)
327 THROW_EXCEPTION("has invalid socket");
328
329 mSocket = sock;
330}
331
332cf::socket_t cf::network::tcp::detach()
333 throw (exception)
334{
335 if (mSocket == UNUSED_SOCKET)
336 THROW_EXCEPTION("has invalid socket");
337
338 cf::socket_t sock = mSocket;
339
340 mSocket = UNUSED_SOCKET;
341
342 return sock;
343}
344
345cf::void_t cf::network::tcp::send(const cf::bin & in) const
346 throw (cf::exception)
347{
348 if (in.size() == 0)
349 THROW_EXCEPTION("send data is zero-bytes");
350
351 cf::char_t * buf = reinterpret_cast<cf::char_t *>(in.buffer());
352 cf::int32_t size = static_cast<cf::int32_t>(in.size());
353
354 cf::int32_t sentSize = (cf::int32_t)::send(mSocket, buf, size, 0);
355 if (sentSize != size)
356 THROW_EXCEPTION("cannot send (" << cf::exception::systemCode() << ")");
357}
358
359cf::void_t cf::network::tcp::receive(cf::bin & out) const
360 throw (cf::exception)
361{
362 if (out.size() == 0)
363 THROW_EXCEPTION("binary buffer is not created");
364
365 try
366 {
367 waitForTimeout(mSocket, mTimeout, false);
368 }
369 catch (cf::exception & e)
370 {
371 FORWARD_EXCEPTION(e);
372 }
373
374 cf::char_t * buf = reinterpret_cast<cf::char_t *>(out.buffer());
375 cf::int32_t size = static_cast<cf::int32_t>(out.size());
376
377 cf::int32_t receivedSize = (cf::int32_t)::recv(mSocket, buf, size, 0);
378 if (receivedSize < 0)
379 THROW_EXCEPTION("cannot receive (" << cf::exception::systemCode() << ")");
380 else if (receivedSize == 0)
381 THROW_EXCEPTION("connection closed");
382 else if (receivedSize < size)
383 out.resize(receivedSize);
384}
385
386cf::bin cf::network::tcp::receive(const cf::int32_t size) const
387 throw (cf::exception)
388{
389 cf::bin out;
390
391 out.resize(size);
392 receive(out);
393
394 return out;
395}
396
397cf::bin cf::network::tcp::receive() const
398 throw (cf::exception)
399{
400 const cf::size_t bufferSize = 1024;
401
402 cf::bin buffer;
403 cf::bin out;
404
405 buffer.resize(bufferSize);
406
407 do
408 {
409 receive(buffer);
410 out.append(buffer);
411 } while (buffer.size() == bufferSize);
412
413 return out;
414}
415
416cf::void_t cf::network::tcp::getOption(const cf::int32_t optname,
417 cf::void_t * optval,
418 cf::int32_t * optlen) const
419 throw (cf::exception)
420{
421 cf::int32_t result = getsockopt(mSocket,
422 SOL_SOCKET,
423 optname,
424#ifdef _ON_WINDOWS
425 (cf::char_t *)optval,
426#else
427 optval,
428#endif
429 (socklen_t *)optlen);
430 if (result < 0)
431 THROW_EXCEPTION("cannot get socket option ("
432 << cf::exception::systemCode()
433 << ")");
434}
435
436cf::void_t cf::network::tcp::setOption(const cf::int32_t optname,
437 const cf::void_t * optval,
438 const cf::int32_t optlen) const
439 throw (cf::exception)
440{
441 cf::int32_t result = setsockopt(mSocket,
442 SOL_SOCKET,
443 optname,
444#ifdef _ON_WINDOWS
445 (cf::char_t *)optval,
446#else
447 optval,
448#endif
449 (socklen_t)optlen);
450 if (result < 0)
451 THROW_EXCEPTION("cannot set socket option ("
452 << cf::exception::systemCode()
453 << ")");
454}
455
456cf::void_t cf::network::tcp::setNonBlocking(const cf::bool_t flag)
457{
458#ifdef _ON_WINDOWS
459 cf::ulong_t mode = flag ? 1 : 0;
460 ioctlsocket(mSocket, FIONBIO, &mode);
461#else
462 cf::int32_t mode = fcntl(mSocket, F_GETFL, 0);
463
464 if (flag) mode |= O_NONBLOCK;
465 else mode &= ~O_NONBLOCK;
466
467 fcntl(mSocket, F_SETFL, mode);
468#endif
469}
470
471cf::void_t cf::network::tcp::setTimeout(const cf::int32_t seconds)
472{
473 setNonBlocking(seconds > 0 /*? true : false*/);
474 mTimeout = seconds;
475}
476
477cf::network::host cf::network::tcp::peer() const
478 throw (cf::exception)
479{
480 try
481 {
482 return getSocketNameFromFunction(mSocket, getpeername);
483 }
484 catch (cf::exception & e)
485 {
486 FORWARD_EXCEPTION(e);
487 }
488}
489
490cf::network::host cf::network::tcp::local() const
491 throw (cf::exception)
492{
493 try
494 {
495 return getSocketNameFromFunction(mSocket, getsockname);
496 }
497 catch (cf::exception & e)
498 {
499 FORWARD_EXCEPTION(e);
500 }
501}
502
503std::string cf::network::nic::getMACAddress()
504 throw (cf::exception)
505{
506 static const cf::int32_t macSize = 6; /* = 48-bits */
507 static cf::bool_t isDone = false;
508 static cf::uint8_t bytes[macSize] = {0x00,};
509 static cf::char_t asciiz[macSize * 2 + 1] = {0x00,};
510
511 if (!isDone)
512 {
513 long result = 0;
514
515 result = GetMACAddress(reinterpret_cast<cf::char_t *>(bytes));
516 if (result)
517 THROW_EXCEPTION("cannot get mac-address");
518
519 for (cf::int32_t iter = 0 ; iter < macSize ; iter++)
520 snprintf(asciiz + (iter * 2), sizeof(asciiz) - 1,
521 "%02x",
522 bytes[iter]);
523
524 isDone = true;
525 }
526
527 return std::string(asciiz);
528}
529
530
531cf::uint32_t cf::network::byteOrder::htonl(cf::uint32_t in)
532{
533 return ::htonl(in);
534}
535
536cf::uint16_t cf::network::byteOrder::htons(cf::uint16_t in)
537{
538 return ::htons(in);
539}
540
541cf::uint32_t cf::network::byteOrder::ntohl(cf::uint32_t in)
542{
543 return ::ntohl(in);
544}
545
546cf::uint16_t cf::network::byteOrder::ntohs(cf::uint16_t in)
547{
548 return ::ntohs(in);
549}
Note: See TracBrowser for help on using the repository browser.