ucommon  7.0.0
About: GNU uCommon C++ is a portable and optimized class framework for writing C++ applications that need to use threads and support concurrent synchronization, and that use sockets, XML parsing, object serialization, thread-optimized string and data structure classes, etc..
  Fossies Dox: ucommon-7.0.0.tar.gz  ("unofficial" and yet experimental doxygen-generated source code documentation)  

Loading...
Searching...
No Matches
socket.h
Go to the documentation of this file.
1// Copyright (C) 1999-2005 Open Source Telecom Corporation.
2// Copyright (C) 2006-2013 David Sugar, Tycho Softworks.
3// Copyright (C) 2014 David Sugar, Tycho Softworks, Savoir-Faire Linux Inc.
4// Copyright (C) 2015 Cherokees of Idaho, Savoir-Faire Linux Inc.
5//
6// This program is free software; you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation; either version 2 of the License, or
9// (at your option) any later version.
10//
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15//
16// You should have received a copy of the GNU Lesser General Public License
17// along with this program. If not, see <http://www.gnu.org/licenses/>.
18//
19// As a special exception, you may use this file as part of a free software
20// library without restriction. Specifically, if other files instantiate
21// templates or use macros or inline functions from this file, or you compile
22// this file and link it with other files to produce an executable, this
23// file does not by itself cause the resulting executable to be covered by
24// the GNU General Public License. This exception does not however
25// invalidate any other reasons why the executable file might be covered by
26// the GNU General Public License.
27//
28// This exception applies only to the code released under the name GNU
29// Common C++. If you copy code from other releases into a copy of GNU
30// Common C++, as the General Public License permits, the exception does
31// not apply to the code that you add in this way. To avoid misleading
32// anyone as to the status of such modified files, you must delete
33// this exception notice from them.
34//
35// If you write modifications of your own for GNU Common C++, it is your choice
36// whether to permit this exception to apply to your modifications.
37// If you do not wish that, delete this exception notice.
38//
39
40/**
41 * @file commoncpp/socket.h
42 * @short socket operations.
43 **/
44
45#ifndef COMMONCPP_SOCKET_H_
46#define COMMONCPP_SOCKET_H_
47
48#include <cstdio>
49
50#ifndef COMMONCPP_CONFIG_H_
51#include <commoncpp/config.h>
52#endif
53
54#ifndef COMMONCPP_STRING_H_
55#include <commoncpp/string.h>
56#endif
57
58#ifndef COMMONCPP_ADDRESS_H_
59#include <commoncpp/address.h>
60#endif
61
62#ifndef COMMONCPP_EXCEPTION_H_
63#include <commoncpp/exception.h>
64#endif
65
66#ifndef MSG_DONTWAIT
67#define MSG_DONTWAIT 0
68#endif
69
70#ifndef MSG_NOSIGNAL
71#define MSG_NOSIGNAL 0
72#endif
73
74#ifndef SOCK_DCCP
75#define SOCK_DCCP 6
76#endif
77#ifndef IPPROTO_DCCP
78#define IPPROTO_DCCP 33
79#endif
80#ifndef SOL_DCCP
81#define SOL_DCCP 269
82#endif
83#define DCCP_SOCKOPT_AVAILABLE_CCIDS 12
84#define DCCP_SOCKOPT_CCID 13
85#define DCCP_SOCKOPT_TX_CCID 14
86#define DCCP_SOCKOPT_RX_CCID 15
87
88namespace ost {
89
91
93{
94public:
95 enum State {
101 STREAM
102 };
103 typedef enum State State;
104
105 enum Family {
106#ifdef CCXX_IPV6
107 IPV6 = AF_INET6,
108#endif
109 IPV4 = AF_INET
110 };
111
112 typedef enum Family Family;
113
114 enum Error {
115 errSuccess = 0,
143 errInvalidValue
144 };
145
146 typedef enum Error Error;
147
148 enum Tos {
149 tosLowDelay = 0,
153 tosInvalid
154 };
155 typedef enum Tos Tos;
156
157 enum Pending {
160 pendingError
161 };
162 typedef enum Pending Pending;
163
164private:
165 // used by exception handlers....
166 mutable Error errid;
167 mutable const char *errstr;
168 mutable long syserr;
169
170 void setSocket(void);
171
172protected:
173 static socket_t dupSocket(socket_t s,Socket::State state);
174
175 mutable struct {
176 bool thrown: 1;
177 bool broadcast: 1;
178 bool route: 1;
179 bool keepalive: 1;
180 bool loopback: 1;
181 bool multicast: 1;
182 bool completion: 1;
183 bool linger: 1;
184 unsigned ttl: 8;
185 } flags;
186
187 State volatile state;
188
189 /**
190 * This service is used to throw all socket errors which usually
191 * occur during the socket constructor.
192 *
193 * @param error defined socket error id.
194 * @param err string or message to pass.
195 * @param systemError the system error# that caused the error
196 */
197 Error error(Error error, const char *err = NULL, long systemError = 0) const;
198
199 /**
200 * This service is used to throw application defined socket errors
201 * where the application specific error code is a string.
202 *
203 * @param err string or message to pass.
204 */
205 inline void error(const char *err) const {
206 error(errExtended, err);
207 }
208
209 /**
210 * This service is used to turn the error handler on or off for
211 * "throwing" exceptions by manipulating the thrown flag.
212 *
213 * @param enable true to enable handler.
214 */
215 inline void setError(bool enable) {
216 flags.thrown = !enable;
217 }
218
219 /**
220 * Used as the default destructor for ending a socket. This
221 * will cleanly terminate the socket connection. It is provided
222 * for use in derived virtual destructors.
223 */
224 void endSocket(void);
225
226 /**
227 * Used as a common handler for connection failure processing.
228 *
229 * @return correct failure code to apply.
230 */
231 Error connectError(void) const;
232
233 /**
234 * Set the send limit.
235 */
236 Error sendLimit(int limit = 2048);
237
238 /**
239 * Set thr receive limit.
240 */
241 Error receiveLimit(int limit = 1);
242
243 /**
244 * Set the send timeout for sending raw network data.
245 *
246 * @return errSuccess if set.
247 * @param timer value in millisec.
248 */
249 Error sendTimeout(timeout_t timer);
250
251 /**
252 * Receive timeout for receiving raw network data.
253 *
254 * @return errSuccess if set.
255 * @param timer value in milliseconds.
256 */
257 Error receiveTimeout(timeout_t timer);
258
259 /**
260 * Set the protocol stack network kernel send buffer size
261 * associated with the socket.
262 *
263 * @return errSuccess on success, or error.
264 * @param size of buffer in bytes.
265 */
266 Error sendBuffer(unsigned size);
267
268 /**
269 * Set the protocol stack network kernel receive buffer size
270 * associated with the socket.
271 *
272 * @return errSuccess on success, or error.
273 * @param size of buffer in bytes.
274 */
275 Error receiveBuffer(unsigned size);
276
277 /**
278 * Set the total protocol stack network kernel buffer size
279 * for both send and receive together.
280 *
281 * @return errSuccess on success
282 * @param size of buffer.
283 */
284 Error bufferSize(unsigned size);
285
286 /**
287 * Set the subnet broadcast flag for the socket. This enables
288 * sending to a subnet and may require special image privileges
289 * depending on the operating system.
290 *
291 * @return 0 (errSuccess) on success, else error code.
292 * @param enable when set to true.
293 */
294 Error setBroadcast(bool enable);
295
296 /**
297 * Setting multicast binds the multicast interface used for
298 * the socket to the interface the socket itself has been
299 * implicitly bound to. It is also used as a check flag
300 * to make sure multicast is enabled before multicast
301 * operations are used.
302 *
303 * @return 0 (errSuccess) on success, else error code.
304 * @param enable when set to true.
305 * @param family of protocol.
306 */
307 Error setMulticastByFamily(bool enable, Family family = IPV4);
308
309 /**
310 * Set the multicast loopback flag for the socket. Loopback
311 * enables a socket to hear what it is sending.
312 *
313 * @return 0 (errSuccess) on success, else error code.
314 * @param enable when set to true.
315 * @param family of protocol.
316 */
317 Error setLoopbackByFamily(bool enable, Family family = IPV4);
318
319 /**
320 * Set the multicast time to live for a multicast socket.
321 *
322 * @return 0 (errSuccess) on success, else error code.
323 * @param ttl time to live.
324 * @param fam family of protocol.
325 */
326 Error setTimeToLiveByFamily(uint8_t ttl, Family fam = IPV4);
327
328 /**
329 * Join a multicast group.
330 *
331 * @return 0 (errSuccess) on success, else error code.
332 * @param ia address of multicast group to join.
333 */
334 Error join(const ucommon::Socket::address &ia, int iface = 0);
335 inline Error join(const IPV4Multicast &ia) {
336 return join(ucommon::Socket::address(getaddress(ia)));
337 }
338#ifdef CCXX_IPV6
339 inline Error join(const IPV6Multicast &ia, int iface = 0) {
340 return join(ucommon::Socket::address(getaddress(ia)), iface);
341 }
342#endif
343
344 /**
345 * Drop membership from a multicast group.
346 *
347 * @return 0 (errSuccess) on success, else error code.
348 * @param ia address of multicast group to drop.
349 */
350 Error drop(const ucommon::Socket::address &ia, int iface = 0);
352 return drop(ucommon::Socket::address(getaddress(ia)));
353 }
354#ifdef CCXX_IPV6
355 Error drop(const IPV6Multicast &ia, int iface = 0) {
356 return drop(ucommon::Socket::address(getaddress(ia)), iface);
357 }
358#endif
359
360 /**
361 * Set the socket routing to indicate if outgoing messages
362 * should bypass normal routing (set false).
363 *
364 * @return 0 on success.
365 * @param enable normal routing when set to true.
366 */
367 Error setRouting(bool enable);
368
369 /**
370 * Enable/disable delaying packets (Nagle algorithm)
371 *
372 * @return 0 on success.
373 * @param enable disable Nagle algorithm when set to true.
374 */
375 Error setNoDelay(bool enable);
376
377 /**
378 * An unconnected socket may be created directly on the local
379 * machine. Sockets can occupy both the internet domain (AF_INET)
380 * and UNIX socket domain (AF_UNIX) under unix. The socket type
381 * (SOCK_STREAM, SOCK_DGRAM) and protocol may also be specified.
382 * If the socket cannot be created, an exception is thrown.
383 *
384 * @param domain socket domain to use.
385 * @param type base type and protocol family of the socket.
386 * @param protocol specific protocol to apply.
387 */
388 Socket(int domain, int type, int protocol = 0);
389
390 /**
391 * A socket object may be created from a file descriptor when that
392 * descriptor was created either through a socket() or accept()
393 * call. This constructor is mostly for internal use.
394 *
395 * @param fd file descriptor of an already existing socket.
396 */
397 Socket(socket_t fd);
398
399 /**
400 * Create an inactive socket object for base constructors.
401 */
402 Socket();
403
404 /**
405 * A socket can also be constructed from an already existing
406 * Socket object. On POSIX systems, the socket file descriptor
407 * is dup()'d. On Win32, DuplicateHandle() is used.
408 *
409 * @param source of existing socket to clone.
410 */
411 Socket(const Socket &source);
412
413 /**
414 * Process a logical input line from a socket descriptor
415 * directly.
416 *
417 * @param buf pointer to string.
418 * @param len maximum length to read.
419 * @param timeout for pending data in milliseconds.
420 * @return number of bytes actually read.
421 */
422 ssize_t readLine(char *buf, size_t len, timeout_t timeout = 0);
423
424 /**
425 * Read in a block of len bytes with specific separator. Can
426 * be zero, or any other char. If \\n or \\r, it's treated just
427 * like a readLine(). Otherwise it looks for the separator.
428 *
429 * @param buf pointer to byte allocation.
430 * @param len maximum length to read.
431 * @param separator separator for a particular ASCII character
432 * @param t timeout for pending data in milliseconds.
433 * @return number of bytes actually read.
434 */
435 virtual ssize_t readData(void * buf,size_t len,char separator=0,timeout_t t=0);
436
437 /**
438 * Write a block of len bytes to socket.
439 *
440 * @param buf pointer to byte allocation.
441 * @param len maximum length to write.
442 * @param t timeout for pending data in milliseconds.
443 * @return number of bytes actually written.
444 */
445 virtual ssize_t writeData(const void* buf,size_t len,timeout_t t=0);
446
447public:
448 ~Socket();
449
450 /**
451 * Often used by a "catch" to fetch the last error of a thrown
452 * socket.
453 *
454 * @return error number of Error error.
455 */
456 inline Error getErrorNumber(void) const {
457 return errid;
458 }
459
460 /**
461 * Often used by a "catch" to fetch the user set error string
462 * of a thrown socket, but only if EXTENDED error codes are used.
463 *
464 * @return string for error message.
465 */
466 inline const char *getErrorString(void) const {
467 return errstr;
468 }
469
470 inline long getSystemError(void) const {
471 return syserr;
472 }
473
474 const char *getSystemErrorString(void) const;
475
476 /**
477 * Get the status of pending operations. This can be used to
478 * examine if input or output is waiting, or if an error has
479 * occured on the descriptor.
480 *
481 * @return true if ready, false on timeout.
482 * @param pend ready check to perform.
483 * @param timeout in milliseconds, inf. if not specified.
484 */
485 virtual bool isPending(Pending pend, timeout_t timeout = TIMEOUT_INF);
486
487 /**
488 * See if a specific protocol family is available in the
489 * current runtime environment.
490 *
491 * @return true if family available.
492 */
493 static bool check(Family fam);
494
495 /**
496 * Operator based testing to see if a socket is currently
497 * active.
498 */
499 bool operator!() const;
500
501 operator bool() const;
502
503 /**
504 * Sockets may also be duplicated by the assignment operator.
505 */
506 Socket &operator=(const Socket &from);
507
508 /**
509 * May be used to examine the origin of data waiting in the
510 * socket receive queue. This can tell a TCP server where pending
511 * "connect" requests are coming from, or a UDP socket where it's
512 * next packet arrived from.
513 *
514 * @param port ptr to port number of sender.
515 * @return host address, test with "isInetAddress()".
516 */
517 ucommon::Socket::address getSender() const;
518
519 virtual IPV4Host getIPV4Sender(in_port_t *port = NULL) const;
520
521 inline IPV4Host getSender(in_port_t *port) const {
522 return getIPV4Sender(port);
523 }
524
525#ifdef CCXX_IPV6
526 virtual IPV6Host getIPV6Sender(in_port_t *port = NULL) const;
527#endif
528
529 /**
530 * Get the host address and port of the socket this socket
531 * is connected to. If the socket is currently not in a
532 * connected state, then a host address of 0.0.0.0 is
533 * returned.
534 *
535 * @param port ptr to port number of remote socket.
536 * @return host address of remote socket.
537 */
538 ucommon::Socket::address getPeer() const;
539
540 IPV4Host getIPV4Peer(in_port_t *port = NULL) const;
541
542 inline IPV4Host getPeer(in_port_t *port) const {
543 return getIPV4Peer(port);
544 }
545
546#ifdef CCXX_IPV6
547 IPV6Host getIPV6Peer(in_port_t *port = NULL) const;
548#endif
549
550 /**
551 * Get the local address and port number this socket is
552 * currently bound to.
553 *
554 * @param port ptr to port number on local host.
555 * @return host address of interface this socket is bound to.
556 */
557 IPV4Host getIPV4Local(in_port_t *port = NULL) const;
558
559 inline IPV4Host getLocal(in_port_t *port) const {
560 return getIPV4Local(port);
561 }
562
563#ifdef CCXX_IPV6
564 IPV6Host getIPV6Local(in_port_t *port = NULL) const;
565#endif
566
567 ucommon::Socket::address getLocal() const;
568
569 /**
570 * Used to specify blocking mode for the socket. A socket
571 * can be made non-blocking by setting setCompletion(false)
572 * or set to block on all access with setCompletion(true).
573 * I do not believe this form of non-blocking socket I/O is supported
574 * in winsock, though it provides an alternate asynchronous set of
575 * socket services.
576 *
577 * @param immediate mode specify socket I/O call blocking mode.
578 */
579 void setCompletion(bool immediate);
580
581 /**
582 * Enable lingering sockets on close.
583 *
584 * @param linger specify linger enable.
585 */
586 Error setLinger(bool linger);
587
588 /**
589 * Set the keep-alive status of this socket and if keep-alive
590 * messages will be sent.
591 *
592 * @return 0 on success.
593 * @param enable keep alive messages.
594 */
595 Error setKeepAlive(bool enable);
596
597 /**
598 * Set packet scheduling on platforms which support ip quality
599 * of service conventions. This effects how packets in the
600 * queue are scheduled through the interface.
601 *
602 * @return 0 on success, error code on failure.
603 * @param service type of service enumerated type.
604 */
605 Error setTypeOfService(Tos service);
606
607 /**
608 * Can test to see if this socket is "connected", and hence
609 * whether a "catch" can safely call getPeer(). Of course,
610 * an unconnected socket will return a 0.0.0.0 address from
611 * getPeer() as well.
612 *
613 * @return true when socket is connected to a peer.
614 */
615 bool isConnected(void) const;
616
617 /**
618 * Test to see if the socket is at least operating or if it
619 * is mearly initialized. "initialized" sockets may be the
620 * result of failed constructors.
621 *
622 * @return true if not in initial state.
623 */
624 bool isActive(void) const;
625
626 /**
627 * Return if broadcast has been enabled for the specified
628 * socket.
629 *
630 * @return true if broadcast socket.
631 */
632 inline bool isBroadcast(void) const {
633 return flags.broadcast;
634 }
635
636 /**
637 * Return if socket routing is enabled.
638 *
639 * @return true if routing enabled.
640 */
641 inline bool isRouted(void) const {
642 return flags.route;
643 }
644
645
646 inline struct in_addr getaddress(const IPV4Address &ia) const {
647 return ia.getAddress();
648 }
649
650#ifdef CCXX_IPV6
651 inline struct in6_addr getaddress(const IPV6Address &ia) const {
652 return ia.getAddress();
653 }
654#endif
655
656};
657
658#if defined(CCXX_EXCEPTIONS)
659
660class __EXPORT SockException : public IOException
661{
662private:
663 Socket::Error _socketError;
664
665public:
666 inline SockException(const String &str, Socket::Error socketError, long systemError = 0) :
667 IOException(str, systemError), _socketError(socketError) {}
668
669 inline Socket::Error getSocketError() const {
670 return _socketError;
671 }
672};
673
674#endif
675
676} // namespace ost
677
678#endif
Network addresses and sockets related classes.
The network name and address objects are all derived from a common IPV4Address base class.
Definition: address.h:363
This object is used to hold the actual and valid internet address of a specific host machine that wil...
Definition: address.h:579
A specialization of IPV4Address that provides address validation for multicast addresses.
Definition: address.h:652
long syserr
Definition: socket.h:168
bool route
Definition: socket.h:178
bool loopback
Definition: socket.h:180
@ tosReliability
Definition: socket.h:151
@ tosThroughput
Definition: socket.h:150
@ tosMinCost
Definition: socket.h:152
bool broadcast
Definition: socket.h:177
@ pendingOutput
Definition: socket.h:159
@ pendingInput
Definition: socket.h:158
enum Error Error
Definition: socket.h:146
IPV4Host getLocal(in_port_t *port) const
Definition: socket.h:559
bool keepalive
Definition: socket.h:179
Error errid
Definition: socket.h:166
bool linger
Definition: socket.h:183
bool isRouted(void) const
Return if socket routing is enabled.
Definition: socket.h:641
unsigned ttl
Definition: socket.h:184
IPV4Host getSender(in_port_t *port) const
Definition: socket.h:521
void setError(bool enable)
This service is used to turn the error handler on or off for "throwing" exceptions by manipulating th...
Definition: socket.h:215
Error getErrorNumber(void) const
Often used by a "catch" to fetch the last error of a thrown socket.
Definition: socket.h:456
State volatile state
Definition: socket.h:187
enum Tos Tos
Definition: socket.h:155
long getSystemError(void) const
Definition: socket.h:470
bool multicast
Definition: socket.h:181
const char * getErrorString(void) const
Often used by a "catch" to fetch the user set error string of a thrown socket, but only if EXTENDED e...
Definition: socket.h:466
bool thrown
Definition: socket.h:176
bool isBroadcast(void) const
Return if broadcast has been enabled for the specified socket.
Definition: socket.h:632
enum Family Family
Definition: socket.h:112
enum Pending Pending
Definition: socket.h:162
Error drop(const IPV4Multicast &ia)
Definition: socket.h:351
enum State State
Definition: socket.h:103
void error(const char *err) const
This service is used to throw application defined socket errors where the application specific error ...
Definition: socket.h:205
@ CONNECTED
Definition: socket.h:99
@ CONNECTING
Definition: socket.h:100
@ AVAILABLE
Definition: socket.h:97
@ INITIAL
Definition: socket.h:96
@ errConnectInvalid
Definition: socket.h:128
@ errOutput
Definition: socket.h:121
@ errLookupFail
Definition: socket.h:141
@ errCopyFailed
Definition: socket.h:117
@ errConnectNoRoute
Definition: socket.h:130
@ errServiceUnavailable
Definition: socket.h:136
@ errKeepaliveDenied
Definition: socket.h:134
@ errResourceFailure
Definition: socket.h:120
@ errTimeout
Definition: socket.h:138
@ errBindingFailed
Definition: socket.h:131
@ errNotConnected
Definition: socket.h:123
@ errServiceDenied
Definition: socket.h:135
@ errConnectFailed
Definition: socket.h:127
@ errConnectRejected
Definition: socket.h:125
@ errMulticastDisabled
Definition: socket.h:137
@ errSearchErr
Definition: socket.h:142
@ errCreateFailed
Definition: socket.h:116
@ errExtended
Definition: socket.h:140
@ errRoutingDenied
Definition: socket.h:133
@ errInput
Definition: socket.h:118
@ errInputInterrupt
Definition: socket.h:119
@ errBroadcastDenied
Definition: socket.h:132
@ errConnectBusy
Definition: socket.h:129
@ errConnectRefused
Definition: socket.h:124
@ errConnectTimeout
Definition: socket.h:126
@ errOutputInterrupt
Definition: socket.h:122
@ errNoDelay
Definition: socket.h:139
bool completion
Definition: socket.h:182
Error join(const IPV4Multicast &ia)
Definition: socket.h:335
const char * errstr
Definition: socket.h:167
IPV4Host getPeer(in_port_t *port) const
Definition: socket.h:542
A generic socket address class.
Definition: socket.h:365
A generic socket base class.
Definition: socket.h:328
Common C++ generic string class.
#define TIMEOUT_INF
Definition: config.h:58
#define __EXPORT
Definition: config.h:49
GNU Common C++ exception model base classes.
static shell::numericopt timeout('t', "--timeout", _TEXT("optional keyboard input timeout"), "seconds", 0)
Definition: address.cpp:63
struct in_addr getaddress(const IPV4Address &ia)
Definition: address.h:692
socket_t SOCKET
Definition: socket.h:90
String str(Socket &so, size_t size)
Definition: socket.cpp:3507
static shell::stringopt error('e', "--error", _TEXT("stderr path to use"), "filename")
int socket_t
Definition: platform.h:414
unsigned long timeout_t
Definition: platform.h:453
static shell::numericopt port('p', "--port", _TEXT("port to use"), "port", 0)