-
-
Notifications
You must be signed in to change notification settings - Fork 703
/
socket.d
3641 lines (3177 loc) · 107 KB
/
socket.d
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
// Written in the D programming language
/*
Copyright (C) 2004-2011 Christopher E. Miller
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
socket.d 1.4
Jan 2011
Thanks to Benjamin Herr for his assistance.
*/
/**
* Socket primitives.
* Example: See $(SAMPLESRC listener.d) and $(SAMPLESRC htmlget.d)
* License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
* Authors: Christopher E. Miller, $(HTTP klickverbot.at, David Nadlinger),
* $(HTTP thecybershadow.net, Vladimir Panteleev)
* Source: $(PHOBOSSRC std/socket.d)
*/
module std.socket;
import core.stdc.stdint, core.stdc.stdlib, core.stdc.string, std.conv, std.string;
import core.stdc.config;
import core.time : dur, Duration;
import std.exception;
import std.internal.cstring;
@safe:
version (Windows)
{
pragma (lib, "ws2_32.lib");
pragma (lib, "wsock32.lib");
import core.sys.windows.winbase, std.windows.syserror;
public import core.sys.windows.winsock2;
private alias _ctimeval = core.sys.windows.winsock2.timeval;
private alias _clinger = core.sys.windows.winsock2.linger;
enum socket_t : SOCKET { INVALID_SOCKET }
private const int _SOCKET_ERROR = SOCKET_ERROR;
private int _lasterr() nothrow @nogc
{
return WSAGetLastError();
}
}
else version (Posix)
{
version (linux)
{
enum : int
{
TCP_KEEPIDLE = 4,
TCP_KEEPINTVL = 5
}
}
public import core.sys.posix.netinet.in_;
import core.sys.posix.arpa.inet;
import core.sys.posix.fcntl;
import core.sys.posix.netdb;
import core.sys.posix.netinet.tcp;
import core.sys.posix.sys.select;
import core.sys.posix.sys.socket;
import core.sys.posix.sys.time;
import core.sys.posix.sys.un : sockaddr_un;
import core.sys.posix.unistd;
private alias _ctimeval = core.sys.posix.sys.time.timeval;
private alias _clinger = core.sys.posix.sys.socket.linger;
import core.stdc.errno;
enum socket_t : int32_t { init = -1 }
private const int _SOCKET_ERROR = -1;
private enum : int
{
SD_RECEIVE = SHUT_RD,
SD_SEND = SHUT_WR,
SD_BOTH = SHUT_RDWR
}
private int _lasterr() nothrow @nogc
{
return errno;
}
}
else
{
static assert(0); // No socket support yet.
}
version (unittest)
{
// Print a message on exception instead of failing the unittest.
private void softUnittest(void delegate() @safe test, int line = __LINE__) @trusted
{
import std.stdio : writefln;
try
test();
catch (Throwable e)
{
writefln(" --- std.socket(%d) test fails depending on environment ---", line);
writefln(" (%s)", e);
}
}
}
/// Base exception thrown by `std.socket`.
class SocketException: Exception
{
mixin basicExceptionCtors;
}
version (CRuntime_Glibc) version = GNU_STRERROR;
version (CRuntime_UClibc) version = GNU_STRERROR;
/*
* Needs to be public so that SocketOSException can be thrown outside of
* std.socket (since it uses it as a default argument), but it probably doesn't
* need to actually show up in the docs, since there's not really any public
* need for it outside of being a default argument.
*/
string formatSocketError(int err) @trusted
{
version (Posix)
{
char[80] buf;
const(char)* cs;
version (GNU_STRERROR)
{
cs = strerror_r(err, buf.ptr, buf.length);
}
else
{
auto errs = strerror_r(err, buf.ptr, buf.length);
if (errs == 0)
cs = buf.ptr;
else
return "Socket error " ~ to!string(err);
}
auto len = strlen(cs);
if (cs[len - 1] == '\n')
len--;
if (cs[len - 1] == '\r')
len--;
return cs[0 .. len].idup;
}
else
version (Windows)
{
return sysErrorString(err);
}
else
return "Socket error " ~ to!string(err);
}
/// Retrieve the error message for the most recently encountered network error.
@property string lastSocketError()
{
return formatSocketError(_lasterr());
}
/**
* Socket exceptions representing network errors reported by the operating
* system.
*/
class SocketOSException: SocketException
{
int errorCode; /// Platform-specific error code.
///
this(string msg,
string file = __FILE__,
size_t line = __LINE__,
Throwable next = null,
int err = _lasterr(),
string function(int) @trusted errorFormatter = &formatSocketError)
{
errorCode = err;
if (msg.length)
super(msg ~ ": " ~ errorFormatter(err), file, line, next);
else
super(errorFormatter(err), file, line, next);
}
///
this(string msg,
Throwable next,
string file = __FILE__,
size_t line = __LINE__,
int err = _lasterr(),
string function(int) @trusted errorFormatter = &formatSocketError)
{
this(msg, file, line, next, err, errorFormatter);
}
///
this(string msg,
int err,
string function(int) @trusted errorFormatter = &formatSocketError,
string file = __FILE__,
size_t line = __LINE__,
Throwable next = null)
{
this(msg, file, line, next, err, errorFormatter);
}
}
/// Socket exceptions representing invalid parameters specified by user code.
class SocketParameterException: SocketException
{
mixin basicExceptionCtors;
}
/**
* Socket exceptions representing attempts to use network capabilities not
* available on the current system.
*/
class SocketFeatureException: SocketException
{
mixin basicExceptionCtors;
}
/**
* Returns:
* `true` if the last socket operation failed because the socket
* was in non-blocking mode and the operation would have blocked.
*/
bool wouldHaveBlocked() nothrow @nogc
{
version (Windows)
return _lasterr() == WSAEWOULDBLOCK;
else version (Posix)
return _lasterr() == EAGAIN;
else
static assert(0);
}
private immutable
{
typeof(&getnameinfo) getnameinfoPointer;
typeof(&getaddrinfo) getaddrinfoPointer;
typeof(&freeaddrinfo) freeaddrinfoPointer;
}
shared static this() @system
{
version (Windows)
{
WSADATA wd;
// Winsock will still load if an older version is present.
// The version is just a request.
int val;
val = WSAStartup(0x2020, &wd);
if (val) // Request Winsock 2.2 for IPv6.
throw new SocketOSException("Unable to initialize socket library", val);
// These functions may not be present on older Windows versions.
// See the comment in InternetAddress.toHostNameString() for details.
auto ws2Lib = GetModuleHandleA("ws2_32.dll");
if (ws2Lib)
{
getnameinfoPointer = cast(typeof(getnameinfoPointer))
GetProcAddress(ws2Lib, "getnameinfo");
getaddrinfoPointer = cast(typeof(getaddrinfoPointer))
GetProcAddress(ws2Lib, "getaddrinfo");
freeaddrinfoPointer = cast(typeof(freeaddrinfoPointer))
GetProcAddress(ws2Lib, "freeaddrinfo");
}
}
else version (Posix)
{
getnameinfoPointer = &getnameinfo;
getaddrinfoPointer = &getaddrinfo;
freeaddrinfoPointer = &freeaddrinfo;
}
}
shared static ~this() @system nothrow @nogc
{
version (Windows)
{
WSACleanup();
}
}
/**
* The communication domain used to resolve an address.
*/
enum AddressFamily: int
{
UNSPEC = AF_UNSPEC, /// Unspecified address family
UNIX = AF_UNIX, /// Local communication
INET = AF_INET, /// Internet Protocol version 4
IPX = AF_IPX, /// Novell IPX
APPLETALK = AF_APPLETALK, /// AppleTalk
INET6 = AF_INET6, /// Internet Protocol version 6
}
/**
* Communication semantics
*/
enum SocketType: int
{
STREAM = SOCK_STREAM, /// Sequenced, reliable, two-way communication-based byte streams
DGRAM = SOCK_DGRAM, /// Connectionless, unreliable datagrams with a fixed maximum length; data may be lost or arrive out of order
RAW = SOCK_RAW, /// Raw protocol access
RDM = SOCK_RDM, /// Reliably-delivered message datagrams
SEQPACKET = SOCK_SEQPACKET, /// Sequenced, reliable, two-way connection-based datagrams with a fixed maximum length
}
/**
* Protocol
*/
enum ProtocolType: int
{
IP = IPPROTO_IP, /// Internet Protocol version 4
ICMP = IPPROTO_ICMP, /// Internet Control Message Protocol
IGMP = IPPROTO_IGMP, /// Internet Group Management Protocol
GGP = IPPROTO_GGP, /// Gateway to Gateway Protocol
TCP = IPPROTO_TCP, /// Transmission Control Protocol
PUP = IPPROTO_PUP, /// PARC Universal Packet Protocol
UDP = IPPROTO_UDP, /// User Datagram Protocol
IDP = IPPROTO_IDP, /// Xerox NS protocol
RAW = IPPROTO_RAW, /// Raw IP packets
IPV6 = IPPROTO_IPV6, /// Internet Protocol version 6
}
/**
* `Protocol` is a class for retrieving protocol information.
*
* Example:
* ---
* auto proto = new Protocol;
* writeln("About protocol TCP:");
* if (proto.getProtocolByType(ProtocolType.TCP))
* {
* writefln(" Name: %s", proto.name);
* foreach (string s; proto.aliases)
* writefln(" Alias: %s", s);
* }
* else
* writeln(" No information found");
* ---
*/
class Protocol
{
/// These members are populated when one of the following functions are called successfully:
ProtocolType type;
string name; /// ditto
string[] aliases; /// ditto
void populate(protoent* proto) @system pure nothrow
{
type = cast(ProtocolType) proto.p_proto;
name = to!string(proto.p_name);
int i;
for (i = 0;; i++)
{
if (!proto.p_aliases[i])
break;
}
if (i)
{
aliases = new string[i];
for (i = 0; i != aliases.length; i++)
{
aliases[i] =
to!string(proto.p_aliases[i]);
}
}
else
{
aliases = null;
}
}
/** Returns: false on failure */
bool getProtocolByName(scope const(char)[] name) @trusted nothrow
{
protoent* proto;
proto = getprotobyname(name.tempCString());
if (!proto)
return false;
populate(proto);
return true;
}
/** Returns: false on failure */
// Same as getprotobynumber().
bool getProtocolByType(ProtocolType type) @trusted nothrow
{
protoent* proto;
proto = getprotobynumber(type);
if (!proto)
return false;
populate(proto);
return true;
}
}
// Skip this test on Android because getprotobyname/number are
// unimplemented in bionic.
version (CRuntime_Bionic) {} else
@safe unittest
{
// import std.stdio : writefln;
softUnittest({
Protocol proto = new Protocol;
assert(proto.getProtocolByType(ProtocolType.TCP));
//writeln("About protocol TCP:");
//writefln("\tName: %s", proto.name);
// foreach (string s; proto.aliases)
// {
// writefln("\tAlias: %s", s);
// }
assert(proto.name == "tcp");
assert(proto.aliases.length == 1 && proto.aliases[0] == "TCP");
});
}
/**
* `Service` is a class for retrieving service information.
*
* Example:
* ---
* auto serv = new Service;
* writeln("About service epmap:");
* if (serv.getServiceByName("epmap", "tcp"))
* {
* writefln(" Service: %s", serv.name);
* writefln(" Port: %d", serv.port);
* writefln(" Protocol: %s", serv.protocolName);
* foreach (string s; serv.aliases)
* writefln(" Alias: %s", s);
* }
* else
* writefln(" No service for epmap.");
* ---
*/
class Service
{
/// These members are populated when one of the following functions are called successfully:
string name;
string[] aliases; /// ditto
ushort port; /// ditto
string protocolName; /// ditto
void populate(servent* serv) @system pure nothrow
{
name = to!string(serv.s_name);
port = ntohs(cast(ushort) serv.s_port);
protocolName = to!string(serv.s_proto);
int i;
for (i = 0;; i++)
{
if (!serv.s_aliases[i])
break;
}
if (i)
{
aliases = new string[i];
for (i = 0; i != aliases.length; i++)
{
aliases[i] =
to!string(serv.s_aliases[i]);
}
}
else
{
aliases = null;
}
}
/**
* If a protocol name is omitted, any protocol will be matched.
* Returns: false on failure.
*/
bool getServiceByName(scope const(char)[] name, scope const(char)[] protocolName = null) @trusted nothrow
{
servent* serv;
serv = getservbyname(name.tempCString(), protocolName.tempCString());
if (!serv)
return false;
populate(serv);
return true;
}
/// ditto
bool getServiceByPort(ushort port, scope const(char)[] protocolName = null) @trusted nothrow
{
servent* serv;
serv = getservbyport(port, protocolName.tempCString());
if (!serv)
return false;
populate(serv);
return true;
}
}
@safe unittest
{
import std.stdio : writefln;
softUnittest({
Service serv = new Service;
if (serv.getServiceByName("epmap", "tcp"))
{
// writefln("About service epmap:");
// writefln("\tService: %s", serv.name);
// writefln("\tPort: %d", serv.port);
// writefln("\tProtocol: %s", serv.protocolName);
// foreach (string s; serv.aliases)
// {
// writefln("\tAlias: %s", s);
// }
// For reasons unknown this is loc-srv on Wine and epmap on Windows
assert(serv.name == "loc-srv" || serv.name == "epmap", serv.name);
assert(serv.port == 135);
assert(serv.protocolName == "tcp");
}
else
{
writefln("No service for epmap.");
}
});
}
private mixin template socketOSExceptionCtors()
{
///
this(string msg, string file = __FILE__, size_t line = __LINE__,
Throwable next = null, int err = _lasterr())
{
super(msg, file, line, next, err);
}
///
this(string msg, Throwable next, string file = __FILE__,
size_t line = __LINE__, int err = _lasterr())
{
super(msg, next, file, line, err);
}
///
this(string msg, int err, string file = __FILE__, size_t line = __LINE__,
Throwable next = null)
{
super(msg, next, file, line, err);
}
}
/**
* Class for exceptions thrown from an `InternetHost`.
*/
class HostException: SocketOSException
{
mixin socketOSExceptionCtors;
}
/**
* `InternetHost` is a class for resolving IPv4 addresses.
*
* Consider using `getAddress`, `parseAddress` and `Address` methods
* instead of using this class directly.
*/
class InternetHost
{
/// These members are populated when one of the following functions are called successfully:
string name;
string[] aliases; /// ditto
uint[] addrList; /// ditto
void validHostent(in hostent* he)
{
if (he.h_addrtype != cast(int) AddressFamily.INET || he.h_length != 4)
throw new HostException("Address family mismatch");
}
void populate(hostent* he) @system pure nothrow
{
int i;
char* p;
name = to!string(he.h_name);
for (i = 0;; i++)
{
p = he.h_aliases[i];
if (!p)
break;
}
if (i)
{
aliases = new string[i];
for (i = 0; i != aliases.length; i++)
{
aliases[i] =
to!string(he.h_aliases[i]);
}
}
else
{
aliases = null;
}
for (i = 0;; i++)
{
p = he.h_addr_list[i];
if (!p)
break;
}
if (i)
{
addrList = new uint[i];
for (i = 0; i != addrList.length; i++)
{
addrList[i] = ntohl(*(cast(uint*) he.h_addr_list[i]));
}
}
else
{
addrList = null;
}
}
private bool getHostNoSync(string opMixin, T)(T param) @system
{
mixin(opMixin);
if (!he)
return false;
validHostent(he);
populate(he);
return true;
}
version (Windows)
alias getHost = getHostNoSync;
else
{
// posix systems use global state for return value, so we
// must synchronize across all threads
private bool getHost(string opMixin, T)(T param) @system
{
synchronized(this.classinfo)
return getHostNoSync!(opMixin, T)(param);
}
}
/**
* Resolve host name.
* Returns: false if unable to resolve.
*/
bool getHostByName(scope const(char)[] name) @trusted
{
static if (is(typeof(gethostbyname_r)))
{
return getHostNoSync!q{
hostent he_v;
hostent* he;
ubyte[256] buffer_v = void;
auto buffer = buffer_v[];
auto param_zTmp = param.tempCString();
while (true)
{
he = &he_v;
int errno;
if (gethostbyname_r(param_zTmp, he, buffer.ptr, buffer.length, &he, &errno) == ERANGE)
buffer.length = buffer.length * 2;
else
break;
}
}(name);
}
else
{
return getHost!q{
auto he = gethostbyname(param.tempCString());
}(name);
}
}
/**
* Resolve IPv4 address number.
*
* Params:
* addr = The IPv4 address to resolve, in host byte order.
* Returns:
* false if unable to resolve.
*/
bool getHostByAddr(uint addr) @trusted
{
return getHost!q{
auto x = htonl(param);
auto he = gethostbyaddr(&x, 4, cast(int) AddressFamily.INET);
}(addr);
}
/**
* Same as previous, but addr is an IPv4 address string in the
* dotted-decimal form $(I a.b.c.d).
* Returns: false if unable to resolve.
*/
bool getHostByAddr(scope const(char)[] addr) @trusted
{
return getHost!q{
auto x = inet_addr(param.tempCString());
enforce(x != INADDR_NONE,
new SocketParameterException("Invalid IPv4 address"));
auto he = gethostbyaddr(&x, 4, cast(int) AddressFamily.INET);
}(addr);
}
}
///
@safe unittest
{
InternetHost ih = new InternetHost;
ih.getHostByAddr(0x7F_00_00_01);
assert(ih.addrList[0] == 0x7F_00_00_01);
ih.getHostByAddr("127.0.0.1");
assert(ih.addrList[0] == 0x7F_00_00_01);
if (!ih.getHostByName("www.digitalmars.com"))
return; // don't fail if not connected to internet
assert(ih.addrList.length);
InternetAddress ia = new InternetAddress(ih.addrList[0], InternetAddress.PORT_ANY);
assert(ih.name == "www.digitalmars.com" || ih.name == "digitalmars.com",
ih.name);
assert(ih.getHostByAddr(ih.addrList[0]));
string getHostNameFromInt = ih.name.dup;
assert(ih.getHostByAddr(ia.toAddrString()));
string getHostNameFromStr = ih.name.dup;
assert(getHostNameFromInt == getHostNameFromStr);
}
/// Holds information about a socket _address retrieved by `getAddressInfo`.
struct AddressInfo
{
AddressFamily family; /// Address _family
SocketType type; /// Socket _type
ProtocolType protocol; /// Protocol
Address address; /// Socket _address
string canonicalName; /// Canonical name, when `AddressInfoFlags.CANONNAME` is used.
}
/**
* A subset of flags supported on all platforms with getaddrinfo.
* Specifies option flags for `getAddressInfo`.
*/
enum AddressInfoFlags: int
{
/// The resulting addresses will be used in a call to `Socket.bind`.
PASSIVE = AI_PASSIVE,
/// The canonical name is returned in `canonicalName` member in the first `AddressInfo`.
CANONNAME = AI_CANONNAME,
/**
* The `node` parameter passed to `getAddressInfo` must be a numeric string.
* This will suppress any potentially lengthy network host address lookups.
*/
NUMERICHOST = AI_NUMERICHOST,
}
/**
* On POSIX, getaddrinfo uses its own error codes, and thus has its own
* formatting function.
*/
private string formatGaiError(int err) @trusted
{
version (Windows)
{
return sysErrorString(err);
}
else
{
synchronized
return to!string(gai_strerror(err));
}
}
/**
* Provides _protocol-independent translation from host names to socket
* addresses. If advanced functionality is not required, consider using
* `getAddress` for compatibility with older systems.
*
* Returns: Array with one `AddressInfo` per socket address.
*
* Throws: `SocketOSException` on failure, or `SocketFeatureException`
* if this functionality is not available on the current system.
*
* Params:
* node = string containing host name or numeric address
* options = optional additional parameters, identified by type:
* $(UL $(LI `string` - service name or port number)
* $(LI `AddressInfoFlags` - option flags)
* $(LI `AddressFamily` - address family to filter by)
* $(LI `SocketType` - socket type to filter by)
* $(LI `ProtocolType` - protocol to filter by))
*
* Example:
* ---
* // Roundtrip DNS resolution
* auto results = getAddressInfo("www.digitalmars.com");
* assert(results[0].address.toHostNameString() ==
* "digitalmars.com");
*
* // Canonical name
* results = getAddressInfo("www.digitalmars.com",
* AddressInfoFlags.CANONNAME);
* assert(results[0].canonicalName == "digitalmars.com");
*
* // IPv6 resolution
* results = getAddressInfo("ipv6.google.com");
* assert(results[0].family == AddressFamily.INET6);
*
* // Multihomed resolution
* results = getAddressInfo("google.com");
* assert(results.length > 1);
*
* // Parsing IPv4
* results = getAddressInfo("127.0.0.1",
* AddressInfoFlags.NUMERICHOST);
* assert(results.length && results[0].family ==
* AddressFamily.INET);
*
* // Parsing IPv6
* results = getAddressInfo("::1",
* AddressInfoFlags.NUMERICHOST);
* assert(results.length && results[0].family ==
* AddressFamily.INET6);
* ---
*/
AddressInfo[] getAddressInfo(T...)(scope const(char)[] node, scope T options)
{
const(char)[] service = null;
addrinfo hints;
hints.ai_family = AF_UNSPEC;
foreach (i, option; options)
{
static if (is(typeof(option) : const(char)[]))
service = options[i];
else
static if (is(typeof(option) == AddressInfoFlags))
hints.ai_flags |= option;
else
static if (is(typeof(option) == AddressFamily))
hints.ai_family = option;
else
static if (is(typeof(option) == SocketType))
hints.ai_socktype = option;
else
static if (is(typeof(option) == ProtocolType))
hints.ai_protocol = option;
else
static assert(0, "Unknown getAddressInfo option type: " ~ typeof(option).stringof);
}
return () @trusted { return getAddressInfoImpl(node, service, &hints); }();
}
@system unittest
{
struct Oops
{
const(char[]) breakSafety()
{
*cast(int*) 0xcafebabe = 0xdeadbeef;
return null;
}
alias breakSafety this;
}
assert(!__traits(compiles, () {
getAddressInfo("", Oops.init);
}), "getAddressInfo breaks @safe");
}
private AddressInfo[] getAddressInfoImpl(scope const(char)[] node, scope const(char)[] service, addrinfo* hints) @system
{
import std.array : appender;
if (getaddrinfoPointer && freeaddrinfoPointer)
{
addrinfo* ai_res;
int ret = getaddrinfoPointer(
node.tempCString(),
service.tempCString(),
hints, &ai_res);
enforce(ret == 0, new SocketOSException("getaddrinfo error", ret, &formatGaiError));
scope(exit) freeaddrinfoPointer(ai_res);
auto result = appender!(AddressInfo[])();
// Use const to force UnknownAddressReference to copy the sockaddr.
for (const(addrinfo)* ai = ai_res; ai; ai = ai.ai_next)
result ~= AddressInfo(
cast(AddressFamily) ai.ai_family,
cast(SocketType ) ai.ai_socktype,
cast(ProtocolType ) ai.ai_protocol,
new UnknownAddressReference(ai.ai_addr, cast(socklen_t) ai.ai_addrlen),
ai.ai_canonname ? to!string(ai.ai_canonname) : null);
assert(result.data.length > 0);
return result.data;
}
throw new SocketFeatureException("Address info lookup is not available " ~
"on this system.");
}
@safe unittest
{
softUnittest({
if (getaddrinfoPointer)
{
// Roundtrip DNS resolution
auto results = getAddressInfo("www.digitalmars.com");
assert(results[0].address.toHostNameString() == "digitalmars.com");
// Canonical name
results = getAddressInfo("www.digitalmars.com",
AddressInfoFlags.CANONNAME);
assert(results[0].canonicalName == "digitalmars.com");
// IPv6 resolution
//results = getAddressInfo("ipv6.google.com");
//assert(results[0].family == AddressFamily.INET6);
// Multihomed resolution
//results = getAddressInfo("google.com");
//assert(results.length > 1);