This file is indexed.

/usr/include/d2/4.6/std/socket.d is in libphobos2-4.6-dev 0.29.1-4.6.3-1ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
// Written in the D programming language

/*
        Copyright (C) 2004-2005 Christopher E. Miller

        This software is provided 'as-is', without any express or implied
        warranty.  In no event will the authors be held liable for any damages
        arising from the use of this software.

        Permission is granted to anyone to use this software for any purpose,
        including commercial applications, and to alter it and redistribute it
        freely, subject to the following restrictions:

        1. The origin of this software must not be misrepresented; you must not
           claim that you wrote the original software. If you use this software
           in a product, an acknowledgment in the product documentation would be
           appreciated but is not required.
        2. Altered source versions must be plainly marked as such, and must not
           be misrepresented as being the original software.
        3. This notice may not be removed or altered from any source
           distribution.

        socket.d 1.3
        Jan 2005

        Thanks to Benjamin Herr for his assistance.
 */

/**
 * Notes: For Win32 systems, link with ws2_32.lib.
 * Example: See /dmd/samples/d/listener.d.
 * Authors: Christopher E. Miller, $(WEB klickverbot.at, David Nadlinger)
 * Source:  $(PHOBOSSRC std/_socket.d)
 * Macros:
 *      WIKI=Phobos/StdSocket
 */

module std.socket;

import core.stdc.stdint, std.string, std.c.string, std.c.stdlib, std.conv,
       std.traits;

import core.stdc.config;
import core.time : dur, Duration;
import std.algorithm : max;
import std.exception : assumeUnique, enforce;

version(unittest)
{
    private import std.c.stdio : printf;
}

version(Posix)
{
    version = BsdSockets;
}

version(Win32)
{
    pragma (lib, "ws2_32.lib");
    pragma (lib, "wsock32.lib");

    private import std.c.windows.windows, std.c.windows.winsock;
    private alias std.c.windows.winsock.timeval _ctimeval;

    enum socket_t : SOCKET { INVALID_SOCKET };
    private const int _SOCKET_ERROR = SOCKET_ERROR;


    private int _lasterr()
    {
        return WSAGetLastError();
    }
}
else version(BsdSockets)
{
    version(Posix)
    {
        version(linux)
            import std.c.linux.socket : AF_IPX, AF_APPLETALK, SOCK_RDM,
                   IPPROTO_IGMP, IPPROTO_GGP, IPPROTO_PUP, IPPROTO_IDP,
                   SD_RECEIVE, SD_SEND, SD_BOTH, MSG_NOSIGNAL, INADDR_NONE;
        else version(OSX)
            private import std.c.osx.socket;
        else version(FreeBSD)
        {
            import core.sys.posix.sys.socket;
            import core.sys.posix.sys.select;
            import std.c.freebsd.socket;
            private enum SD_RECEIVE = SHUT_RD;
            private enum SD_SEND    = SHUT_WR;
            private enum SD_BOTH    = SHUT_RDWR;
        }
        else
            static assert(false);

        import core.sys.posix.netdb;
        private import core.sys.posix.fcntl;
        private import core.sys.posix.unistd;
        private import core.sys.posix.arpa.inet;
        private import core.sys.posix.netinet.tcp;
        private import core.sys.posix.netinet.in_;
        private import core.sys.posix.sys.time;
        //private import core.sys.posix.sys.select;
        private import core.sys.posix.sys.socket;
        private alias core.sys.posix.sys.time.timeval _ctimeval;
    }
    private import core.stdc.errno;

    enum socket_t : int32_t { init = -1 }
    private const int _SOCKET_ERROR = -1;


    private int _lasterr()
    {
        return errno;
    }
}
else
{
    static assert(0);     // No socket support yet.
}


/// Base exception thrown from a Socket.
class SocketException: Exception
{
    int errorCode;     /// Platform-specific error code.

    this(string msg, int err = 0)
    {
        errorCode = err;

        version(Posix)
        {
            if(errorCode > 0)
            {
                char[80] buf;
                const(char)* cs;
                version (linux)
                {
                    cs = strerror_r(errorCode, buf.ptr, buf.length);
                }
                else version (OSX)
                {
                    auto errs = strerror_r(errorCode, buf.ptr, buf.length);
                    if (errs == 0)
                        cs = buf.ptr;
                    else
                    {
                        cs = "Unknown error";
                    }
                }
                else version (FreeBSD)
                {
                    auto errs = strerror_r(errorCode, buf.ptr, buf.length);
                    if (errs == 0)
                        cs = buf.ptr;
                    else
                    {
                        cs = "Unknown error";
                    }
                }
                else
                {
                    static assert(0);
                }

                auto len = strlen(cs);

                if(cs[len - 1] == '\n')
                    len--;
                if(cs[len - 1] == '\r')
                    len--;
                msg = cast(string) (msg ~ ": " ~ cs[0 .. len]);
            }
        }

        super(msg);
    }
}


private __gshared typeof(&getnameinfo) getnameinfoPointer;

shared static this()
{
    version(Win32)
    {
        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 SocketException("Unable to initialize socket library", val);

        // See the comment in InternetAddress.toHostNameString() for
        // details on the getnameinfo() issue.
        auto ws2Lib = GetModuleHandleA("ws2_32.dll");
        if (ws2Lib)
        {
            getnameinfoPointer = cast(typeof(getnameinfoPointer))
                                 GetProcAddress(ws2Lib, "getnameinfo");
        }
    }
    else version(Posix)
    {
        getnameinfoPointer = &getnameinfo;
    }
}


shared static ~this()
{
    version(Win32)
    {
        WSACleanup();
    }
}

/**
 * The communication domain used to resolve an address.
 */
enum AddressFamily: int
{
    UNSPEC =     AF_UNSPEC,     ///
    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
    IPV6 =  IPPROTO_IPV6,       /// internet protocol version 6
}


/**
 * Protocol is a class for retrieving protocol information.
 */
class Protocol
{
    ProtocolType type;          /// These members are populated when one of the following functions are called without failure:
    string name;                /// ditto
    string[] aliases;           /// ditto


    void populate(protoent* proto)
    {
        type = cast(ProtocolType)proto.p_proto;
        name = to!string(proto.p_name).idup;

        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]).idup;
            }
        }
        else
        {
            aliases = null;
        }
    }

    /** Returns false on failure */
    bool getProtocolByName(string name)
    {
        protoent* proto;
        proto = getprotobyname(toStringz(name));
        if(!proto)
            return false;
        populate(proto);
        return true;
    }


    /** Returns false on failure */
    // Same as getprotobynumber().
    bool getProtocolByType(ProtocolType type)
    {
        protoent* proto;
        proto = getprotobynumber(type);
        if(!proto)
            return false;
        populate(proto);
        return true;
    }
}


unittest
{
    Protocol proto = new Protocol;
    version (Windows)
    {
        // These fail, don't know why
        pragma(msg, " --- std.socket(" ~ __LINE__.stringof ~ ") broken test ---");
    }
    else
    {
        assert(proto.getProtocolByType(ProtocolType.TCP));
        //printf("About protocol TCP:\n\tName: %.*s\n", proto.name);
        // foreach(string s; proto.aliases)
        // {
        //      printf("\tAlias: %.*s\n", s);
        // }
        assert(proto.name == "tcp");
        assert(proto.aliases.length == 1 && proto.aliases[0] == "TCP");
    }
}


/**
 * Service is a class for retrieving service information.
 */
class Service
{
    /** These members are populated when one of the following functions are called without failure: */
    string name;
    string[] aliases;           /// ditto
    ushort port;                /// ditto
    string protocolName;        /// ditto


    void populate(servent* serv)
    {
        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]).idup;
            }
        }
        else
        {
            aliases = null;
        }
    }

    /**
     * If a protocol name is omitted, any protocol will be matched.
     * Returns: false on failure.
     */
    bool getServiceByName(string name, string protocolName)
    {
        servent* serv;
        serv = getservbyname(toStringz(name), toStringz(protocolName));
        if(!serv)
            return false;
        populate(serv);
        return true;
    }


    // Any protocol name will be matched.
    /// ditto
    bool getServiceByName(string name)
    {
        servent* serv;
        serv = getservbyname(toStringz(name), null);
        if(!serv)
            return false;
        populate(serv);
        return true;
    }


    /// ditto
    bool getServiceByPort(ushort port, string protocolName)
    {
        servent* serv;
        serv = getservbyport(port, toStringz(protocolName));
        if(!serv)
            return false;
        populate(serv);
        return true;
    }


    // Any protocol name will be matched.
    /// ditto
    bool getServiceByPort(ushort port)
    {
        servent* serv;
        serv = getservbyport(port, null);
        if(!serv)
            return false;
        populate(serv);
        return true;
    }
}


unittest
{
    Service serv = new Service;
    if(serv.getServiceByName("epmap", "tcp"))
    {
        // printf("About service epmap:\n\tService: %.*s\n"
        //         "\tPort: %d\n\tProtocol: %.*s\n",
        //         serv.name, serv.port, serv.protocolName);
        // foreach(string s; serv.aliases)
        // {
        //      printf("\tAlias: %.*s\n", 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");
        // This assert used to pass, don't know why it fails now
        //assert(serv.aliases.length == 1 && serv.aliases[0] == "epmap");
    }
    else
    {
        printf("No service for epmap.\n");
    }
}


/**
 * Base exception thrown from an InternetHost.
 */
class HostException: Exception
{
    int errorCode;      /// Platform-specific error code.


    this(string msg, int err = 0)
    {
        errorCode = err;
        super(msg);
    }
}

/**
 * InternetHost is a class for resolving IPv4 addresses.
 */
class InternetHost
{
    /** These members are populated when one of the following functions are called without failure: */
    string name;
    string[] aliases;           /// ditto
    uint32_t[] addrList;        /// ditto


    void validHostent(hostent* he)
    {
        if(he.h_addrtype != cast(int)AddressFamily.INET || he.h_length != 4)
            throw new HostException("Address family mismatch", _lasterr());
    }


    void populate(hostent* he)
    {
        int i;
        char* p;

        name = to!string(he.h_name).idup;

        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]).idup;
            }
        }
        else
        {
            aliases = null;
        }

        for(i = 0;; i++)
        {
            p = he.h_addr_list[i];
            if(!p)
                break;
        }

        if(i)
        {
            addrList = new uint32_t[i];
            for(i = 0; i != addrList.length; i++)
            {
                addrList[i] = ntohl(*(cast(uint32_t*)he.h_addr_list[i]));
            }
        }
        else
        {
            addrList = null;
        }
    }

    /**
     * Resolve host name. Returns false if unable to resolve.
     */
    bool getHostByName(string name)
    {
        version(Windows)
        {
            // TODO gethostbyname is deprecated in windows, use getaddrinfo
            auto he = gethostbyname(toStringz(name));
            if(!he)
                return false;
            validHostent(he);
            populate(he);
        }
        else
        {
            // posix systems use global state for return value, so we
            // must synchronize across all threads
            synchronized(this.classinfo)
            {
                auto he = gethostbyname(toStringz(name));
                if(!he)
                    return false;
                validHostent(he);
                populate(he);
            }
        }
        return true;
    }


    /**
     * Resolve IPv4 address number. Returns false if unable to resolve.
     *
     * Params:
     *   addr = The IPv4 address to resolve, in network byte order.
     */
    bool getHostByAddr(uint addr)
    {
        uint x = htonl(addr);
        version(Windows)
        {
            // TODO gethostbyaddr is deprecated in windows, use getnameinfo
            auto he = gethostbyaddr(&x, 4, cast(int)AddressFamily.INET);
            if(!he)
                return false;
            validHostent(he);
            populate(he);
        }
        else
        {
            // posix systems use global state for return value, so we
            // must synchronize across all threads
            synchronized(this.classinfo)
            {
                auto he = gethostbyaddr(&x, 4, cast(int)AddressFamily.INET);
                if(!he)
                    return false;
                validHostent(he);
                populate(he);
            }
        }
        return true;
    }


    /**
     * 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(string addr)
    {
        uint x = inet_addr(std.string.toStringz(addr));
        version(Windows)
        {
            // TODO gethostbyaddr is deprecated in windows, use getnameinfo
            auto he = gethostbyaddr(&x, 4, cast(int)AddressFamily.INET);
            if(!he)
                return false;
            validHostent(he);
            populate(he);
        }
        else
        {
            // posix systems use global state for return value, so we
            // must synchronize across all threads
            synchronized(this.classinfo)
            {
                auto he = gethostbyaddr(&x, 4, cast(int)AddressFamily.INET);
                if(!he)
                    return false;
                validHostent(he);
                populate(he);
            }
        }
        return true;
    }
}


unittest
{
    try
    {
        InternetHost ih = new InternetHost;
        if (!ih.getHostByName("www.digitalmars.com"))
            return;             // don't fail if not connected to internet
        //printf("addrList.length = %d\n", ih.addrList.length);
        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);
        // printf("IP address = %.*s\nname = %.*s\n", ia.toAddrString(), ih.name);
        // foreach(int i, string s; ih.aliases)
        // {
        //      printf("aliases[%d] = %.*s\n", i, s);
        // }
        // printf("---\n");

        assert(ih.getHostByAddr(ih.addrList[0]));
        // printf("name = %.*s\n", ih.name);
        // foreach(int i, string s; ih.aliases)
        // {
        //      printf("aliases[%d] = %.*s\n", i, s);
        // }
    }
    catch (Throwable e)
    {
        // Test fails or succeeds depending on environment!
        printf(" --- std.socket(%u) broken test ---\n", __LINE__);
        printf(" (%.*s)\n", e.toString());
    }
}


/**
 * Base exception thrown from an Address.
 */
class AddressException: Exception
{
    this(string msg)
    {
        super(msg);
    }
}


/**
 * Address is an abstract class for representing a network addresses.
 */
abstract class Address
{
    protected sockaddr* name();
    protected int nameLen();
    AddressFamily addressFamily();      /// Family of this address.
    override string toString();                 /// Human readable string representing this address.
}

/**
 *
 */
class UnknownAddress: Address
{
protected:
    sockaddr sa;


    override sockaddr* name()
    {
        return &sa;
    }


    override int nameLen()
    {
        return sa.sizeof;
    }


public:
    override AddressFamily addressFamily()
    {
        return cast(AddressFamily)sa.sa_family;
    }


    override string toString()
    {
        return "Unknown";
    }
}


/**
 * InternetAddress is a class that represents an IPv4 (internet protocol version
 * 4) address and port.
 */
class InternetAddress: Address
{
protected:
    sockaddr_in sin;


    override sockaddr* name()
    {
        return cast(sockaddr*)&sin;
    }


    override int nameLen()
    {
        return sin.sizeof;
    }


    this()
    {
    }


public:
    enum uint ADDR_ANY = INADDR_ANY;           /// Any IPv4 address number.
    enum uint ADDR_NONE = INADDR_NONE;         /// An invalid IPv4 address number.
    enum ushort PORT_ANY = 0;                  /// Any IPv4 port number.

    /// Overridden to return AddressFamily.INET.
    override AddressFamily addressFamily()
    {
        return cast(AddressFamily)AddressFamily.INET;
    }

    /// Returns the IPv4 port number.
    ushort port()
    {
        return ntohs(sin.sin_port);
    }

    /// Returns the IPv4 address number.
    uint addr()
    {
        return ntohl(sin.sin_addr.s_addr);
    }

    /**
     * Params:
     *   addr = an IPv4 address string in the dotted-decimal form a.b.c.d,
     *          or a host name that will be resolved using an InternetHost
     *          object.
     *   port = may be PORT_ANY as stated below.
     */
    this(string addr, ushort port)
    {
        uint uiaddr = parse(addr);
        if(ADDR_NONE == uiaddr)
        {
            InternetHost ih = new InternetHost;
            if(!ih.getHostByName(addr))
                //throw new AddressException("Invalid internet address");
                throw new AddressException(
                          "Unable to resolve host '" ~ addr ~ "'");
            uiaddr = ih.addrList[0];
        }
        sin.sin_family = AddressFamily.INET;
        sin.sin_addr.s_addr = htonl(uiaddr);
        sin.sin_port = htons(port);
    }

    /**
     * Construct a new Address. addr may be ADDR_ANY (default) and port may
     * be PORT_ANY, and the actual numbers may not be known until a connection
     * is made.
     */
    this(uint addr, ushort port)
    {
        sin.sin_family = AddressFamily.INET;
        sin.sin_addr.s_addr = htonl(addr);
        sin.sin_port = htons(port);
    }

    /// ditto
    this(ushort port)
    {
        sin.sin_family = AddressFamily.INET;
        sin.sin_addr.s_addr = 0;         //any, "0.0.0.0"
        sin.sin_port = htons(port);
    }

    /// Human readable string representing the IPv4 address in dotted-decimal form.
    string toAddrString()
    {
        return to!string(inet_ntoa(sin.sin_addr)).idup;
    }

    /// Human readable string representing the IPv4 port.
    string toPortString()
    {
        return std.conv.to!string(port());
    }

    /*
     * Returns the host name as a fully qualified domain name, if
     * available, or the IP address in dotted-decimal notation otherwise.
     */
    string toHostNameString()
    {
        // getnameinfo() is the recommended way to perform a reverse (name)
        // lookup on both Posix and Windows. However, it is only available
        // on Windows XP and above, and not included with the WinSock import
        // libraries shipped with DMD. Thus, we check for getnameinfo at
        // runtime in the shared module constructor, and fall back to the
        // deprecated getHostByAddr() if it could not be found. See also:
        // http://technet.microsoft.com/en-us/library/aa450403.aspx
        if (getnameinfoPointer is null)
        {
            auto host = new InternetHost();
            enforce(host.getHostByAddr(sin.sin_addr.s_addr),
                    new SocketException("Could not get host name."));
            return host.name;
        }

        auto buf = new char[NI_MAXHOST];
        auto rc = getnameinfoPointer(cast(sockaddr*)&sin, sin.sizeof,
                                     buf.ptr, cast(uint)buf.length, null, 0, 0);
        enforce(rc == 0, new SocketException(
                    "Could not get host name", _lasterr()));
        return assumeUnique(buf[0 .. strlen(buf.ptr)]);
    }

    /// Human readable string representing the IPv4 address and port in the form $(I a.b.c.d:e).
    override string toString()
    {
        return toAddrString() ~ ":" ~ toPortString();
    }

    /**
     * Parse an IPv4 address string in the dotted-decimal form $(I a.b.c.d)
     * and return the number.
     * If the string is not a legitimate IPv4 address,
     * ADDR_NONE is returned.
     */
    static uint parse(string addr)
    {
        return ntohl(inet_addr(std.string.toStringz(addr)));
    }
}


unittest
{
    try
    {
        InternetAddress ia = new InternetAddress("63.105.9.61", 80);
        assert(ia.toString() == "63.105.9.61:80");
    }
    catch (Throwable e)
    {
        printf(" --- std.socket(%u) broken test ---\n", __LINE__);
        printf(" (%.*s)\n", e.toString());
    }
}


/** */
class SocketAcceptException: SocketException
{
    this(string msg, int err = 0)
    {
        super(msg, err);
    }
}

/// How a socket is shutdown:
enum SocketShutdown: int
{
    RECEIVE =  SD_RECEIVE,      /// socket receives are disallowed
    SEND =     SD_SEND,         /// socket sends are disallowed
    BOTH =     SD_BOTH,         /// both RECEIVE and SEND
}


/// Flags may be OR'ed together:
enum SocketFlags: int
{
    NONE =       0,                 /// no flags specified

    OOB =        MSG_OOB,           /// out-of-band stream data
    PEEK =       MSG_PEEK,          /// peek at incoming data without removing it from the queue, only for receiving
    DONTROUTE =  MSG_DONTROUTE,     /// data should not be subject to routing; this flag may be ignored. Only for sending
}


/// Duration timeout value.
extern(C) struct timeval
{
    // D interface
    c_long seconds;                /// Number of seconds.
    c_long microseconds;           /// Number of additional microseconds.

    // C interface
    deprecated
    {
        alias seconds tv_sec;
        alias microseconds tv_usec;
    }
}


/// A collection of sockets for use with Socket.select.
class SocketSet
{
private:
    uint maxsockets;     /// max desired sockets, the fd_set might be capable of holding more
    fd_set set;


    version(Win32)
    {
        uint count()
        {
            return set.fd_count;
        }
    }
    else version(BsdSockets)
    {
        int maxfd;
        uint count;
    }


public:

    /// Set the maximum amount of sockets that may be added.
    this(uint max)
    {
        maxsockets = max;
        reset();
    }

    /// Uses the default maximum for the system.
    this()
    {
        this(FD_SETSIZE);
    }

    /// Reset the SocketSet so that there are 0 Sockets in the collection.
    void reset()
    {
        FD_ZERO(&set);

        version(BsdSockets)
        {
            maxfd = -1;
            count = 0;
        }
    }


    void add(socket_t s)
    in
    {
        // Make sure too many sockets don't get added.
        assert(count < maxsockets);
    }
    body
    {
        FD_SET(s, &set);

        version(BsdSockets)
        {
            ++count;
            if(s > maxfd)
                maxfd = s;
        }
    }

    /// Add a Socket to the collection. Adding more than the maximum has dangerous side affects.
    void add(Socket s)
    {
        add(s.sock);
    }

    void remove(socket_t s)
    {
        FD_CLR(s, &set);
        version(BsdSockets)
        {
            --count;
            // note: adjusting maxfd would require scanning the set, not worth it
        }
    }


    /// Remove this Socket from the collection.
    void remove(Socket s)
    {
        remove(s.sock);
    }

    int isSet(socket_t s)
    {
        return FD_ISSET(s, &set);
    }


    /// Returns nonzero if this Socket is in the collection.
    int isSet(Socket s)
    {
        return isSet(s.sock);
    }


    /// Return maximum amount of sockets that can be added, like FD_SETSIZE.
    uint max()
    {
        return maxsockets;
    }


    fd_set* toFd_set()
    {
        return &set;
    }


    int selectn()
    {
        version(Win32)
        {
            return count;
        }
        else version(BsdSockets)
        {
            return maxfd + 1;
        }
    }
}


/// The level at which a socket option is defined:
enum SocketOptionLevel: int
{
    SOCKET =  SOL_SOCKET,               /// socket level
    IP =      ProtocolType.IP,          /// internet protocol version 4 level
    ICMP =    ProtocolType.ICMP,        ///
    IGMP =    ProtocolType.IGMP,        ///
    GGP =     ProtocolType.GGP,         ///
    TCP =     ProtocolType.TCP,         /// transmission control protocol level
    PUP =     ProtocolType.PUP,         ///
    UDP =     ProtocolType.UDP,         /// user datagram protocol level
    IDP =     ProtocolType.IDP,         ///
    IPV6 =    ProtocolType.IPV6,        /// internet protocol version 6 level
}

/// Linger information for use with SocketOption.LINGER.
extern(C) struct linger
{
    // D interface
    version(Win32)
    {
        uint16_t on;            /// Nonzero for on.
        uint16_t time;          /// Linger time.
    }
    else version(BsdSockets)
    {
        int32_t on;
        int32_t time;
    }

    // C interface
    deprecated
    {
        alias on l_onoff;
        alias time l_linger;
    }
}


/// Specifies a socket option:
enum SocketOption: int
{
    DEBUG =                SO_DEBUG,            /// record debugging information
    BROADCAST =            SO_BROADCAST,        /// allow transmission of broadcast messages
    REUSEADDR =            SO_REUSEADDR,        /// allow local reuse of address
    LINGER =               SO_LINGER,           /// linger on close if unsent data is present
    OOBINLINE =            SO_OOBINLINE,        /// receive out-of-band data in band
    SNDBUF =               SO_SNDBUF,           /// send buffer size
    RCVBUF =               SO_RCVBUF,           /// receive buffer size
    DONTROUTE =            SO_DONTROUTE,        /// do not route
    SNDTIMEO =             SO_SNDTIMEO,         /// send timeout
    RCVTIMEO =             SO_RCVTIMEO,         /// receive timeout

    // SocketOptionLevel.TCP:
    TCP_NODELAY =          .TCP_NODELAY,        /// disable the Nagle algorithm for send coalescing

    // SocketOptionLevel.IPV6:
    IPV6_UNICAST_HOPS =    .IPV6_UNICAST_HOPS,          ///
    IPV6_MULTICAST_IF =    .IPV6_MULTICAST_IF,          ///
    IPV6_MULTICAST_LOOP =  .IPV6_MULTICAST_LOOP,        ///
    IPV6_JOIN_GROUP =      .IPV6_JOIN_GROUP,            ///
    IPV6_LEAVE_GROUP =     .IPV6_LEAVE_GROUP,           ///
}


/**
 *  Socket is a class that creates a network communication endpoint using the
 * Berkeley sockets interface.
 */
class Socket
{
private:
    socket_t sock;
    AddressFamily _family;

    version(Win32)
        bool _blocking = false;         /// Property to get or set whether the socket is blocking or nonblocking.

    // The WinSock timeouts seem to be effectively skewed by a constant
    // offset of about half a second (value in milliseconds). This has
    // been confirmed on updated (as of Jun 2011) Windows XP, Windows 7
    // and Windows Server 2008 R2 boxes.
    enum WINSOCK_TIMEOUT_SKEW = 500;

    void setSock(socket_t handle)
    {
        assert(handle != socket_t.init);
        sock = handle;

        // Set the option to disable SIGPIPE on send() if the platform
        // has it (e.g. on OS X).
        static if (is(typeof(SO_NOSIGPIPE)))
        {
            setOption(SocketOptionLevel.SOCKET, cast(SocketOption)SO_NOSIGPIPE, true);
        }
    }


    // For use with accepting().
    protected this()
    {
    }


public:

    /**
     * Create a blocking socket. If a single protocol type exists to support
     * this socket type within the address family, the ProtocolType may be
     * omitted.
     */
    this(AddressFamily af, SocketType type, ProtocolType protocol)
    {
        _family = af;
        auto handle = cast(socket_t) socket(af, type, protocol);
        if(handle == socket_t.init)
            throw new SocketException("Unable to create socket", _lasterr());
        setSock(handle);
    }


    // A single protocol exists to support this socket type within the
    // protocol family, so the ProtocolType is assumed.
    /// ditto
    this(AddressFamily af, SocketType type)
    {
        this(af, type, cast(ProtocolType)0);         // Pseudo protocol number.
    }


    /// ditto
    this(AddressFamily af, SocketType type, string protocolName)
    {
        protoent* proto;
        proto = getprotobyname(toStringz(protocolName));
        if(!proto)
            throw new SocketException("Unable to find the protocol", _lasterr());
        this(af, type, cast(ProtocolType)proto.p_proto);
    }


    ~this()
    {
        close();
    }


    /// Get underlying socket handle.
    socket_t handle()
    {
        return sock;
    }

    /**
     * Get/set socket's blocking flag.
     *
     * When a socket is blocking, calls to receive(), accept(), and send()
     * will block and wait for data/action.
     * A non-blocking socket will immediately return instead of blocking.
     */
    bool blocking()
    {
        version(Win32)
        {
            return _blocking;
        }
        else version(BsdSockets)
        {
            return !(fcntl(handle, F_GETFL, 0) & O_NONBLOCK);
        }
    }

    /// ditto
    void blocking(bool byes)
    {
        version(Win32)
        {
            uint num = !byes;
            if(_SOCKET_ERROR == ioctlsocket(sock, FIONBIO, &num))
                goto err;
            _blocking = byes;
        }
        else version(BsdSockets)
        {
            int x = fcntl(sock, F_GETFL, 0);
            if(-1 == x)
                goto err;
            if(byes)
                x &= ~O_NONBLOCK;
            else
                x |= O_NONBLOCK;
            if(-1 == fcntl(sock, F_SETFL, x))
                goto err;
        }
        return;         // Success.

 err:
        throw new SocketException("Unable to set socket blocking", _lasterr());
    }


    /// Get the socket's address family.
    AddressFamily addressFamily()     // getter
    {
        return _family;
    }

    /// Property that indicates if this is a valid, alive socket.
    bool isAlive()     // getter
    {
        int type;
        socklen_t typesize = cast(socklen_t) type.sizeof;
        return !getsockopt(sock, SOL_SOCKET, SO_TYPE, cast(char*)&type, &typesize);
    }

    /// Associate a local address with this socket.
    void bind(Address addr)
    {
        if(_SOCKET_ERROR == .bind(sock, addr.name(), addr.nameLen()))
            throw new SocketException("Unable to bind socket", _lasterr());
    }

    /**
     * Establish a connection. If the socket is blocking, connect waits for
     * the connection to be made. If the socket is nonblocking, connect
     * returns immediately and the connection attempt is still in progress.
     */
    void connect(Address to)
    {
        if(_SOCKET_ERROR == .connect(sock, to.name(), to.nameLen()))
        {
            int err;
            err = _lasterr();

            if(!blocking)
            {
                version(Win32)
                {
                    if(WSAEWOULDBLOCK == err)
                        return;
                }
                else version(Posix)
                {
                    if(EINPROGRESS == err)
                        return;
                }
                else
                {
                    static assert(0);
                }
            }
            throw new SocketException("Unable to connect socket", err);
        }
    }

    /**
     * Listen for an incoming connection. bind must be called before you can
     * listen. The backlog is a request of how many pending incoming
     * connections are queued until accept'ed.
     */
    void listen(int backlog)
    {
        if(_SOCKET_ERROR == .listen(sock, backlog))
            throw new SocketException("Unable to listen on socket", _lasterr());
    }

    /**
     * Called by accept when a new Socket must be created for a new
     * connection. To use a derived class, override this method and return an
     * instance of your class. The returned Socket's handle must not be set;
     * Socket has a protected constructor this() to use in this situation.
     */
    // Override to use a derived class.
    // The returned socket's handle must not be set.
    protected Socket accepting()
    {
        return new Socket;
    }

    /**
     * Accept an incoming connection. If the socket is blocking, accept
     * waits for a connection request. Throws SocketAcceptException if unable
     * to accept. See accepting for use with derived classes.
     */
    Socket accept()
    {
        auto newsock = cast(socket_t).accept(sock, null, null);
        if(socket_t.init == newsock)
            throw new SocketAcceptException("Unable to accept socket connection", _lasterr());

        Socket newSocket;
        try
        {
            newSocket = accepting();
            assert(newSocket.sock == socket_t.init);

            newSocket.setSock(newsock);
            version(Win32)
                newSocket._blocking = _blocking;                 //inherits blocking mode
            newSocket._family = _family;             //same family
        }
        catch(Throwable o)
        {
            _close(newsock);
            throw o;
        }

        return newSocket;
    }

    /// Disables sends and/or receives.
    void shutdown(SocketShutdown how)
    {
        .shutdown(sock, cast(int)how);
    }


    private static void _close(socket_t sock)
    {
        version(Win32)
        {
            .closesocket(sock);
        }
        else version(BsdSockets)
        {
            .close(sock);
        }
    }


    /**
     * Immediately drop any connections and release socket resources.
     * Calling shutdown before close is recommended for connection-oriented
     * sockets. The Socket object is no longer usable after close.
     */
    //calling shutdown() before this is recommended
    //for connection-oriented sockets
    void close()
    {
        _close(sock);
        sock = socket_t.init;
    }


    private Address newFamilyObject()
    {
        Address result;
        switch(_family)
        {
        case cast(AddressFamily)AddressFamily.INET:
            result = new InternetAddress;
            break;

        default:
            result = new UnknownAddress;
        }
        return result;
    }


    /// Returns the local machine's host name. Idea from mango.
    static string hostName()     // getter
    {
        char[256] result;         // Host names are limited to 255 chars.
        if(_SOCKET_ERROR == .gethostname(result.ptr, result.length))
            throw new SocketException("Unable to obtain host name", _lasterr());
        return to!string(cast(char*)result).idup;
    }

    /// Remote endpoint Address.
    Address remoteAddress()
    {
        Address addr = newFamilyObject();
        socklen_t nameLen = cast(socklen_t) addr.nameLen();
        if(_SOCKET_ERROR == .getpeername(sock, addr.name(), &nameLen))
            throw new SocketException("Unable to obtain remote socket address", _lasterr());
        assert(addr.addressFamily() == _family);
        return addr;
    }

    /// Local endpoint Address.
    Address localAddress()
    {
        Address addr = newFamilyObject();
        socklen_t nameLen = cast(socklen_t) addr.nameLen();
        if(_SOCKET_ERROR == .getsockname(sock, addr.name(), &nameLen))
            throw new SocketException("Unable to obtain local socket address", _lasterr());
        assert(addr.addressFamily() == _family);
        return addr;
    }

    /// Send or receive error code.
    enum int ERROR = _SOCKET_ERROR;

    /**
     * Send data on the connection. Returns the number of bytes actually
     * sent, or ERROR on failure. If the socket is blocking and there is no
     * buffer space left, send waits.
     */
    //returns number of bytes actually sent, or -1 on error
    Select!(size_t.sizeof > 4, long, int)
    send(const(void)[] buf, SocketFlags flags)
    {
        static if (is(typeof(MSG_NOSIGNAL)))
        {
            flags = cast(SocketFlags)(flags | MSG_NOSIGNAL);
        }
        version( Windows )
            auto sent = .send(sock, buf.ptr, to!int(buf.length), cast(int)flags);
        else
            auto sent = .send(sock, buf.ptr, buf.length, cast(int)flags);
        return sent;
    }

    /// ditto
    Select!(size_t.sizeof > 4, long, int) send(const(void)[] buf)
    {
        return send(buf, SocketFlags.NONE);
    }

    /**
     * Send data to a specific destination Address. If the destination address is not specified, a connection must have been made and that address is used. If the socket is blocking and there is no buffer space left, sendTo waits.
     */
    Select!(size_t.sizeof > 4, long, int)
    sendTo(const(void)[] buf, SocketFlags flags, Address to)
    {
        static if (is(typeof(MSG_NOSIGNAL)))
        {
            flags = cast(SocketFlags)(flags | MSG_NOSIGNAL);
        }
        version( Windows )
            return .sendto(
                       sock, buf.ptr, std.conv.to!int(buf.length),
                       cast(int)flags, to.name(), to.nameLen()
                       );
        else
            return .sendto(sock, buf.ptr, buf.length, cast(int)flags, to.name(), to.nameLen());
    }

    /// ditto
    Select!(size_t.sizeof > 4, long, int) sendTo(const(void)[] buf, Address to)
    {
        return sendTo(buf, SocketFlags.NONE, to);
    }


    //assumes you connect()ed
    /// ditto
    Select!(size_t.sizeof > 4, long, int) sendTo(const(void)[] buf, SocketFlags flags)
    {
        static if (is(typeof(MSG_NOSIGNAL)))
        {
            flags = cast(SocketFlags)(flags | MSG_NOSIGNAL);
        }
        version(Windows)
            return .sendto(sock, buf.ptr, to!int(buf.length), cast(int)flags, null, 0);
        else
            return .sendto(sock, buf.ptr, buf.length, cast(int)flags, null, 0);
    }


    //assumes you connect()ed
    /// ditto
    Select!(size_t.sizeof > 4, long, int) sendTo(const(void)[] buf)
    {
        return sendTo(buf, SocketFlags.NONE);
    }


    /**
     * Receive data on the connection. Returns the number of bytes actually
     * received, 0 if the remote side has closed the connection, or ERROR on
     * failure. If the socket is blocking, receive waits until there is data
     * to be received.
     */
    //returns number of bytes actually received, 0 on connection closure, or -1 on error
    ptrdiff_t receive(void[] buf, SocketFlags flags)
    {
        version(Win32)         // Does not use size_t
        {
            return buf.length
                   ? .recv(sock, buf.ptr, to!int(buf.length), cast(int)flags)
                   : 0;
        } else {
            return buf.length
                   ? .recv(sock, buf.ptr, buf.length, cast(int)flags)
                   : 0;
        }
    }

    /// ditto
    ptrdiff_t receive(void[] buf)
    {
        return receive(buf, SocketFlags.NONE);
    }

    /**
     * Receive data and get the remote endpoint Address.
     * If the socket is blocking, receiveFrom waits until there is data to
     * be received.
     * Returns: the number of bytes actually received,
     * 0 if the remote side has closed the connection, or ERROR on failure.
     */
    Select!(size_t.sizeof > 4, long, int)
    receiveFrom(void[] buf, SocketFlags flags, out Address from)
    {
        if(!buf.length)         //return 0 and don't think the connection closed
            return 0;
        from = newFamilyObject();
        socklen_t nameLen = cast(socklen_t) from.nameLen();
        version(Win32)
        {
            auto read = .recvfrom(sock, buf.ptr, to!int(buf.length), cast(int)flags, from.name(), &nameLen);
            assert(from.addressFamily() == _family);
            // if(!read) //connection closed
            return read;
        } else {
            auto read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, from.name(), &nameLen);
            assert(from.addressFamily() == _family);
            // if(!read) //connection closed
            return read;
        }
    }


    /// ditto
    ptrdiff_t receiveFrom(void[] buf, out Address from)
    {
        return receiveFrom(buf, SocketFlags.NONE, from);
    }


    //assumes you connect()ed
    /// ditto
    Select!(size_t.sizeof > 4, long, int)
    receiveFrom(void[] buf, SocketFlags flags)
    {
        if(!buf.length)         //return 0 and don't think the connection closed
            return 0;
        version(Win32)
        {
            auto read = .recvfrom(sock, buf.ptr, to!int(buf.length), cast(int)flags, null, null);
            // if(!read) //connection closed
            return read;
        } else {
            auto read = .recvfrom(sock, buf.ptr, buf.length, cast(int)flags, null, null);
            // if(!read) //connection closed
            return read;
        }
    }


    //assumes you connect()ed
    /// ditto
    ptrdiff_t receiveFrom(void[] buf)
    {
        return receiveFrom(buf, SocketFlags.NONE);
    }


    /// Get a socket option. Returns the number of bytes written to result.
    //returns the length, in bytes, of the actual result - very different from getsockopt()
    int getOption(SocketOptionLevel level, SocketOption option, void[] result)
    {
        socklen_t len = cast(socklen_t) result.length;
        if(_SOCKET_ERROR == .getsockopt(sock, cast(int)level, cast(int)option, result.ptr, &len))
            throw new SocketException("Unable to get socket option", _lasterr());
        return len;
    }


    /// Common case of getting integer and boolean options.
    int getOption(SocketOptionLevel level, SocketOption option, out int32_t result)
    {
        return getOption(level, option, (&result)[0 .. 1]);
    }


    /// Get the linger option.
    int getOption(SocketOptionLevel level, SocketOption option, out linger result)
    {
        //return getOption(cast(SocketOptionLevel)SocketOptionLevel.SOCKET, SocketOption.LINGER, (&result)[0 .. 1]);
        return getOption(level, option, (&result)[0 .. 1]);
    }

    /// Get a timeout (duration) option.
    void getOption(SocketOptionLevel level, SocketOption option, out Duration result)
    {
        enforce(option == SocketOption.SNDTIMEO || option == SocketOption.RCVTIMEO,
                new SocketException("Not a valid timeout option: " ~ to!string(option)));
        // WinSock returns the timeout values as a milliseconds DWORD,
        // while Linux and BSD return a timeval struct.
        version (Win32)
        {
            int msecs;
            getOption(level, option, (&msecs)[0 .. 1]);
            if (option == SocketOption.RCVTIMEO)
                msecs += WINSOCK_TIMEOUT_SKEW;
            result = dur!"msecs"(msecs);
        }
        else version (BsdSockets)
        {
            timeval tv;
            getOption(level, option, (&tv)[0..1]);
            result = dur!"seconds"(tv.seconds) + dur!"usecs"(tv.microseconds);
        }
        else static assert(false);
    }

    // Set a socket option.
    void setOption(SocketOptionLevel level, SocketOption option, void[] value)
    {
        if(_SOCKET_ERROR == .setsockopt(sock, cast(int)level,
                                        cast(int)option, value.ptr, cast(uint) value.length))
            throw new SocketException("Unable to set socket option", _lasterr());
    }


    /// Common case for setting integer and boolean options.
    void setOption(SocketOptionLevel level, SocketOption option, int32_t value)
    {
        setOption(level, option, (&value)[0 .. 1]);
    }


    /// Set the linger option.
    void setOption(SocketOptionLevel level, SocketOption option, linger value)
    {
        //setOption(cast(SocketOptionLevel)SocketOptionLevel.SOCKET, SocketOption.LINGER, (&value)[0 .. 1]);
        setOption(level, option, (&value)[0 .. 1]);
    }

    /**
     * Sets a timeout (duration) option, i.e. SocketOption.SNDTIMEO or
     * RCVTIMEO. Zero indicates no timeout.
     *
     * In a typical application, you might also want to consider using
     * a non-blocking socket instead of setting a timeout on a blocking one.
     *
     * Note: While the receive timeout setting is generally quite accurate
     * on *nix systems even for smaller durations, there are two issues to
     * be aware of on Windows: First, although undocumented, the effective
     * timeout duration seems to be the one set on the socket plus half
     * a second. setOption() tries to compensate for that, but still,
     * timeouts under 500ms are not possible on Windows. Second, be aware
     * that the actual amount of time spent until a blocking call returns
     * randomly varies on the order of 10ms.
     *
     * Params:
     *   value = The timeout duration to set. Must not be negative.
     *
     * Throws: SocketException if setting the options fails.
     *
     * Example:
     * ---
     * import std.datetime;
     * auto pair = socketPair();
     * scope(exit) foreach (s; pair) s.close();
     *
     * // Set a receive timeout, and then wait at one end of
     * // the socket pair, knowing that no data will arrive.
     * pair[0].setOption(SocketOptionLevel.SOCKET,
     *     SocketOption.RCVTIMEO, dur!"seconds"(1));
     *
     * auto sw = StopWatch(AutoStart.yes);
     * ubyte[1] buffer;
     * pair[0].receive(buffer);
     * writefln("Waited %s ms until the socket timed out.",
     *     sw.peek.msecs);
     * ---
     */
    void setOption(SocketOptionLevel level, SocketOption option, Duration value)
    {
        enforce(option == SocketOption.SNDTIMEO || option == SocketOption.RCVTIMEO,
                new SocketException("Not a valid timeout option: " ~ to!string(option)));

        enforce(value >= dur!"hnsecs"(0), new SocketException(
                    "Timeout duration must not be negative."));

        version (Win32)
        {
            auto msecs = cast(int)value.total!"msecs"();
            if (msecs == 0 || option != SocketOption.RCVTIMEO)
            {
                setOption(level, option, msecs);
            }
            else
            {
                setOption(level, option, cast(int)
                          max(1, msecs - WINSOCK_TIMEOUT_SKEW));
            }
        }
        else version (BsdSockets)
        {
            timeval tv = { seconds: cast(int)value.total!"seconds"(),
                           microseconds: value.fracSec.usecs };
            setOption(level, option, (&tv)[0 .. 1]);
        }
        else static assert(false);
    }

    /**
     * Wait for a socket to change status. A wait timeout timeval or int microseconds may be specified; if a timeout is not specified or the timeval is null, the maximum timeout is used. The timeval timeout has an unspecified value when select returns. Returns the number of sockets with status changes, 0 on timeout, or -1 on interruption. If the return value is greater than 0, the SocketSets are updated to only contain the sockets having status changes. For a connecting socket, a write status change means the connection is established and it's able to send. For a listening socket, a read status change means there is an incoming connection request and it's able to accept.
     */
    //SocketSet's updated to include only those sockets which an event occured
    //returns the number of events, 0 on timeout, or -1 on interruption
    //for a connect()ing socket, writeability means connected
    //for a listen()ing socket, readability means listening
    //Winsock: possibly internally limited to 64 sockets per set
    static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, timeval* tv)
    in
    {
        //make sure none of the SocketSet's are the same object
        if(checkRead)
        {
            assert(checkRead !is checkWrite);
            assert(checkRead !is checkError);
        }
        if(checkWrite)
        {
            assert(checkWrite !is checkError);
        }
    }
    body
    {
        fd_set* fr, fw, fe;
        int n = 0;

        version(Win32)
        {
            // Windows has a problem with empty fd_set`s that aren't null.
            fr = (checkRead && checkRead.count()) ? checkRead.toFd_set() : null;
            fw = (checkWrite && checkWrite.count()) ? checkWrite.toFd_set() : null;
            fe = (checkError && checkError.count()) ? checkError.toFd_set() : null;
        }
        else
        {
            if(checkRead)
            {
                fr = checkRead.toFd_set();
                n = checkRead.selectn();
            }
            else
            {
                fr = null;
            }

            if(checkWrite)
            {
                fw = checkWrite.toFd_set();
                int _n;
                _n = checkWrite.selectn();
                if(_n > n)
                    n = _n;
            }
            else
            {
                fw = null;
            }

            if(checkError)
            {
                fe = checkError.toFd_set();
                int _n;
                _n = checkError.selectn();
                if(_n > n)
                    n = _n;
            }
            else
            {
                fe = null;
            }
        }

        int result = .select(n, fr, fw, fe, cast(_ctimeval*)tv);

        version(Win32)
        {
            if(_SOCKET_ERROR == result && WSAGetLastError() == WSAEINTR)
                return -1;
        }
        else version(Posix)
        {
            if(_SOCKET_ERROR == result && errno == EINTR)
                return -1;
        }
        else
        {
            static assert(0);
        }

        if(_SOCKET_ERROR == result)
            throw new SocketException("Socket select error", _lasterr());

        return result;
    }


    /// ditto
    static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError, int microseconds)
    {
        timeval tv;
        tv.seconds = microseconds / 1_000_000;
        tv.microseconds = microseconds % 1_000_000;
        return select(checkRead, checkWrite, checkError, &tv);
    }


    /// ditto
    //maximum timeout
    static int select(SocketSet checkRead, SocketSet checkWrite, SocketSet checkError)
    {
        return select(checkRead, checkWrite, checkError, null);
    }


    /+
       bool poll(events)
       {
            int WSAEventSelect(socket_t s, WSAEVENT hEventObject, int lNetworkEvents); // Winsock 2 ?
            int poll(pollfd* fds, int nfds, int timeout); // Unix ?
       }
     +/
}


/// TcpSocket is a shortcut class for a TCP Socket.
class TcpSocket: Socket
{
    /// Constructs a blocking TCP Socket.
    this(AddressFamily family)
    {
        super(family, SocketType.STREAM, ProtocolType.TCP);
    }

    /// Constructs a blocking TCP Socket.
    this()
    {
        this(cast(AddressFamily)AddressFamily.INET);
    }


    //shortcut
    /// Constructs a blocking TCP Socket and connects to an InternetAddress.
    this(Address connectTo)
    {
        this(connectTo.addressFamily());
        connect(connectTo);
    }
}


/// UdpSocket is a shortcut class for a UDP Socket.
class UdpSocket: Socket
{
    /// Constructs a blocking UDP Socket.
    this(AddressFamily family)
    {
        super(family, SocketType.DGRAM, ProtocolType.UDP);
    }


    /// Constructs a blocking UDP Socket.
    this()
    {
        this(cast(AddressFamily)AddressFamily.INET);
    }
}

/**
 * Creates a pair of connected sockets.
 *
 * The two sockets are indistinguishable.
 *
 * Throws: SocketException if creation of the sockets fails.
 *
 * Example:
 * ---
 * immutable ubyte[] data = [1, 2, 3, 4];
 * auto pair = socketPair();
 * scope(exit) foreach (s; pair) s.close();
 *
 * pair[0].send(data);
 *
 * auto buf = new ubyte[data.length];
 * pair[1].receive(buf);
 * assert(buf == data);
 * ---
 */
Socket[2] socketPair()
{
    version(BsdSockets)
    {
        int[2] socks;
        if (socketpair(AF_UNIX, SOCK_STREAM, 0, socks) == -1)
            throw new SocketException("Unable to create socket pair", _lasterr());

        Socket toSocket(size_t id)
        {
            auto s = new Socket;
            s.setSock(cast(socket_t)socks[id]);
            s._family = AddressFamily.UNIX;
            return s;
        }

        return [toSocket(0), toSocket(1)];
    }
    else version(Win32)
    {
        // We do not have socketpair() on Windows, just manually create a
        // pair of sockets connected over some localhost port.
        Socket[2] result;

        auto listener = new TcpSocket();
        listener.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true);
        listener.bind(new InternetAddress(INADDR_LOOPBACK, InternetAddress.PORT_ANY));
        auto addr = listener.localAddress();
        listener.listen(1);

        result[0] = new TcpSocket(addr);
        result[1] = listener.accept();

        listener.close();
        return result;
    }
    else
        static assert(false);
}

unittest
{
    immutable ubyte[] data = [1, 2, 3, 4];
    auto pair = socketPair();
    scope(exit) foreach (s; pair) s.close();

    pair[0].send(data);

    auto buf = new ubyte[data.length];
    pair[1].receive(buf);
    assert(buf == data);
}