-
Notifications
You must be signed in to change notification settings - Fork 0
/
OSNet.h
2726 lines (2383 loc) · 79.4 KB
/
OSNet.h
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************************************************:')
OSNet.h
Network includes, typedefs, defines, initialization and some useful functions.
You must call InitNet() before using any low-level network function.
Fabrice Le Bars
Created : 2007
***************************************************************************************************************:)*/
// Prevent Visual Studio Intellisense from defining _WIN32 and _MSC_VER when we use
// Visual Studio to edit Linux or Borland C++ code.
#ifdef __linux__
# undef _WIN32
#endif // __linux__
#if defined(__GNUC__) || defined(__BORLANDC__)
# undef _MSC_VER
#endif // defined(__GNUC__) || defined(__BORLANDC__)
#ifndef OSNET_H
#define OSNET_H
#include "OSTime.h"
#ifndef DISABLE_THREADS_OSNET
#include "OSThread.h"
#endif // !DISABLE_THREADS_OSNET
/*
Debug macros specific to OSNet.
*/
#ifdef _DEBUG_MESSAGES_OSUTILS
# define _DEBUG_MESSAGES_OSNET
#endif // _DEBUG_MESSAGES_OSUTILS
#ifdef _DEBUG_WARNINGS_OSUTILS
# define _DEBUG_WARNINGS_OSNET
#endif // _DEBUG_WARNINGS_OSUTILS
#ifdef _DEBUG_ERRORS_OSUTILS
# define _DEBUG_ERRORS_OSNET
#endif // _DEBUG_ERRORS_OSUTILS
#ifdef _DEBUG_MESSAGES_OSNET
# define PRINT_DEBUG_MESSAGE_OSNET(params) PRINT_DEBUG_MESSAGE(params)
#else
# define PRINT_DEBUG_MESSAGE_OSNET(params)
#endif // _DEBUG_MESSAGES_OSNET
#ifdef _DEBUG_WARNINGS_OSNET
# define PRINT_DEBUG_WARNING_OSNET(params) PRINT_DEBUG_WARNING(params)
#else
# define PRINT_DEBUG_WARNING_OSNET(params)
#endif // _DEBUG_WARNINGS_OSNET
#ifdef _DEBUG_ERRORS_OSNET
# define PRINT_DEBUG_ERROR_OSNET(params) PRINT_DEBUG_ERROR(params)
#else
# define PRINT_DEBUG_ERROR_OSNET(params)
#endif // _DEBUG_ERRORS_OSNET
#ifdef _WIN32
// The maximum number of sockets that an application can actually use is independent of
// the number of sockets supported by a particular implementation. The maximum number of
// sockets that a Windows Sockets application can use is determined at compile time by the
// manifest constant FD_SETSIZE. This value is used in constructing the FD_SET structures
// used in select. The default value in Winsock2.h is 64.
//#define FD_SETSIZE 64
#else
//#define FD_SETSIZE 64
#endif // _WIN32
#ifdef _WIN32
#ifdef __BORLANDC__
// Disable some Borland C++ Builder warnings that happen in ws2tcpip.h.
#pragma warn -8004
#endif // __BORLANDC__
#include <winsock2.h>
#include <ws2tcpip.h>
#if (_WIN32_WINNT <= 0x0500)
#include <Wspiapi.h>
#endif // (_WIN32_WINNT <= 0x0500)
//#include <iphlpapi.h>
#ifdef __BORLANDC__
// Restore the Borland C++ Builder warnings previously disabled for ws2tcpip.h.
#pragma warn .8004
#endif // __BORLANDC__
#else
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#ifndef DISABLE_IOCTLSOCKET
#include <sys/ioctl.h>
#endif // !DISABLE_IOCTLSOCKET
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <arpa/inet.h>
#endif // _WIN32
#ifndef DEFAULT_SOCK_TIMEOUT
#define DEFAULT_SOCK_TIMEOUT 10000
#endif // !DEFAULT_SOCK_TIMEOUT
#define OTHER_DEV_TYPE_OSNET 0
#define TCP_CLIENT_DEV_TYPE_OSNET 1
#define TCP_SERVER_DEV_TYPE_OSNET 2
#define UDP_CLIENT_DEV_TYPE_OSNET 3
#define UDP_SERVER_DEV_TYPE_OSNET 4
#ifdef _WIN32
/*
Format a message corresponding to the last error in a system call related
to network with Winsock (thread-safe).
char* buf : (INOUT) Valid pointer to a buffer that will receive the message.
int buflen : (IN) Size of the buffer in bytes.
Return : buf.
*/
inline char* WSAFormatLastErrorMsg(char* buf, int buflen)
{
TCHAR* tstr = (TCHAR*)calloc((size_t)buflen, sizeof(TCHAR));
memset(buf, 0, (size_t)buflen);
if (tstr == NULL)
{
sprintf(buf, "calloc failed. ");
buf[buflen-1] = 0;
return buf;
}
memset(tstr, 0, (size_t)(buflen*sizeof(TCHAR)));
if (!FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK, // Remove the line break at the end.
// Note that there is still a dot and a space at the end.
NULL,
WSAGetLastError(),
0,
tstr,
(DWORD)buflen,
NULL
))
{
sprintf(buf, "FormatMessage failed. ");
buf[buflen-1] = 0;
free(tstr); tstr = NULL;
return buf;
}
#ifdef UNICODE
wcstombs(buf, tstr, buflen);
#else
memcpy(buf, tstr, buflen);
#endif // UNICODE
buf[buflen-1] = 0;
free(tstr); tstr = NULL;
return buf;
}
#else
typedef int SOCKET;
#define INVALID_SOCKET (-1)
#define SOCKET_ERROR (-1)
#define SD_RECEIVE SHUT_RD
#define SD_SEND SHUT_WR
#define SD_BOTH SHUT_RDWR
#ifndef DISABLE_IOCTLSOCKET
#define ioctlsocket ioctl
#endif // !DISABLE_IOCTLSOCKET
#define closesocket(sock) close((sock))
#endif // _WIN32
// Specific macro used with PRINT_DEBUG_MESSAGE, PRINT_DEBUG_WARNING
// or PRINT_DEBUG_ERROR to return the message corresponding to the last error
// in a system call related to network (with Winsock for Windows) in the
// current thread.
#ifdef _WIN32
#define WSAGetLastErrorMsg() WSAFormatLastErrorMsg(szLastErrMsg, LAST_ERROR_MSG_SIZE)
#else
#define WSAGetLastErrorMsg GetLastErrorMsg
#endif // _WIN32
/*
Initialize the network. Must be called once before the use of any network function.
Use ReleaseNet() to release the network at the end.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int InitNet(void)
{
#ifdef _WIN32
WSADATA wsaData;
// Initiate use of the Winsock 2 DLL (WS2_32.dll) by a process.
int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
switch (iResult)
{
case EXIT_SUCCESS:
break;
#ifdef _DEBUG_ERRORS_OSNET
case WSASYSNOTREADY:
PRINT_DEBUG_ERROR_OSNET(("InitNet error (%s) : %s"
"\n",
strtime_m(),
"The underlying network subsystem is not ready for network communication. "));
return EXIT_FAILURE;
case WSAVERNOTSUPPORTED:
PRINT_DEBUG_ERROR_OSNET(("InitNet error (%s) : %s"
"\n",
strtime_m(),
"The version of Windows Sockets support requested is not provided by this particular Windows Sockets implementation. "));
return EXIT_FAILURE;
case WSAEINPROGRESS:
PRINT_DEBUG_ERROR_OSNET(("InitNet error (%s) : %s"
"\n",
strtime_m(),
"A blocking Windows Sockets 1.1 operation is in progress. "));
return EXIT_FAILURE;
case WSAEPROCLIM:
PRINT_DEBUG_ERROR_OSNET(("InitNet error (%s) : %s"
"\n",
strtime_m(),
"A limit on the number of tasks supported by the Windows Sockets implementation has been reached. "));
return EXIT_FAILURE;
case WSAEFAULT:
PRINT_DEBUG_ERROR_OSNET(("InitNet error (%s) : %s"
"\n",
strtime_m(),
"The lpWSAData parameter is not a valid pointer. "));
return EXIT_FAILURE;
#endif // _DEBUG_ERRORS_OSNET
default:
PRINT_DEBUG_ERROR_OSNET(("InitNet error (%s) : %s"
"\n",
strtime_m(),
"WSAStartup failed. "));
return EXIT_FAILURE;
}
#else
#ifndef DISABLE_IGNORE_SIGPIPE
// See https://stackoverflow.com/questions/17332646/server-dies-on-send-if-client-was-closed-with-ctrlc...
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
{
PRINT_DEBUG_WARNING_OSNET(("InitNet warning (%s) : %s"
"\n",
strtime_m(),
"signal failed. "));
}
#endif // DISABLE_IGNORE_SIGPIPE
#endif // _WIN32
return EXIT_SUCCESS;
}
/*
Release the network (previously initialized by InitNet()).
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int ReleaseNet(void)
{
#ifdef _WIN32
// Terminate use of the Winsock 2 DLL (WS2_32.dll).
int iResult = WSACleanup();
switch (iResult)
{
case EXIT_SUCCESS:
break;
#ifdef _DEBUG_ERRORS_OSNET
case WSANOTINITIALISED:
PRINT_DEBUG_ERROR_OSNET(("ReleaseNet error (%s) : %s"
"\n",
strtime_m(),
"A successful WSAStartup call must occur before using this function. "));
return EXIT_FAILURE;
case WSAENETDOWN:
PRINT_DEBUG_ERROR_OSNET(("ReleaseNet error (%s) : %s"
"\n",
strtime_m(),
"The network subsystem has failed. "));
return EXIT_FAILURE;
case WSAEINPROGRESS:
PRINT_DEBUG_ERROR_OSNET(("ReleaseNet error (%s) : %s"
"\n",
strtime_m(),
"A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. "));
return EXIT_FAILURE;
#endif // _DEBUG_ERRORS_OSNET
default:
PRINT_DEBUG_ERROR_OSNET(("ReleaseNet error (%s) : %s"
"\n",
strtime_m(),
"WSACleanup failed. "));
return EXIT_FAILURE;
}
#endif
return EXIT_SUCCESS;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Portable functions that can be directly used.
//////////////////////////////////////////////////////////////////////////////////////////
// Note that struct sockaddr variables should be defined as struct sockaddr_storage (to be protocol independant) and then
// cast to struct sockaddr when called in functions that need this type (especially when it is a pointer).
// If a send or receive operation times out on a socket, the socket state is indeterminate, and should not be used.
// If the pNodeName parameter points to a computer name, all permanent addresses for the computer that can be used as a source address are returned.
// If the pNodeName parameter points to a string equal to "localhost", all loopback addresses on the local computer are returned.
// If the pNodeName parameter contains an empty string, all registered addresses on the local computer are returned.
// ppResult is a linked list.
// Do not set errno, use gai_strerror() for Linux (thread-safe?) or WSAGetLastErrorMsg() for Windows.
//int getaddrinfo(char* pNodeName, char* pServiceName, struct addrinfo* pHints, struct addrinfo** ppResult);
// Free the linked-list returned by getaddrinfo()
//void freeaddrinfo(struct addrinfo* pAi);
// Convert a socket address to a corresponding host/address and service/port.
// Use NI_MAXHOST and NI_MAXSERV for the size of host and serv.
// flags can be a combination of NI_NAMEREQD (a host name that cannot be resolved by DNS results in an error),
// NI_NOFQDN (return only the hostname part of the fully qualified domain name for local hosts)
// NI_NUMERICHOST (returns the numeric form of the host name instead of its name)
// NI_NUMERICSERV (returns the port number of the service instead of its name)
// NI_DGRAM (indicates that the service is an UDP service rather than TCP)
// Do not set errno, use gai_strerror() for Linux (thread-safe?) or WSAGetLastErrorMsg() for Windows.
//int getnameinfo(const struct sockaddr* sa, socklen_t salen, char* host, size_t hostlen, char* serv, size_t servlen, int flags);
// Translate the error codes of getaddrinfo() and getnameinfo() to a string for Linux.
//const char* gai_strerror(int errcode);
/*
Create a socket for a specific protocol (TCP/IPv4, UDP/IPv4, TCP/IPv6 or UDP/IPv6 are the
most common).
Used at the beginning to create a server or client application.
Often use the addrinfo results of a call to getaddrinfo().
InitNet() must be called before using any network function.
int af : (IN) Address family : AF_INET for IPv4, AF_INET6 for IPv6. Often set to the ai_family
field of an addrinfo element of the linked list returned by getaddrinfo().
int type : (IN) Socket type : SOCK_STREAM for TCP, SOCK_DGRAM for UDP. Often set to the ai_socktype
field of an addrinfo element of the linked list returned by getaddrinfo().
int protocol : (IN) Protocol to be used : IPPROTO_TCP for TCP, IPPROTO_UDP for UDP. Often set to the ai_protocol
field of an addrinfo element of the linked list returned by getaddrinfo().
Return : The socket created or INVALID_SOCKET if there is an error.
*/
//SOCKET socket(int af, int type, int protocol);
/*
Close an existing socket (defined as close() for Linux).
InitNet() must be called before using any network function.
SOCKET s : (IN) Socket to close.
Return : EXIT_SUCCESS or SOCKET_ERROR if there is an error.
*/
//int closesocket(SOCKET s);
/*
Associate a local address and port with a server socket.
InitNet() must be called before using any network function.
SOCKET s : (IN) Unbound server socket.
struct sockaddr* name : (IN) Address family, host address and port to assign to the socket as a sockaddr structure.
Can be obtained from getaddrinfo() (ai_addr field of the resulting addrinfo structures) or built using its
fields sin_family, sin_addr.s_addr (using the conversion function inet_addr()) and sin_port (using the
conversion function htons()). There are several special addresses : INADDR_LOOPBACK ("127.0.0.1") always
refers to the local host via the loopback device, INADDR_ANY ("0.0.0.0") means any address for binding.
When INADDR_ANY is specified, the socket will be bound to all local interfaces.
int namelen : (IN) Length of the value in the name parameter in bytes.
Return : EXIT_SUCCESS or SOCKET_ERROR if there is an error.
*/
//int bind(SOCKET s, struct sockaddr* name, int namelen);
/*
Place a socket in a state in which it is listening for an incoming connection. The socket is put into
passive mode where incoming connection requests are acknowledged and queued pending acceptance by the
process. If a connection request arrives and the queue is full, the client will receive an error.
Should be used only with TCP sockets.
InitNet() must be called before using any network function.
SOCKET s : (IN) Bound and unconnected server socket.
int backlog : (IN) Maximum length of the queue of pending connections. Set to 1 if there
should be only 1 simultaneous client or to SOMAXCONN for a default maximum reasonable value.
Return : EXIT_SUCCESS or SOCKET_ERROR if there is an error.
*/
//int listen(SOCKET s, int backlog);
/*
Determine the status of the sockets in the different fd_set structures, waiting if necessary until
at least one socket meets the specified criteria depending on timeout. Upon return, the fd_set structures
are updated to reflect the subset of the sockets that meet the specified condition.
Macros to manipulate and check fd_set contents :
FD_ZERO(fd_set* set)
Initialize the set to the null set.
FD_SET(int s, fd_set* set)
Add socket s to set.
FD_ISSET(int s, fd_set* set)
Nonzero if s is a member of the set. Otherwise, 0.
FD_CLR(int s, fd_set* set)
Remove the socket s from set.
Structure to define the timeout :
struct timeval {
long tv_sec; // Seconds.
long tv_usec; // Microseconds.
};
InitNet() must be called before using any network function.
int nfds : (IN) Highest-numbered file descriptor in any of the three sets, plus 1.
fd_set* pReadfds : (INOUT) Valid pointer to a set of sockets to be checked for readability
(data is available i.e. a recv(), recvfrom() is guaranteed not to block, a connect request has been received
by a listening socket such that an accept() is guaranteed to complete without blocking, or a request to
close the socket has been received). NULL to ignore.
fd_set* pWritefds : (INOUT) Valid pointer to a set of sockets to be checked for writability (data can be
sent i.e. a send(), sendto() is guaranteed to succeed). NULL to ignore.
fd_set* pExceptfds : (INOUT) Valid pointer to a set of sockets to be checked for errors/exceptions (do not use).
NULL to ignore.
struct timeval* pTimeout : (INOUT) Valid pointer to a timeval structure specifying the maximum time to wait,
NULL for infinite. Return immediately if the structure is initialized to {0,0}. The structure may be modified
after the call.
Return : The total number of sockets contained in the updated fd_set structures, 0 if the time limit expired
or SOCKET_ERROR if there is an error.
*/
//int select(int nfds, fd_set* pReadfds, fd_set* pWritefds, fd_set* pExceptfds, struct timeval* pTimeout);
/*
Extract the first connection request on the queue of pending connections for a listening socket.
Can block the caller until a connection is present.
Should be used only with TCP sockets.
InitNet() must be called before using any network function.
SOCKET s : (IN) Bound and listening server socket.
struct sockaddr* addr : (INOUT) Address family, host address and port of the accepted client socket as a
sockaddr structure (fields sin_family, sin_addr.s_addr (using the conversion function inet_addr()) and
sin_port (using the conversion function htons()). NULL to ignore.
int* addrlen : (INOUT) Valid pointer to the length of the addr parameter in bytes.
On return it will contain the actual length in bytes of the address returned. NULL to ignore.
Return : The client socket or INVALID_SOCKET if there is an error.
*/
//SOCKET accept(SOCKET s, struct sockaddr* addr, int* addrlen);
/*
Establish a connection to a server.
Usually used with TCP sockets.
InitNet() must be called before using any network function.
SOCKET s : (IN) Unconnected client socket.
struct sockaddr* name : (IN) Address family, host address and port of the server socket as a sockaddr
structure (fields sin_family, sin_addr.s_addr (using the conversion function inet_addr()) and sin_port
(using the conversion function htons()).
int namelen : (IN) Length of the value in the name parameter in bytes.
Return : EXIT_SUCCESS or SOCKET_ERROR if there is an error.
*/
//int connect(SOCKET s, struct sockaddr* name, int namelen);
//int send(SOCKET s, char* buf, int len, int flags);
//int recv(SOCKET s, char* buf, int len, int flags);
/*
Usually used with UDP sockets.
InitNet() must be called before using any network function.
struct sockaddr* to : (IN) Address family, host address and port of the target socket as a sockaddr
structure (fields sin_family, sin_addr.s_addr (using the conversion function inet_addr()) and sin_port
(using the conversion function htons()).
int tolen : (IN) Length of the value in the to parameter in bytes.
*/
//int sendto(SOCKET s, char* buf, int len, int flags, struct sockaddr* to, int tolen);
/*
Usually used with UDP sockets.
InitNet() must be called before using any network function.
struct sockaddr* from : (INOUT) Address family, host address and port of the source socket as a
sockaddr structure (fields sin_family, sin_addr.s_addr (using the conversion function inet_addr()) and
sin_port (using the conversion function htons()). NULL to ignore.
socklen_t* fromlen : (INOUT) Valid pointer to the length of the from parameter in bytes.
On return it will contain the actual length in bytes of the address returned. NULL to ignore.
*/
//int recvfrom(SOCKET s, char* buf, int len, int flags, struct sockaddr* from, socklen_t* fromlen);
//int shutdown(SOCKET s);
//int setsockopt(SOCKET s, int level, int optname, char *optval, int optlen);
/*
Set timeout options for a socket.
SOCKET sock : (IN) Socket.
int timeout : (IN) Timeout in ms for send and recv (0 to disable timeouts).
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int setsockettimeouts(SOCKET sock, int timeout)
{
#ifdef _WIN32
int iOptVal = 0;
#else
struct timeval tv;
#endif // _WIN32
int iOptLen = 0;
#ifdef _WIN32
iOptVal = timeout; // In ms.
iOptLen = sizeof(int);
if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&iOptVal, iOptLen) == SOCKET_ERROR)
{
PRINT_DEBUG_WARNING_OSNET(("setsockettimeouts warning (%s) : %s(sock=%d, timeout=%d)\n",
strtime_m(),
"setsockopt failed. ",
(int)sock, timeout));
//return EXIT_FAILURE;
}
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&iOptVal, iOptLen) == SOCKET_ERROR)
{
PRINT_DEBUG_WARNING_OSNET(("setsockettimeouts warning (%s) : %s(sock=%d, timeout=%d)\n",
strtime_m(),
"setsockopt failed. ",
(int)sock, timeout));
//return EXIT_FAILURE;
}
#else
tv.tv_sec = (long)(timeout/1000);
tv.tv_usec = (long)((timeout%1000)*1000);
iOptLen = sizeof(struct timeval);
if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, iOptLen) == SOCKET_ERROR)
{
PRINT_DEBUG_WARNING_OSNET(("setsockettimeouts warning (%s) : %s(sock=%d, timeout=%d)\n",
strtime_m(),
"setsockopt failed. ",
(int)sock, timeout));
//return EXIT_FAILURE;
}
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, iOptLen) == SOCKET_ERROR)
{
PRINT_DEBUG_WARNING_OSNET(("setsockettimeouts warning (%s) : %s(sock=%d, timeout=%d)\n",
strtime_m(),
"setsockopt failed. ",
(int)sock, timeout));
//return EXIT_FAILURE;
}
#endif // _WIN32
return EXIT_SUCCESS;
}
/*
Set SO_REUSEADDR option for a socket.
SOCKET sock : (IN) Socket.
BOOL reuseaddr : (IN) 1 to enable SO_REUSEADDR, 0 to disable.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int setsocketreuseaddr(SOCKET sock, BOOL reuseaddr)
{
int iOptVal = 0;
int iOptLen = 0;
iOptVal = (int)reuseaddr;
iOptLen = sizeof(int);
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&iOptVal, iOptLen) == SOCKET_ERROR)
{
PRINT_DEBUG_WARNING_OSNET(("setsocketreuseaddr warning (%s) : %s(sock=%d, reuseaddr=%d)\n",
strtime_m(),
"setsockopt failed. ",
(int)sock, (int)reuseaddr));
//return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
#ifndef DISABLE_IOCTLSOCKET
/*
Set blocking mode for a socket.
SOCKET sock : (IN) Socket.
BOOL blocking : (IN) 1 to make blocking, 0 to non-blocking.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int setsocketblocking(SOCKET sock, BOOL blocking)
{
#ifdef _WIN32
unsigned long blockingMode = (blocking? 0: 1);
if (ioctlsocket(sock, FIONBIO, &blockingMode) != NO_ERROR)
{
PRINT_DEBUG_ERROR_OSNET(("setsocketblocking error (%s) : (FIONBIO) %s(sock=%d, blocking=%d)\n",
strtime_m(),
WSAGetLastErrorMsg(),
(int)sock, (int)blocking));
return EXIT_FAILURE;
}
#else
int flags = fcntl(sock, F_GETFL, 0);
if (flags == -1)
{
PRINT_DEBUG_ERROR_OSNET(("setsocketblocking error (%s) : (F_GETFL) %s(sock=%d, blocking=%d)\n",
strtime_m(),
WSAGetLastErrorMsg(),
(int)sock, (int)blocking));
return EXIT_FAILURE;
}
flags = (blocking? (flags&~O_NONBLOCK): (flags|O_NONBLOCK));
if (fcntl(sock, F_SETFL, flags) != 0)
{
PRINT_DEBUG_ERROR_OSNET(("setsocketblocking error (%s) : (F_SETFL) %s(sock=%d, blocking=%d)\n",
strtime_m(),
WSAGetLastErrorMsg(),
(int)sock, (int)blocking));
return EXIT_FAILURE;
}
#endif // _WIN32
return EXIT_SUCCESS;
}
#endif // !DISABLE_IOCTLSOCKET
/*
Connect to an IPv4 TCP server.
SOCKET* pSock : (INOUT) Valid pointer to a socket that will be used to communicate with the server.
char* address : (IN) IPv4 address of the server.
char* port : (IN) TCP port of the server.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int inittcpcli(SOCKET* pSock, char* address, char* port)
{
struct sockaddr_in sa;
#ifdef _WIN32
WSADATA wsaData;
#endif // _WIN32
#ifdef _WIN32
// Initiate use of the Winsock 2 DLL (WS2_32.dll) by a process.
if (WSAStartup(MAKEWORD(2,2), &wsaData) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("inittcpcli error (%s) : %s(address=%s, port=%s)\n",
strtime_m(),
"WSAStartup failed. ",
address, port));
return EXIT_FAILURE;
}
#endif // _WIN32
// Create a TCP IPv4 socket.
*pSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (*pSock == INVALID_SOCKET)
{
PRINT_DEBUG_ERROR_OSNET(("inittcpcli error (%s) : %s(address=%s, port=%s)\n",
strtime_m(),
"socket failed. ",
address, port));
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return EXIT_FAILURE;
}
// Configure timeouts for send and recv.
if (setsockettimeouts(*pSock, DEFAULT_SOCK_TIMEOUT) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("inittcpcli error (%s) : %s(address=%s, port=%s)\n",
strtime_m(),
"setsockettimeouts failed. ",
address, port));
closesocket(*pSock);
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return EXIT_FAILURE;
}
memset(&sa, 0, sizeof(sa));
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
sa.sin_family = AF_INET;
sa.sin_port = htons((unsigned short)atoi(port));
sa.sin_addr.s_addr = inet_addr(address);
// Connect to server.
if (connect(*pSock, (struct sockaddr*)&sa, sizeof(sa)) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("inittcpcli error (%s) : %s(address=%s, port=%s)\n",
strtime_m(),
"connect failed. ",
address, port));
closesocket(*pSock);
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/*
Disconnect from an IPv4 TCP server.
SOCKET sock : (IN) Socket used to communicate with the server.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int releasetcpcli(SOCKET sock)
{
// Shutdown the connection.
if (shutdown(sock, SD_BOTH) != EXIT_SUCCESS)
{
PRINT_DEBUG_WARNING_OSNET(("releasetcpcli warning (%s) : %s(sock=%d)\n",
strtime_m(),
"shutdown failed. ",
(int)sock));
//return EXIT_FAILURE;
}
// Destroy the socket created by socket().
if (closesocket(sock) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("releasetcpcli error (%s) : %s(sock=%d)\n",
strtime_m(),
"closesocket failed. ",
(int)sock));
return EXIT_FAILURE;
}
#ifdef _WIN32
// Terminate use of the Winsock 2 DLL (WS2_32.dll).
if (WSACleanup() != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("releasetcpcli error (%s) : %s(sock=%d)\n",
strtime_m(),
"WSACleanup failed. ",
(int)sock));
return EXIT_FAILURE;
}
#endif // _WIN32
return EXIT_SUCCESS;
}
/*
Connect to an IPv4 UDP server.
SOCKET* pSock : (INOUT) Valid pointer to a socket that will be used to communicate with the server.
char* address : (IN) IPv4 address of the server.
char* port : (IN) UDP port of the server.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int initudpcli(SOCKET* pSock, char* address, char* port)
{
struct sockaddr_in sa;
#ifdef _WIN32
WSADATA wsaData;
#endif // _WIN32
#ifdef _WIN32
// Initiate use of the Winsock 2 DLL (WS2_32.dll) by a process.
if (WSAStartup(MAKEWORD(2,2), &wsaData) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("initudpcli error (%s) : %s(address=%s, port=%s)\n",
strtime_m(),
"WSAStartup failed. ",
address, port));
return EXIT_FAILURE;
}
#endif // _WIN32
// Create a UDP IPv4 socket.
*pSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (*pSock == INVALID_SOCKET)
{
PRINT_DEBUG_ERROR_OSNET(("initudpcli error (%s) : %s(address=%s, port=%s)\n",
strtime_m(),
"socket failed. ",
address, port));
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return EXIT_FAILURE;
}
// Configure timeouts for send and recv.
if (setsockettimeouts(*pSock, DEFAULT_SOCK_TIMEOUT) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("initudpcli error (%s) : %s(address=%s, port=%s)\n",
strtime_m(),
"setsockettimeouts failed. ",
address, port));
closesocket(*pSock);
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return EXIT_FAILURE;
}
memset(&sa, 0, sizeof(sa));
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
sa.sin_family = AF_INET;
sa.sin_port = htons((unsigned short)atoi(port));
sa.sin_addr.s_addr = inet_addr(address);
// // Associate the client to the desired address and port.
// if (bind(*pSock, (struct sockaddr*)&sa, sizeof(sa)) != EXIT_SUCCESS)
// {
// PRINT_DEBUG_ERROR_OSNET(("initudpcli error (%s) : %s(address=%s, port=%s)\n",
// strtime_m(),
// "bind failed. ",
// address, port));
// closesocket(*pSock);
//#ifdef _WIN32
// WSACleanup();
//#endif // _WIN32
// return EXIT_FAILURE;
// }
// Connect to server.
if (connect(*pSock, (struct sockaddr*)&sa, sizeof(sa)) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("initudpcli error (%s) : %s(address=%s, port=%s)\n",
strtime_m(),
"connect failed. ",
address, port));
closesocket(*pSock);
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/*
Disconnect from an IPv4 UDP server.
SOCKET sock : (IN) Socket used to communicate with the server.
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int releaseudpcli(SOCKET sock)
{
// Shutdown the connection.
if (shutdown(sock, SD_BOTH) != EXIT_SUCCESS)
{
PRINT_DEBUG_WARNING_OSNET(("releaseudpcli warning (%s) : %s(sock=%d)\n",
strtime_m(),
"shutdown failed. ",
(int)sock));
//return EXIT_FAILURE;
}
// Destroy the socket created by socket().
if (closesocket(sock) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("releaseudpcli error (%s) : %s(sock=%d)\n",
strtime_m(),
"closesocket failed. ",
(int)sock));
return EXIT_FAILURE;
}
#ifdef _WIN32
// Terminate use of the Winsock 2 DLL (WS2_32.dll).
if (WSACleanup() != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("releaseudpcli error (%s) : %s(sock=%d)\n",
strtime_m(),
"WSACleanup failed. ",
(int)sock));
return EXIT_FAILURE;
}
#endif // _WIN32
return EXIT_SUCCESS;
}
/*
Create an IPv4 TCP server.
SOCKET* pSock : (INOUT) Valid pointer to a server socket.
char* address : (IN) IPv4 address of the server. Set to "0.0.0.0" to use all local
network interfaces.
char* port : (IN) TCP port of the server.
int maxnbcli : (IN) Maximum number of simultaneous client connections. Set to 1 if there
should be only 1 simultaneous client or to SOMAXCONN for a default maximum reasonable value.
int timeout : (IN) Timeout in ms for send and recv (0 to disable timeouts).
Return : EXIT_SUCCESS or EXIT_FAILURE if there is an error.
*/
inline int inittcpsrv(SOCKET* pSock, char* address, char* port, int maxnbcli, int timeout)
{
struct sockaddr_in sa;
#ifdef _WIN32
WSADATA wsaData;
#endif // _WIN32
#ifdef _WIN32
// Initiate use of the Winsock 2 DLL (WS2_32.dll) by a process.
if (WSAStartup(MAKEWORD(2,2), &wsaData) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("inittcpsrv error (%s) : %s(address=%s, port=%s, maxnbcli=%d, timeout=%d)\n",
strtime_m(),
"WSAStartup failed. ",
address, port, maxnbcli, timeout));
return EXIT_FAILURE;
}
#endif // _WIN32
// Create a TCP IPv4 socket.
*pSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (*pSock == INVALID_SOCKET)
{
PRINT_DEBUG_ERROR_OSNET(("inittcpsrv error (%s) : %s(address=%s, port=%s, maxnbcli=%d, timeout=%d)\n",
strtime_m(),
"socket failed. ",
address, port, maxnbcli, timeout));
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return EXIT_FAILURE;
}
// Configure timeouts for send and recv.
if (setsockettimeouts(*pSock, timeout) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("inittcpsrv error (%s) : %s(address=%s, port=%s, maxnbcli=%d, timeout=%d)\n",
strtime_m(),
"setsockettimeouts failed. ",
address, port, maxnbcli, timeout));
closesocket(*pSock);
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return EXIT_FAILURE;
}
#ifndef DISABLE_TCPSERVER_SO_REUSEADDR
// Enable immediate reuse of the address and port.
if (setsocketreuseaddr(*pSock, TRUE) != EXIT_SUCCESS)
{
PRINT_DEBUG_ERROR_OSNET(("inittcpsrv error (%s) : %s(address=%s, port=%s, maxnbcli=%d, timeout=%d)\n",
strtime_m(),
"setsocketreuseaddr failed. ",
address, port, maxnbcli, timeout));
closesocket(*pSock);
#ifdef _WIN32
WSACleanup();
#endif // _WIN32
return EXIT_FAILURE;
}
#endif // DISABLE_TCPSERVER_SO_REUSEADDR
memset(&sa, 0, sizeof(sa));
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server.
sa.sin_family = AF_INET;
sa.sin_port = htons((unsigned short)atoi(port));
sa.sin_addr.s_addr = inet_addr(address);