-
Notifications
You must be signed in to change notification settings - Fork 2
/
nio4c_socket.c
1174 lines (935 loc) · 29.6 KB
/
nio4c_socket.c
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
/*
* nio4c_socket.c
*
* copyright (c) 2019, 2020 Xiongfei Shi
*
* author: Xiongfei Shi <xiongfei.shi(a)icloud.com>
* license: Apache-2.0
*
* https://github.com/shixiongfei/nio4c
*/
#include "nio4c_internal.h"
#if defined(__APPLE__)
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/network/IOEthernetController.h>
#include <IOKit/network/IOEthernetInterface.h>
#include <IOKit/network/IONetworkInterface.h>
#define TCP_KEEPIDLE TCP_KEEPALIVE
#if MAC_OS_X_VERSION_MAX_ALLOWED < 120000 // Before macOS 12 Monterey
#define kIOMainPortDefault kIOMasterPortDefault
#endif
#endif
#if defined(__linux__) || defined(__BSD__)
#include <net/ethernet.h>
#include <net/if_arp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#endif
#ifdef _WIN32
#include <mstcpip.h>
#include <process.h>
#include <stdio.h>
#ifdef _MSC_VER
static const struct in6_addr in6addr_any = {{{0}}};
#endif
#define socklen_t int
#define socket_errno() WSAGetLastError()
#define SOCKERR_EAGAIN WSAEWOULDBLOCK
#define SOCKERR_EINPROGRESS WSAEINPROGRESS
#else
#define SOCKET int
#define socket_errno() errno
#define SOCKERR_EAGAIN EAGAIN
#define SOCKERR_EINPROGRESS EINPROGRESS
#endif
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 64
#endif
#ifdef _MSC_VER
#define strncasecmp _strnicmp
#endif
#ifndef IPV6_ADD_MEMBERSHIP
#ifdef IPV6_JOIN_GROUP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif
#endif
#ifndef IPV6_DROP_MEMBERSHIP
#ifdef IPV6_LEAVE_GROUP
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif
#endif
const char *nio_gethostname(void) {
static char buffer[MAXHOSTNAMELEN] = {0};
if (!buffer[0]) {
if (0 != gethostname(buffer, sizeof(buffer))) {
strcpy(buffer, "localhost");
}
}
return buffer;
}
#if defined(__APPLE__)
static kern_return_t find_ethernet_interfaces(io_iterator_t *matchingServices,
int primary_only) {
CFMutableDictionaryRef matchingDict;
matchingDict = IOServiceMatching(kIOEthernetInterfaceClass);
if (primary_only && (NULL != matchingDict)) {
CFMutableDictionaryRef propertyMatchDict;
propertyMatchDict = CFDictionaryCreateMutable(
kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if (NULL != propertyMatchDict) {
CFDictionarySetValue(propertyMatchDict, CFSTR(kIOPrimaryInterface),
kCFBooleanTrue);
CFDictionarySetValue(matchingDict, CFSTR(kIOPropertyMatchKey),
propertyMatchDict);
CFRelease(propertyMatchDict);
}
}
return IOServiceGetMatchingServices(kIOMainPortDefault, matchingDict,
matchingServices);
}
int nio_gethwaddr(niohwaddr_t *hwaddr, int count) {
io_iterator_t intfIterator;
io_object_t intfService;
io_object_t controllerService;
int num = 0;
if (KERN_SUCCESS != find_ethernet_interfaces(&intfIterator, 1))
if (KERN_SUCCESS != find_ethernet_interfaces(&intfIterator, 0))
return 0;
while ((num < count) && !!(intfService = IOIteratorNext(intfIterator))) {
CFTypeRef MACAddressAsCFData;
if (KERN_SUCCESS != IORegistryEntryGetParentEntry(
intfService, kIOServicePlane, &controllerService))
continue;
MACAddressAsCFData = IORegistryEntryCreateCFProperty(
controllerService, CFSTR(kIOMACAddress), kCFAllocatorDefault, 0);
if (MACAddressAsCFData) {
CFDataGetBytes(MACAddressAsCFData, CFRangeMake(0, kIOEthernetAddressSize),
hwaddr[num++].hwaddr);
CFRelease(MACAddressAsCFData);
}
IOObjectRelease(controllerService);
}
IOObjectRelease(intfIterator);
return num;
}
#elif defined(_WIN32)
static int is_physical_adapter(const char *name) {
char buffer[256] = {0};
DWORD dwType = REG_SZ, dwDataLen;
HKEY hNetKey = NULL;
sprintf(buffer,
"SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-"
"BFC1-08002BE10318}\\%s\\Connection",
name);
if (ERROR_SUCCESS !=
RegOpenKeyExA(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hNetKey))
return 0;
dwDataLen = sizeof(buffer);
if (ERROR_SUCCESS == RegQueryValueExA(hNetKey, "MediaSubType", 0, &dwType,
(LPBYTE)buffer, &dwDataLen)) {
DWORD dwMediaSubType = *(DWORD *)buffer;
/* 0x01 local network, 0x02 wifi network. */
if ((0x01 != dwMediaSubType) && (0x02 != dwMediaSubType)) {
RegCloseKey(hNetKey);
return 0;
}
}
dwDataLen = sizeof(buffer);
if (ERROR_SUCCESS != RegQueryValueExA(hNetKey, "PnpInstanceID", 0, &dwType,
(LPBYTE)buffer, &dwDataLen)) {
RegCloseKey(hNetKey);
return 0;
}
RegCloseKey(hNetKey);
return 0 == strncasecmp(buffer, "PCI", 3);
}
int nio_gethwaddr(niohwaddr_t *hwaddr, int count) {
IP_ADAPTER_ADDRESSES *pAdapterAddr = NULL;
ULONG ulOutBufLen = 0;
ULONG ulFlags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST |
GAA_FLAG_SKIP_DNS_SERVER;
int num = 0;
if (ERROR_BUFFER_OVERFLOW == GetAdaptersAddresses(AF_UNSPEC, ulFlags, NULL,
pAdapterAddr,
&ulOutBufLen)) {
pAdapterAddr = (IP_ADAPTER_ADDRESSES *)nio_malloc(ulOutBufLen);
if (!pAdapterAddr)
return -1;
}
if (NO_ERROR == GetAdaptersAddresses(AF_UNSPEC, ulFlags, NULL, pAdapterAddr,
&ulOutBufLen)) {
IP_ADAPTER_ADDRESSES *pAdapter;
for (pAdapter = pAdapterAddr; (NULL != pAdapter) && (num < count);
pAdapter = pAdapter->Next) {
MIB_IFROW mib;
memset(&mib, 0, sizeof(MIB_IFROW));
if (pAdapter->IfIndex > 0)
mib.dwIndex = pAdapter->IfIndex;
else if (pAdapter->Ipv6IfIndex > 0)
mib.dwIndex = pAdapter->Ipv6IfIndex;
else
continue;
if (NO_ERROR != GetIfEntry(&mib))
continue;
if ((IF_TYPE_ETHERNET_CSMACD == pAdapter->IfType) ||
(IF_TYPE_IEEE80211 == pAdapter->IfType))
if (is_physical_adapter(pAdapter->AdapterName))
memcpy(hwaddr[num++].hwaddr, pAdapter->PhysicalAddress,
pAdapter->PhysicalAddressLength);
}
}
if (pAdapterAddr)
nio_free(pAdapterAddr);
return num;
}
#else
int nio_gethwaddr(niohwaddr_t *hwaddr, int count) {
struct ifaddrs *ifaddr;
struct ifaddrs *ifa;
int num = 0;
if (0 != getifaddrs(&ifaddr))
return 0;
for (ifa = ifaddr; (NULL != ifa) && (num < count); ifa = ifa->ifa_next) {
if ((ifa->ifa_addr) && (AF_LINK == ifa->ifa_addr->sa_family)) {
struct ifreq ifr;
int fd = socket(AF_INET, SOCK_DGRAM, 0);
#ifdef __linux__
strcpy(ifr.ifr_name, ifa->ifa_name);
ioctl(fd, SIOCGIFHWADDR, &ifr);
close(fd);
if ((ARPHRD_ETHER == ifr.ifr_hwaddr.sa_family) ||
(ARPHRD_IEEE80211 == ifr.ifr_hwaddr.sa_family))
memcpy(hwaddr[num++].hwaddr, ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
#else
struct ifmediareq ifmed;
memset(&ifmed, 0, sizeof(struct ifmediareq));
strcpy(ifmed.ifm_name, ifa->ifa_name);
ioctl(fd, SIOCGIFMEDIA, (caddr_t)&ifmed);
close(fd);
if ((IFM_ETHER == IFM_TYPE(ifmed.ifm_active)) ||
(IFM_IEEE80211 == IFM_TYPE(ifmed.ifm_active))) {
struct sockaddr_dl *sdl = (struct sockaddr_dl *)ifa->ifa_addr;
if (ETHER_ADDR_LEN == sdl->sdl_alen)
memcpy(hwaddr[num++].hwaddr, LLADDR(sdl), sdl->sdl_alen);
}
#endif
}
}
freeifaddrs(ifaddr);
return num;
}
#endif
int nio_resolvehost(niosockaddr_t *addr_list, int count, int af,
const char *hostname, unsigned short port) {
int retval = 0;
if (hostname) {
/* IP Address Resolve Host */
struct addrinfo hints;
struct addrinfo *servinfo = NULL;
char port_str[8] = {0};
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
sprintf(port_str, "%d", port);
if (0 == getaddrinfo(hostname, port_str, &hints, &servinfo)) {
struct addrinfo *aip;
for (aip = servinfo; (NULL != aip) && (retval < count);
aip = aip->ai_next) {
if ((AF_INET == af) && (AF_INET == aip->ai_family)) {
struct sockaddr_in *ipv4 = (struct sockaddr_in *)aip->ai_addr;
ipv4->sin_port = htons(port);
memcpy(&addr_list[retval++].saddr, ipv4, sizeof(struct sockaddr_in));
}
if ((AF_INET6 == af) && (AF_INET6 == aip->ai_family)) {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)aip->ai_addr;
ipv6->sin6_port = htons(port);
memcpy(&addr_list[retval++].saddr, ipv6, sizeof(struct sockaddr_in6));
}
}
freeaddrinfo(servinfo);
}
} else {
if (AF_INET == af) {
/* IP Address Any IPv4 */
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
memcpy(&addr_list[retval++].saddr, &addr, sizeof(struct sockaddr_in));
}
if (AF_INET6 == af) {
/* IP Address Any IPv6 */
struct sockaddr_in6 addr;
memset(&addr, 0, sizeof(addr));
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(port);
addr.sin6_addr = in6addr_any;
memcpy(&addr_list[retval++].saddr, &addr, sizeof(struct sockaddr_in6));
}
}
return retval;
}
int nio_hostaddr(niosockaddr_t *addr, const char *hostname,
unsigned short port) {
if (nio_resolvehost(addr, 1, AF_INET, hostname, port) > 0)
return 0;
if (nio_resolvehost(addr, 1, AF_INET6, hostname, port) > 0)
return 0;
return -1;
}
/* addr is in_addr or in6_addr */
static const char *nio_inetntop(int af, const void *addr, char *strbuf,
int strbuf_size) {
#ifndef _WIN32
return inet_ntop(af, addr, strbuf, strbuf_size);
#else
struct sockaddr_storage ss;
unsigned long s = strbuf_size;
wchar_t wch_addr[INET6_ADDRSTRLEN + 1] = {0};
ZeroMemory(&ss, sizeof(ss));
ss.ss_family = af;
switch (af) {
case AF_INET:
((struct sockaddr_in *)&ss)->sin_addr = *(struct in_addr *)addr;
break;
case AF_INET6:
((struct sockaddr_in6 *)&ss)->sin6_addr = *(struct in6_addr *)addr;
break;
default:
return NULL;
}
/* cannot direclty use &size because of strict aliasing rules */
if (0 != WSAAddressToStringW((struct sockaddr *)&ss, sizeof(ss), NULL,
wch_addr, &s))
return NULL;
WideCharToMultiByte(CP_UTF8, 0, wch_addr, -1, strbuf, s, NULL, NULL);
return strbuf;
#endif /* _WIN32 */
}
static int in6_equal(const struct in6_addr *a, const struct in6_addr *b) {
return 0 == memcmp(a, b, sizeof(*a));
}
int nio_sockaddrequal(const niosockaddr_t *a, const niosockaddr_t *b) {
if (a->saddr.ss_family != b->saddr.ss_family)
return 0;
switch (a->saddr.ss_family) {
case AF_INET: {
struct sockaddr_in *a4 = (struct sockaddr_in *)&a->saddr;
struct sockaddr_in *b4 = (struct sockaddr_in *)&b->saddr;
return a4->sin_addr.s_addr == b4->sin_addr.s_addr &&
a4->sin_port == b4->sin_port;
}
case AF_INET6: {
struct sockaddr_in6 *a6 = (struct sockaddr_in6 *)&a->saddr;
struct sockaddr_in6 *b6 = (struct sockaddr_in6 *)&b->saddr;
return (in6_equal(&a6->sin6_addr, &b6->sin6_addr) &&
a6->sin6_port == b6->sin6_port);
}
default:
return 0;
}
return 0;
}
#if 0
static int nio_inetpton(int af, const char *strbuf, void *addr) {
#ifndef _WIN32
return inet_pton(af, strbuf, addr);
#else
struct sockaddr_storage ss;
int size = sizeof(ss);
wchar_t src_copy[INET6_ADDRSTRLEN + 1] = { 0 };
ZeroMemory(&ss, sizeof(ss));
MultiByteToWideChar(CP_UTF8, 0, strbuf, -1, src_copy, INET6_ADDRSTRLEN + 1);
if (0 ==
WSAStringToAddressW(src_copy, af, NULL, (struct sockaddr *)&ss, &size)) {
switch (af) {
case AF_INET:
*(struct in_addr *)addr = ((struct sockaddr_in *)&ss)->sin_addr;
return 1;
case AF_INET6:
*(struct in6_addr *)addr = ((struct sockaddr_in6 *)&ss)->sin6_addr;
return 1;
default:
return -1;
}
}
return 0;
#endif /* _WIN32 */
}
#endif
int nio_ipstr(nioipstr_t *ipstr, const niosockaddr_t *addr) {
if (AF_INET == addr->saddr.ss_family) {
struct sockaddr_in *ss = (struct sockaddr_in *)(&addr->saddr);
nio_inetntop(AF_INET, &ss->sin_addr, ipstr->addr, sizeof(ipstr->addr));
ipstr->port = ntohs(ss->sin_port);
} else if (AF_INET6 == addr->saddr.ss_family) {
struct sockaddr_in6 *ss = (struct sockaddr_in6 *)(&addr->saddr);
nio_inetntop(AF_INET6, &ss->sin6_addr, ipstr->addr, sizeof(ipstr->addr));
ipstr->port = ntohs(ss->sin6_port);
} else
return -1;
return 0;
}
static unsigned int ipv4_submask(unsigned int prefixlen) {
return htonl(~((1 << (32 - prefixlen)) - 1));
}
int nio_isnat(const niosockaddr_t *addr) {
struct sockaddr_in *ss_addr = (struct sockaddr_in *)(&addr->saddr);
/* Class A: 10.0.0.0 ~ 10.255.255.255 */
if (htonl(0x0A000000) == (ss_addr->sin_addr.s_addr & ipv4_submask(8)))
return 1;
/* Class B: 172.16.0.0 ~ 172.31.255.255 */
if (htonl(0xAC100000) == (ss_addr->sin_addr.s_addr & ipv4_submask(12)))
return 1;
/* Class C: 192.168.0.0 ~ 192.168.255.255 */
if (htonl(0xC0A80000) == (ss_addr->sin_addr.s_addr & ipv4_submask(16)))
return 1;
/* Invalid Address: 169.254.0.0 ~ 169.254.255.255 */
if (htonl(0xA9FE0000) == (ss_addr->sin_addr.s_addr & ipv4_submask(16)))
return 1;
return 0;
}
static int ipv4_masklen(struct sockaddr_in *s) {
int len = 0;
unsigned char *pnt = (unsigned char *)&s->sin_addr;
unsigned char *end = pnt + 4;
while ((pnt < end) && (0xff == (*pnt))) {
len += 8;
pnt++;
}
if (pnt < end) {
unsigned char val = *pnt;
while (val) {
len += 1;
val <<= 1;
}
}
return len;
}
static int ipv6_masklen(struct sockaddr_in6 *s) {
int len = 0;
unsigned char *pnt = (unsigned char *)&s->sin6_addr;
while ((0xff == (*pnt)) && (len < 128)) {
len += 8;
pnt++;
}
if (len < 128) {
unsigned char val = *pnt;
while (val) {
len += 1;
val <<= 1;
}
}
return len;
}
int nio_ipmasklen(const niosockaddr_t *addr) {
return (AF_INET == addr->saddr.ss_family)
? ipv4_masklen((struct sockaddr_in *)(&addr->saddr))
: ipv6_masklen((struct sockaddr_in6 *)(&addr->saddr));
}
int nio_inprogress(void) {
int errcode = socket_errno();
return SOCKERR_EAGAIN == errcode || SOCKERR_EINPROGRESS == errcode;
}
static int nio_createsocket(niosocket_t *s, int af, int type, int protocol) {
if (!s)
return -1;
#ifndef _WIN32
s->sockfd = socket(af, type, protocol);
#else
s->sockfd = (int)WSASocket(af, type, protocol, NULL, 0, 0);
#endif
return (INVALID_SOCKET != s->sockfd) ? 0 : -1;
}
int nio_createtcp(niosocket_t *s, int af) {
if (AF_INET == af)
return nio_createtcp4(s);
if (AF_INET6 == af)
return nio_createtcp6(s);
return -1;
}
int nio_createtcp4(niosocket_t *s) {
return nio_createsocket(s, AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
int nio_createtcp6(niosocket_t *s) {
return nio_createsocket(s, AF_INET6, SOCK_STREAM, IPPROTO_TCP);
}
int nio_createudp(niosocket_t *s, int af) {
if (AF_INET == af)
return nio_createudp4(s);
if (AF_INET6 == af)
return nio_createudp6(s);
return -1;
}
int nio_createudp4(niosocket_t *s) {
return nio_createsocket(s, AF_INET, SOCK_DGRAM, IPPROTO_IP);
}
int nio_createudp6(niosocket_t *s) {
return nio_createsocket(s, AF_INET6, SOCK_DGRAM, IPPROTO_IP);
}
void nio_initsocket(niosocket_t *s) { s->sockfd = INVALID_SOCKET; }
void nio_closesocket(niosocket_t *s) {
#ifndef _WIN32
close(s->sockfd);
#else
closesocket(s->sockfd);
#endif
}
void nio_destroysocket(niosocket_t *s) {
if (!s || INVALID_SOCKET == s->sockfd)
return;
nio_closesocket(s);
s->sockfd = INVALID_SOCKET;
}
#define sockaddr_len(a) \
((NULL == (a)) ? 0 \
: (AF_INET == (a)->ss_family) ? sizeof(struct sockaddr_in) \
: (AF_INET6 == (a)->ss_family) ? sizeof(struct sockaddr_in6) \
: 0)
int nio_bind(niosocket_t *s, const niosockaddr_t *addr) {
return bind(s->sockfd, (struct sockaddr *)(&addr->saddr),
sockaddr_len(&addr->saddr));
}
int nio_listen(niosocket_t *s, int backlog) {
return listen(s->sockfd, backlog);
}
int nio_connect(niosocket_t *s, const niosockaddr_t *addr) {
#ifndef _WIN32
return connect(s->sockfd, (struct sockaddr *)(&addr->saddr),
sockaddr_len(&addr->saddr));
#else
return WSAConnect(s->sockfd, (struct sockaddr *)(&addr->saddr),
sockaddr_len(&addr->saddr), NULL, NULL, NULL, NULL);
#endif
}
int nio_accept(niosocket_t *s, niosocket_t *client, niosockaddr_t *addr) {
struct sockaddr_storage c_addr;
socklen_t ca_len = sizeof(c_addr);
#ifndef _WIN32
client->sockfd = accept(s->sockfd, (struct sockaddr *)&c_addr, &ca_len);
#else
client->sockfd =
(int)WSAAccept(s->sockfd, (struct sockaddr *)&c_addr, &ca_len, NULL, 0);
#endif
if (addr)
memcpy(&addr->saddr, &c_addr, sizeof(c_addr));
return (INVALID_SOCKET != client->sockfd) ? 0 : -1;
}
int nio_shutdown(niosocket_t *s, int how) { return shutdown(s->sockfd, how); }
int nio_peeraddr(niosocket_t *s, niosockaddr_t *addr) {
if (addr) {
socklen_t size = sizeof(struct sockaddr_storage);
return getpeername(s->sockfd, (struct sockaddr *)(&addr->saddr), &size);
}
return -1;
}
int nio_peeripstr(niosocket_t *s, nioipstr_t *addr) {
niosockaddr_t taddr;
if (nio_peeraddr(s, &taddr) < 0)
return -1;
return nio_ipstr(addr, &taddr);
}
int nio_sockaddr(niosocket_t *s, niosockaddr_t *addr) {
if (addr) {
socklen_t size = sizeof(struct sockaddr_storage);
return getsockname(s->sockfd, (struct sockaddr *)(&addr->saddr), &size);
}
return -1;
}
int nio_sockipstr(niosocket_t *s, nioipstr_t *addr) {
niosockaddr_t taddr;
if (nio_sockaddr(s, &taddr) < 0)
return -1;
return nio_ipstr(addr, &taddr);
}
int nio_socketnonblock(niosocket_t *s, int on) {
#ifdef O_NONBLOCK
int flags = fcntl(s->sockfd, F_GETFL, 0);
if (on) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
return 0 == fcntl(s->sockfd, F_SETFL, flags) ? 0 : -1;
#else
unsigned long mode = (unsigned long)on;
return 0 == nio_ioctlsocket(s->sockfd, FIONBIO, &mode) ? 0 : -1;
#endif
}
int nio_reuseaddr(niosocket_t *s, int on) {
setsockopt(s->sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on));
return 0;
}
int nio_tcpnodelay(niosocket_t *s, int on) {
setsockopt(s->sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&on, sizeof(on));
return 0;
}
int nio_tcpkeepalive(niosocket_t *s, int on) {
setsockopt(s->sockfd, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof(on));
return 0;
}
int nio_tcpkeepvalues(niosocket_t *s, int idle, int interval, int count) {
#ifdef _WIN32
DWORD dw = 0;
struct tcp_keepalive kl, ko;
kl.onoff = 1;
kl.keepalivetime = idle * 1000;
kl.keepaliveinterval = interval * 1000;
WSAIoctl(s->sockfd, SIO_KEEPALIVE_VALS, &kl, sizeof(kl), &ko, sizeof(ko), &dw,
NULL, NULL);
#else
setsockopt(s->sockfd, IPPROTO_TCP, TCP_KEEPIDLE, (char *)&idle, sizeof(idle));
setsockopt(s->sockfd, IPPROTO_TCP, TCP_KEEPINTVL, (char *)&interval,
sizeof(interval));
setsockopt(s->sockfd, IPPROTO_TCP, TCP_KEEPCNT, (char *)&count,
sizeof(count));
#endif
return 0;
}
int nio_udpbroadcast(niosocket_t *s, int on) {
setsockopt(s->sockfd, SOL_SOCKET, SO_BROADCAST, (char *)&on, sizeof(on));
return 0;
}
int nio_socketreadable(niosocket_t *s, unsigned int timedout) {
struct timeval tv = {0, 0};
fd_set fds, fd_error;
int retval;
FD_ZERO(&fds);
FD_ZERO(&fd_error);
FD_SET(s->sockfd, &fds);
FD_SET(s->sockfd, &fd_error);
if (timedout > 0) {
tv.tv_sec = (long)(timedout * 0.001);
tv.tv_usec = (long)((timedout % 1000) * 1000);
}
retval = select(s->sockfd + 1, &fds, NULL, &fd_error, &tv);
if (retval < 0)
return -1;
if (retval > 0) {
if (FD_ISSET(s->sockfd, &fd_error))
return -1;
if (FD_ISSET(s->sockfd, &fds))
return 1;
}
return 0;
}
int nio_socketwritable(niosocket_t *s, unsigned int timedout) {
struct timeval tv = {0, 0};
fd_set fds, fd_error;
int retval;
FD_ZERO(&fds);
FD_ZERO(&fd_error);
FD_SET(s->sockfd, &fds);
FD_SET(s->sockfd, &fd_error);
if (timedout > 0) {
tv.tv_sec = (long)(timedout * 0.001);
tv.tv_usec = (long)((timedout % 1000) * 1000);
}
retval = select(s->sockfd + 1, NULL, &fds, &fd_error, &tv);
if (retval < 0)
return -1;
if (retval > 0) {
if (FD_ISSET(s->sockfd, &fd_error))
return -1;
if (FD_ISSET(s->sockfd, &fds))
return 1;
}
return 0;
}
int nio_send(niosocket_t *s, const void *buffer, int len) {
#ifndef _WIN32
return send(s->sockfd, (const char *)buffer, len, 0);
#else
DWORD num = 0;
WSABUF wsa_buf = {(ULONG)len, (CHAR *)buffer};
if (SOCKET_ERROR == WSASend(s->sockfd, &wsa_buf, 1, &num, 0, NULL, NULL))
return -1;
return num;
#endif
}
int nio_recv(niosocket_t *s, void *buffer, int len) {
#ifndef _WIN32
return recv(s->sockfd, (char *)buffer, len, 0);
#else
DWORD num = 0, flag = 0;
WSABUF wsa_buf = {(ULONG)len, (CHAR *)buffer};
if (SOCKET_ERROR == WSARecv(s->sockfd, &wsa_buf, 1, &num, &flag, NULL, NULL))
return -1;
return (int)num;
#endif
}
int nio_sendto(niosocket_t *s, const niosockaddr_t *addr, const void *buffer,
int len) {
#ifndef _WIN32
return sendto(s->sockfd, (const char *)buffer, len, 0,
(struct sockaddr *)(&addr->saddr), sockaddr_len(&addr->saddr));
#else
DWORD num = 0;
WSABUF wsa_buf = {(ULONG)len, (CHAR *)buffer};
if (SOCKET_ERROR == WSASendTo(s->sockfd, &wsa_buf, 1, &num, 0,
(struct sockaddr *)(&addr->saddr),
sockaddr_len(&addr->saddr), NULL, NULL))
return -1;
return (int)num;
#endif
}
int nio_recvfrom(niosocket_t *s, niosockaddr_t *addr, void *buffer, int len) {
struct sockaddr_storage ss;
socklen_t size = sizeof(ss);
int num = 0;
#ifndef _WIN32
num = recvfrom(s->sockfd, (char *)buffer, len, 0, (struct sockaddr *)&ss,
&size);
#else
DWORD flag = 0, rd_num = 0;
WSABUF wsa_buf = {(ULONG)len, (CHAR *)buffer};
if (SOCKET_ERROR == WSARecvFrom(s->sockfd, &wsa_buf, 1, &rd_num, &flag,
(struct sockaddr *)&ss, &size, NULL, NULL))
return -1;
num = (int)rd_num;
#endif
if (addr)
memcpy(&addr->saddr, &ss, sizeof(ss));
return num;
}
int nio_sendall(niosocket_t *s, const void *buffer, int len) {
unsigned char *lptr = (unsigned char *)buffer;
int sent = 0;
int retval = 0;
while (sent < len) {
retval = nio_send(s, lptr, len - sent);
if (retval >= 0) {
sent += retval;
lptr += retval;
} else {
if (!nio_inprogress())
return -1;
}
if (sent != len)
if (nio_socketwritable(s, UINT_MAX) < 0)
return -1;
}
return sent;
}
int nio_recvall(niosocket_t *s, void *buffer, int len) {
unsigned char *lptr = (unsigned char *)buffer;
int total = 0;
int retval = 0;
while (total < len) {
retval = nio_recv(s, lptr, len - total);
if (retval > 0) {
total += retval;
lptr += retval;
} else {
if (0 == retval)
return total; /* disconnected */
else {
if (!nio_inprogress())
return -1;
}
}
if (total != len)
if (nio_socketreadable(s, UINT_MAX) < 0)
return -1;
}
return total;
}
static void ip4_mreq(struct ip_mreq *mreq4,
const struct sockaddr_storage *ipaddr) {
struct sockaddr_in *ss_addr = (struct sockaddr_in *)ipaddr;
memset(mreq4, 0, sizeof(struct ip_mreq));
mreq4->imr_multiaddr.s_addr = ss_addr->sin_addr.s_addr;
mreq4->imr_interface.s_addr = htonl(INADDR_ANY);
}
static void ip6_mreq(struct ipv6_mreq *mreq6,
const struct sockaddr_storage *ipaddr) {
struct sockaddr_in6 *ss_addr = (struct sockaddr_in6 *)ipaddr;
memset(mreq6, 0, sizeof(struct ipv6_mreq));
memcpy(&mreq6->ipv6mr_multiaddr, &ss_addr->sin6_addr,
sizeof(struct in6_addr));
mreq6->ipv6mr_interface = 0;
}
int nio_addmembership(niosocket_t *s, const niosockaddr_t *multiaddr) {
if (AF_INET == multiaddr->saddr.ss_family) {
struct ip_mreq mreq;
ip4_mreq(&mreq, &multiaddr->saddr);
setsockopt(s->sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq,
sizeof(mreq));
return 0;
}
if (AF_INET6 == multiaddr->saddr.ss_family) {
struct ipv6_mreq mreq;
ip6_mreq(&mreq, &multiaddr->saddr);
setsockopt(s->sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char *)&mreq,
sizeof(mreq));
return 0;
}
return -1;
}
int nio_dropmembership(niosocket_t *s, const niosockaddr_t *multiaddr) {
if (AF_INET == multiaddr->saddr.ss_family) {
struct ip_mreq mreq;
ip4_mreq(&mreq, &multiaddr->saddr);
setsockopt(s->sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&mreq,
sizeof(mreq));
return 0;
}
if (AF_INET6 == multiaddr->saddr.ss_family) {
struct ipv6_mreq mreq;
ip6_mreq(&mreq, &multiaddr->saddr);
setsockopt(s->sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (char *)&mreq,
sizeof(mreq));
return 0;
}
return -1;
}
int nio_multicastloop(niosocket_t *s, const niosockaddr_t *multiaddr, int on) {
if (AF_INET == multiaddr->saddr.ss_family) {
setsockopt(s->sockfd, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&on,
sizeof(on));
return 0;
}
if (AF_INET6 == multiaddr->saddr.ss_family) {
setsockopt(s->sockfd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&on,
sizeof(on));
return 0;
}
return -1;
}
int nio_multicastttl(niosocket_t *s, const niosockaddr_t *multiaddr, int ttl) {
if (AF_INET == multiaddr->saddr.ss_family) {
unsigned char ucttl = (unsigned char)ttl;