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
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger                                  |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/system/netconfigs.h"
#include "gate/results.h"

#if defined(GATE_SYS_WINCE) || defined(GATE_SYS_WINSTORE) || defined(GATE_SYS_WIN16) || defined(GATE_SYS_BEOS)
#	define GATE_SYSTEM_NETCONFIG_NO_IMPL 1
#elif defined(GATE_SYS_WIN)
#	define GATE_SYSTEM_NETCONFIG_WINAPI_IMPL 1
#elif defined(GATE_SYS_POSIX)
#	define GATE_SYSTEM_NETCONFIG_POSIX_IMPL 1
#else
#	define GATE_SYSTEM_NETCONFIG_NO_IMPL 1
#endif


char const* gate_netconfig_print_status(gate_enumint_t status)
{
    switch (status)
    {
    case GATE_NETCONFIG_STATUS_UNKNOWN:			return "Unknown";
    case GATE_NETCONFIG_STATUS_DISABLED:		return "Disabled";
    case GATE_NETCONFIG_STATUS_ENABLED:			return "Enabled";
    case GATE_NETCONFIG_STATUS_NONFUNCT:		return "Non-functional";
    case GATE_NETCONFIG_STATUS_OPERATIONAL:		return "Operational";
    case GATE_NETCONFIG_STATUS_CONNECTING:		return "Connecting";
    case GATE_NETCONFIG_STATUS_CONNECTED:		return "Connected";
    case GATE_NETCONFIG_STATUS_DISCONNECTED:	return "Disconnected";
    case GATE_NETCONFIG_STATUS_ERROR:			return "Error";
    }
    return NULL;
}

char const* gate_netconfig_print_type(gate_enumint_t tp)
{
    switch (tp)
    {
    case GATE_NETCONFIG_TYPE_UNKNOWN:	return "Unknown";
    case GATE_NETCONFIG_TYPE_ETHERNET:	return "Ethernet";
    case GATE_NETCONFIG_TYPE_TOKENRING:	return "Tokenring";
    case GATE_NETCONFIG_TYPE_FDDI:		return "FDDI";
    case GATE_NETCONFIG_TYPE_PPP:		return "PPP";
    case GATE_NETCONFIG_TYPE_LOOPBACK:	return "Loopback";
    case GATE_NETCONFIG_TYPE_WLAN:		return "WLAN";
    case GATE_NETCONFIG_TYPE_SLIP:		return "SLIP";
    case GATE_NETCONFIG_TYPE_OTHER:		return "Other";
    }
    return NULL;
}



#if defined(GATE_SYSTEM_NETCONFIG_WINAPI_IMPL)

#include "gate/net/platform/socket_api.h"
#include "gate/platforms.h"

//#include <iphlpapi.h>

typedef enum
{
    IpPrefixOriginOther = 0,
    IpPrefixOriginManual,
    IpPrefixOriginWellKnown,
    IpPrefixOriginDhcp,
    IpPrefixOriginRouterAdvertisement
} IP_PREFIX_ORIGIN;

typedef enum
{
    IpSuffixOriginOther = 0,
    IpSuffixOriginManual,
    IpSuffixOriginWellKnown,
    IpSuffixOriginDhcp,
    IpSuffixOriginLinkLayerAddress,
    IpSuffixOriginRandom
} IP_SUFFIX_ORIGIN;

typedef enum
{
    IpDadStateInvalid = 0,
    IpDadStateTentative,
    IpDadStateDuplicate,
    IpDadStateDeprecated,
    IpDadStatePreferred
} IP_DAD_STATE;

#if defined(GATE_COMPILER_MSVC98)
typedef gate_unsigned_long_long_t	UINT8;
#endif

typedef struct _IP_ADAPTER_UNICAST_ADDRESS
{
    union
    {
        struct
        {
            ULONG Length;
            DWORD Flags;
        };
    };
    struct _IP_ADAPTER_UNICAST_ADDRESS* Next;
    SOCKET_ADDRESS Address;
    IP_PREFIX_ORIGIN PrefixOrigin;
    IP_SUFFIX_ORIGIN SuffixOrigin;
    IP_DAD_STATE DadState;
    ULONG ValidLifetime;
    ULONG PreferredLifetime;
    ULONG LeaseLifetime;
    UINT8 OnLinkPrefixLength;	/* only on Vista+ */
} IP_ADAPTER_UNICAST_ADDRESS, * PIP_ADAPTER_UNICAST_ADDRESS;

typedef struct _IP_ADAPTER_ANYCAST_ADDRESS
{
    union
    {
        ULONGLONG Alignment;
        struct
        {
            ULONG Length;
            DWORD Flags;
        };
    };
    struct _IP_ADAPTER_ANYCAST_ADDRESS* Next;
    SOCKET_ADDRESS Address;
} IP_ADAPTER_ANYCAST_ADDRESS, * PIP_ADAPTER_ANYCAST_ADDRESS;

typedef struct _IP_ADAPTER_MULTICAST_ADDRESS
{
    union
    {
        ULONGLONG Alignment;
        struct
        {
            ULONG Length;
            DWORD Flags;
        };
    };
    struct _IP_ADAPTER_MULTICAST_ADDRESS* Next;
    SOCKET_ADDRESS Address;
} IP_ADAPTER_MULTICAST_ADDRESS, * PIP_ADAPTER_MULTICAST_ADDRESS;

typedef struct _IP_ADAPTER_DNS_SERVER_ADDRESS
{
    union
    {
        ULONGLONG Alignment;
        struct
        {
            ULONG Length;
            DWORD Reserved;
        };
    };
    struct _IP_ADAPTER_DNS_SERVER_ADDRESS* Next;
    SOCKET_ADDRESS Address;
} IP_ADAPTER_DNS_SERVER_ADDRESS, * PIP_ADAPTER_DNS_SERVER_ADDRESS;

typedef enum
{
    IfOperStatusUp = 1,
    IfOperStatusDown,
    IfOperStatusTesting,
    IfOperStatusUnknown,
    IfOperStatusDormant,
    IfOperStatusNotPresent,
    IfOperStatusLowerLayerDown
} IF_OPER_STATUS;

typedef struct _IP_ADAPTER_PREFIX {
    union
    {
        ULONGLONG  Alignment;
        struct
        {
            ULONG Length;
            DWORD Flags;
        };
    };
    struct _IP_ADAPTER_PREFIX* Next;
    SOCKET_ADDRESS Address;
    ULONG PrefixLength;
} IP_ADAPTER_PREFIX, * PIP_ADAPTER_PREFIX;

#ifndef MAX_ADAPTER_DESCRIPTION_LENGTH
#define MAX_ADAPTER_DESCRIPTION_LENGTH  128
#endif

#ifndef MAX_ADAPTER_NAME_LENGTH
#define MAX_ADAPTER_NAME_LENGTH         256
#endif

#ifndef MAX_ADAPTER_ADDRESS_LENGTH
#define MAX_ADAPTER_ADDRESS_LENGTH      8
#endif

typedef struct _GATE_IP_ADAPTER_ADDRESSES
{
    union
    {
        ULONGLONG Alignment;
        struct
        {
            ULONG Length;
            DWORD IfIndex;
        };
    };
    struct _GATE_IP_ADAPTER_ADDRESSES* Next;
    PCHAR AdapterName;
    PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress;
    PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress;
    PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress;
    PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress;
    PWCHAR DnsSuffix;
    PWCHAR Description;
    PWCHAR FriendlyName;
    BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH];
    DWORD PhysicalAddressLength;
    union
    {
        DWORD Flags;
        struct {
            ULONG DdnsEnabled : 1;
            ULONG RegisterAdapterSuffix : 1;
            ULONG Dhcpv4Enabled : 1;
            ULONG ReceiveOnly : 1;
            ULONG NoMulticast : 1;
            ULONG Ipv6OtherStatefulConfig : 1;
            ULONG NetbiosOverTcpipEnabled : 1;
            ULONG Ipv4Enabled : 1;
            ULONG Ipv6Enabled : 1;
            ULONG Ipv6ManagedAddressConfigurationSupported : 1;
        };
    };
    DWORD Mtu;
    DWORD IfType;
    IF_OPER_STATUS OperStatus;
    DWORD Ipv6IfIndex;
    DWORD ZoneIndices[16];
    PIP_ADAPTER_PREFIX FirstPrefix;
} IP_ADAPTER_ADDRESSES, * PIP_ADAPTER_ADDRESSES;

typedef struct {
    char String[4 * 4];
} IP_ADDRESS_STRING, * PIP_ADDRESS_STRING, IP_MASK_STRING, * PIP_MASK_STRING;


typedef struct _IP_ADDR_STRING {
    struct _IP_ADDR_STRING* Next;
    IP_ADDRESS_STRING IpAddress;
    IP_MASK_STRING IpMask;
    DWORD Context;
} IP_ADDR_STRING, * PIP_ADDR_STRING;


typedef struct _IP_ADAPTER_INFO
{
    struct _IP_ADAPTER_INFO* Next;
    DWORD ComboIndex;
    char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4];
    char Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4];
    UINT AddressLength;
    BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH];
    DWORD Index;
    UINT Type;
    UINT DhcpEnabled;
    PIP_ADDR_STRING CurrentIpAddress;
    IP_ADDR_STRING IpAddressList;
    IP_ADDR_STRING GatewayList;
    IP_ADDR_STRING DhcpServer;
    BOOL HaveWins;
    IP_ADDR_STRING PrimaryWinsServer;
    IP_ADDR_STRING SecondaryWinsServer;
    time_t LeaseObtained;
    time_t LeaseExpires;
} IP_ADAPTER_INFO, * PIP_ADAPTER_INFO;

#ifndef MAX_INTERFACE_NAME_LEN
#define MAX_INTERFACE_NAME_LEN 256
#endif

#ifndef MAXLEN_PHYSADDR
#define MAXLEN_PHYSADDR 8
#endif

#ifndef MAXLEN_IFDESCR
#define MAXLEN_IFDESCR 256
#endif

#ifndef ANY_SIZE
#define ANY_SIZE 1
#endif

typedef struct _MIB_IFROW {
    WCHAR wszName[MAX_INTERFACE_NAME_LEN];
    DWORD dwIndex;
    DWORD dwType;
    DWORD dwMtu;
    DWORD dwSpeed;
    DWORD dwPhysAddrLen;
    BYTE bPhysAddr[MAXLEN_PHYSADDR];
    DWORD dwAdminStatus;
    DWORD dwOperStatus;
    DWORD dwLastChange;
    DWORD dwInOctets;
    DWORD dwInUcastPkts;
    DWORD dwInNUcastPkts;
    DWORD dwInDiscards;
    DWORD dwInErrors;
    DWORD dwInUnknownProtos;
    DWORD dwOutOctets;
    DWORD dwOutUcastPkts;
    DWORD dwOutNUcastPkts;
    DWORD dwOutDiscards;
    DWORD dwOutErrors;
    DWORD dwOutQLen;
    DWORD dwDescrLen;
    BYTE bDescr[MAXLEN_IFDESCR];
} MIB_IFROW, * PMIB_IFROW;


typedef struct _MIB_IFTABLE
{
    DWORD dwNumEntries;
    MIB_IFROW table[ANY_SIZE];
} MIB_IFTABLE, * PMIB_IFTABLE;

typedef union _NET_LUID_LH
{
    ULONG64     Value;
    struct
    {
        ULONG64     Reserved : 24;
        ULONG64     NetLuidIndex : 24;
        ULONG64     IfType : 16;
    }Info;
} NET_LUID_LH, * PNET_LUID_LH;

typedef NET_LUID_LH NET_LUID;
typedef NET_LUID* PNET_LUID;

typedef ULONG NET_IFINDEX, * PNET_IFINDEX;
#if defined(GATE_COMPILER_MSVC98)
typedef USHORT NET_IFTYPE, * PNET_IFTYPE;
#else
typedef UINT16 NET_IFTYPE, * PNET_IFTYPE;
#endif

#define IF_MAX_STRING_SIZE 256
#define IF_MAX_PHYS_ADDRESS_LENGTH 32

typedef ULONG IFTYPE;

typedef enum {
    TUNNEL_TYPE_NONE = 0,
    TUNNEL_TYPE_OTHER = 1,
    TUNNEL_TYPE_DIRECT = 2,
    TUNNEL_TYPE_6TO4 = 11,
    TUNNEL_TYPE_ISATAP = 13,
    TUNNEL_TYPE_TEREDO = 14,
    TUNNEL_TYPE_IPHTTPS = 15,
} TUNNEL_TYPE, * PTUNNEL_TYPE;

typedef enum _NDIS_MEDIUM
{
    NdisMedium802_3,
    NdisMedium802_5,
    NdisMediumFddi,
    NdisMediumWan,
    NdisMediumLocalTalk,
    NdisMediumDix,              // defined for convenience, not a real medium
    NdisMediumArcnetRaw,
    NdisMediumArcnet878_2,
    NdisMediumAtm,
    NdisMediumWirelessWan,
    NdisMediumIrda,
    NdisMediumBpc,
    NdisMediumCoWan,
    NdisMedium1394,
    NdisMediumInfiniBand,
    NdisMediumTunnel,
    NdisMediumNative802_11,
    NdisMediumLoopback,
    NdisMediumWiMAX,
    NdisMediumIP,

    NdisMediumMax               // Not a real medium, defined as an upper-bound
} NDIS_MEDIUM, * PNDIS_MEDIUM;

typedef enum _NDIS_PHYSICAL_MEDIUM
{
    NdisPhysicalMediumUnspecified,
    NdisPhysicalMediumWirelessLan,
    NdisPhysicalMediumCableModem,
    NdisPhysicalMediumPhoneLine,
    NdisPhysicalMediumPowerLine,
    NdisPhysicalMediumDSL,      // includes ADSL and UADSL (G.Lite)
    NdisPhysicalMediumFibreChannel,
    NdisPhysicalMedium1394,
    NdisPhysicalMediumWirelessWan,
    NdisPhysicalMediumNative802_11,
    NdisPhysicalMediumBluetooth,
    NdisPhysicalMediumInfiniband,
    NdisPhysicalMediumWiMax,
    NdisPhysicalMediumUWB,
    NdisPhysicalMedium802_3,
    NdisPhysicalMedium802_5,
    NdisPhysicalMediumIrda,
    NdisPhysicalMediumWiredWAN,
    NdisPhysicalMediumWiredCoWan,
    NdisPhysicalMediumOther,
    NdisPhysicalMediumNative802_15_4,
    NdisPhysicalMediumMax       // Not a real physical type, defined as an upper-bound
} NDIS_PHYSICAL_MEDIUM, * PNDIS_PHYSICAL_MEDIUM;

typedef enum _NET_IF_ACCESS_TYPE
{
    NET_IF_ACCESS_LOOPBACK = 1,
    NET_IF_ACCESS_BROADCAST = 2,
    NET_IF_ACCESS_POINT_TO_POINT = 3,
    NET_IF_ACCESS_POINT_TO_MULTI_POINT = 4,
    NET_IF_ACCESS_MAXIMUM = 5
} NET_IF_ACCESS_TYPE, * PNET_IF_ACCESS_TYPE;

typedef enum _NET_IF_DIRECTION_TYPE
{
    NET_IF_DIRECTION_SENDRECEIVE,
    NET_IF_DIRECTION_SENDONLY,
    NET_IF_DIRECTION_RECEIVEONLY,
    NET_IF_DIRECTION_MAXIMUM
} NET_IF_DIRECTION_TYPE, * PNET_IF_DIRECTION_TYPE;

typedef enum _NET_IF_ADMIN_STATUS   // ifAdminStatus
{
    NET_IF_ADMIN_STATUS_UP = 1,
    NET_IF_ADMIN_STATUS_DOWN = 2,
    NET_IF_ADMIN_STATUS_TESTING = 3
} NET_IF_ADMIN_STATUS, * PNET_IF_ADMIN_STATUS;

typedef enum _NET_IF_MEDIA_CONNECT_STATE
{
    MediaConnectStateUnknown,
    MediaConnectStateConnected,
    MediaConnectStateDisconnected
} NET_IF_MEDIA_CONNECT_STATE, * PNET_IF_MEDIA_CONNECT_STATE;

typedef GUID NET_IF_NETWORK_GUID, * PNET_IF_NETWORK_GUID;

typedef enum _NET_IF_CONNECTION_TYPE
{
    NET_IF_CONNECTION_DEDICATED = 1,
    NET_IF_CONNECTION_PASSIVE = 2,
    NET_IF_CONNECTION_DEMAND = 3,
    NET_IF_CONNECTION_MAXIMUM = 4
} NET_IF_CONNECTION_TYPE, * PNET_IF_CONNECTION_TYPE;

typedef struct _MIB_IF_ROW2 {
    //
    // Key structure.  Sorted by preference.
    //
    NET_LUID InterfaceLuid;
    NET_IFINDEX InterfaceIndex;

    //
    // Read-Only fields.
    //
    GUID InterfaceGuid;
    WCHAR Alias[IF_MAX_STRING_SIZE + 1];
    WCHAR Description[IF_MAX_STRING_SIZE + 1];
    ULONG PhysicalAddressLength;
    UCHAR PhysicalAddress[IF_MAX_PHYS_ADDRESS_LENGTH];
    UCHAR PermanentPhysicalAddress[IF_MAX_PHYS_ADDRESS_LENGTH];

    ULONG Mtu;
    IFTYPE Type;                // Interface Type.
    TUNNEL_TYPE TunnelType;     // Tunnel Type, if Type = IF_TUNNEL.
    NDIS_MEDIUM MediaType;
    NDIS_PHYSICAL_MEDIUM PhysicalMediumType;
    NET_IF_ACCESS_TYPE AccessType;
    NET_IF_DIRECTION_TYPE DirectionType;
    struct {
        BOOLEAN HardwareInterface : 1;
        BOOLEAN FilterInterface : 1;
        BOOLEAN ConnectorPresent : 1;
        BOOLEAN NotAuthenticated : 1;
        BOOLEAN NotMediaConnected : 1;
        BOOLEAN Paused : 1;
        BOOLEAN LowPower : 1;
        BOOLEAN EndPointInterface : 1;
    } InterfaceAndOperStatusFlags;

    IF_OPER_STATUS OperStatus;
    NET_IF_ADMIN_STATUS AdminStatus;
    NET_IF_MEDIA_CONNECT_STATE MediaConnectState;
    NET_IF_NETWORK_GUID NetworkGuid;
    NET_IF_CONNECTION_TYPE ConnectionType;

    //
    // Statistics.
    //
    ULONG64 TransmitLinkSpeed;
    ULONG64 ReceiveLinkSpeed;

    ULONG64 InOctets;
    ULONG64 InUcastPkts;
    ULONG64 InNUcastPkts;
    ULONG64 InDiscards;
    ULONG64 InErrors;
    ULONG64 InUnknownProtos;
    ULONG64 InUcastOctets;
    ULONG64 InMulticastOctets;
    ULONG64 InBroadcastOctets;
    ULONG64 OutOctets;
    ULONG64 OutUcastPkts;
    ULONG64 OutNUcastPkts;
    ULONG64 OutDiscards;
    ULONG64 OutErrors;
    ULONG64 OutUcastOctets;
    ULONG64 OutMulticastOctets;
    ULONG64 OutBroadcastOctets;
    ULONG64 OutQLen;
} MIB_IF_ROW2, * PMIB_IF_ROW2;

typedef struct _MIB_IF_TABLE2 {
    ULONG NumEntries;
    MIB_IF_ROW2 Table[ANY_SIZE];
} MIB_IF_TABLE2, * PMIB_IF_TABLE2;


typedef struct _MIB_IPADDRROW {
    DWORD dwAddr;
    DWORD dwIndex;
    DWORD dwMask;
    DWORD dwBCastAddr;
    DWORD dwReasmSize;
    unsigned short unused1;
    unsigned short wType;
} MIB_IPADDRROW, * PMIB_IPADDRROW;

typedef struct _MIB_IPADDRTABLE {
    DWORD dwNumEntries;
    MIB_IPADDRROW table[ANY_SIZE];
} MIB_IPADDRTABLE, * PMIB_IPADDRTABLE;

#define GAA_FLAG_SKIP_UNICAST                   0x0001
#define GAA_FLAG_SKIP_ANYCAST                   0x0002
#define GAA_FLAG_SKIP_MULTICAST                 0x0004
#define GAA_FLAG_SKIP_DNS_SERVER                0x0008
#define GAA_FLAG_INCLUDE_PREFIX                 0x0010
#define GAA_FLAG_SKIP_FRIENDLY_NAME             0x0020
#define GAA_FLAG_INCLUDE_WINS_INFO              0x0040
#define GAA_FLAG_INCLUDE_GATEWAYS               0x0080
#define GAA_FLAG_INCLUDE_ALL_INTERFACES         0x0100
#define GAA_FLAG_INCLUDE_ALL_COMPARTMENTS       0x0200
#define GAA_FLAG_INCLUDE_TUNNEL_BINDINGORDER    0x0400
#define GAA_FLAG_SKIP_DNS_INFO                  0x0800



typedef struct
{
    DWORD(WINAPI* GetAdaptersInfo)(PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen);
    DWORD(WINAPI* GetIfTable)(PMIB_IFTABLE pIfTable, PULONG pdwSize, BOOL bOrder);
    DWORD(WINAPI* GetIpAddrTable)(PMIB_IPADDRTABLE pIpAddrTable, PULONG pdwSize, BOOL bOrder);
    ULONG(WINAPI* GetAdaptersAddresses)(ULONG Family, ULONG Flags, PVOID Reserved, PIP_ADAPTER_ADDRESSES AdapterAddresses, PULONG SizePointer);
    DWORD(WINAPI* GetIfTable2)(PMIB_IF_TABLE2* Table);
    VOID(WINAPI* FreeMibTable)(PVOID Memory);
} win32_iphlpapi;

static win32_iphlpapi iphlp;

static gate_result_t load_iphlpapi()
{
    static HMODULE hmod_iphlpapi = NULL;
    HMODULE hmod = NULL;

    if (NULL == hmod_iphlpapi)
    {
        hmod = gate_win32_load_library(_T("iphlpapi"), 0);
        if (hmod == NULL)
        {
            return GATE_RESULT_NOTAVAILABLE;
        }
        gate_win32_get_proc_address(hmod, "GetAdaptersInfo", &iphlp.GetAdaptersInfo);
        gate_win32_get_proc_address(hmod, "GetIfTable", &iphlp.GetIfTable);
        gate_win32_get_proc_address(hmod, "GetIpAddrTable", &iphlp.GetIpAddrTable);
        gate_win32_get_proc_address(hmod, "GetAdaptersAddresses", &iphlp.GetAdaptersAddresses);
        gate_win32_get_proc_address(hmod, "GetIfTable2", &iphlp.GetIfTable2);
        gate_win32_get_proc_address(hmod, "FreeMibTable", &iphlp.FreeMibTable);
        hmod_iphlpapi = hmod;
    }
    return GATE_RESULT_OK;
}

#define GATE_MIB_IF_TYPE_OTHER		1
#define GATE_MIB_IF_TYPE_ETHERNET	6
#define GATE_MIB_IF_TYPE_TOKENRING	9
#define GATE_MIB_IF_TYPE_FDDI		15
#define GATE_MIB_IF_TYPE_PPP		23
#define GATE_MIB_IF_TYPE_LOOPBACK	24
#define GATE_MIB_IF_TYPE_SLIP		28
#define GATE_IF_TYPE_IEEE80211		71

#define GATE_IF_OPER_STATUS_NON_OPERATIONAL	0
#define GATE_IF_OPER_STATUS_UNREACHABLE		1
#define GATE_IF_OPER_STATUS_DISCONNECTED	2
#define GATE_IF_OPER_STATUS_CONNECTING		3
#define GATE_IF_OPER_STATUS_CONNECTED		4
#define GATE_IF_OPER_STATUS_OPERATIONAL		5

static void print_mac(gate_uint8_t const* ptr_bytes, gate_size_t len, char* text, gate_size_t text_len)
{
    gate_strbuilder_t builder;
    gate_size_t ndx;

    gate_strbuilder_create_static(&builder, text, text_len, 0);
    for (ndx = 0; ndx != len; ++ndx)
    {
        if (ndx != 0)
        {
            gate_strbuilder_append_chars(&builder, 1, ':');
        }
        gate_strbuilder_append_hex(&builder, &ptr_bytes[ndx], 1, false);
    }

}

static unsigned convert_nif_type(DWORD tp)
{
    switch (tp)
    {
    case GATE_MIB_IF_TYPE_OTHER:		return GATE_NETCONFIG_TYPE_OTHER;
    case GATE_MIB_IF_TYPE_ETHERNET:		return GATE_NETCONFIG_TYPE_ETHERNET;
    case GATE_MIB_IF_TYPE_TOKENRING:	return GATE_NETCONFIG_TYPE_TOKENRING;
    case GATE_MIB_IF_TYPE_FDDI:			return GATE_NETCONFIG_TYPE_FDDI;
    case GATE_MIB_IF_TYPE_PPP:			return GATE_NETCONFIG_TYPE_PPP;
    case GATE_MIB_IF_TYPE_LOOPBACK:		return GATE_NETCONFIG_TYPE_LOOPBACK;
    case GATE_MIB_IF_TYPE_SLIP:			return GATE_NETCONFIG_TYPE_SLIP;
    case GATE_IF_TYPE_IEEE80211:		return GATE_NETCONFIG_TYPE_WLAN;
    default:							return GATE_NETCONFIG_TYPE_UNKNOWN;
    }
}

static gate_bool_t mibrow_2_nif(MIB_IFROW const* ptr_row, gate_netconfig_nif_t* ptr_nif)
{
    gate_size_t pos1, pos2;
    gate_size_t namelen = gate_str16_length_max(ptr_row->wszName, sizeof(ptr_row->wszName) / sizeof(ptr_row->wszName[0]));

    gate_mem_clear(ptr_nif, sizeof(gate_netconfig_nif_t));

    /* get UID */
    pos1 = gate_str16_char_pos(ptr_row->wszName, namelen, '{', 0);
    if (pos1 == GATE_STR_NPOS)
    {
        /* NT/9x: No GUID-string, use index instead */
        ptr_nif->uid[0] = '#';
        gate_str_print_uint(&ptr_nif->uid[1], sizeof(ptr_nif->uid) - 1, ptr_row->dwIndex, 0);
    }
    else
    {
        pos2 = gate_str16_char_pos(ptr_row->wszName, namelen, '}', pos1 + 1);
        if (pos2 == GATE_STR_NPOS)
        {
            /* error: invalid guid string */
            return false;
        }
        gate_str_utf16_2_utf8(&ptr_row->wszName[pos1 + 1], pos2 - pos1 - 1, ptr_nif->uid, sizeof(ptr_nif->uid));
    }

    gate_str_print_text(ptr_nif->name, sizeof(ptr_nif->name), (char const*)&ptr_row->bDescr[0], ptr_row->dwDescrLen);

    ptr_nif->index = (gate_size_t)ptr_row->dwIndex;

    ptr_nif->type = convert_nif_type(ptr_row->dwType);

    switch (ptr_row->dwOperStatus)
    {
    case GATE_IF_OPER_STATUS_NON_OPERATIONAL:	ptr_nif->status = GATE_NETCONFIG_STATUS_DISABLED; break;
    case GATE_IF_OPER_STATUS_UNREACHABLE:		ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_NONFUNCT; break;
    case GATE_IF_OPER_STATUS_DISCONNECTED:		ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_DISCONNECTED; break;
    case GATE_IF_OPER_STATUS_CONNECTING:		ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_CONNECTING; break;
    case GATE_IF_OPER_STATUS_CONNECTED:			ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_CONNECTED; break;
    case GATE_IF_OPER_STATUS_OPERATIONAL:		ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_OPERATIONAL; break;
    default:									ptr_nif->status = GATE_NETCONFIG_STATUS_UNKNOWN; break;
    }

    print_mac(&ptr_row->bPhysAddr[0], ptr_row->dwPhysAddrLen, ptr_nif->address, sizeof(ptr_nif->address));

    return true;
}

static gate_bool_t is_nif_enabled(IP_ADAPTER_INFO const* ptr_info)
{
    static gate_string_t const str_uninit = GATE_STRING_INIT_STATIC("0.0.0.0");
    gate_string_t str;
    gate_string_create_static_len(&str,
        ptr_info->IpAddressList.IpAddress.String,
        gate_str_length_max(ptr_info->IpAddressList.IpAddress.String, sizeof(ptr_info->IpAddressList.IpAddress.String)));
    if (gate_string_is_empty(&str))
    {
        return false;
    }
    return !(gate_string_equals(&str, &str_uninit));
}

static gate_bool_t info_2_nif(IP_ADAPTER_INFO const* ptr_info, gate_netconfig_nif_t* ptr_nif)
{
    gate_size_t pos1, pos2;
    gate_size_t namelen = gate_str_length_max(ptr_info->AdapterName, sizeof(ptr_info->AdapterName));

    gate_mem_clear(ptr_nif, sizeof(gate_netconfig_nif_t));

    /* get UID */
    pos1 = gate_str_char_pos(ptr_info->AdapterName, namelen, '{', 0);
    if (pos1 == GATE_STR_NPOS)
    {
        return false;
    }
    pos2 = gate_str_char_pos(ptr_info->AdapterName, namelen, '}', pos1 + 1);
    if (pos2 == GATE_STR_NPOS)
    {
        return false;
    }
    gate_str_print_text(ptr_nif->uid, sizeof(ptr_nif->uid), &ptr_info->AdapterName[pos1 + 1], pos2 - pos1 - 1);

    /* get name: */
    gate_str_print_text(ptr_nif->name, sizeof(ptr_nif->name),
        ptr_info->Description,
        gate_str_length_max(ptr_info->Description, sizeof(ptr_info->Description)));

    /* get MAC: */
    print_mac(&ptr_info->Address[0], ptr_info->AddressLength, ptr_nif->address, sizeof(ptr_nif->address));

    ptr_nif->type = convert_nif_type(ptr_info->Type);
    ptr_nif->status = is_nif_enabled(ptr_info)
        ? (GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_OPERATIONAL)
        : GATE_NETCONFIG_STATUS_DISABLED;
    ptr_nif->index = ptr_info->Index;
    return true;
}

static gate_bool_t mibrow2_2_nif(MIB_IF_ROW2 const* ptr_row, gate_netconfig_nif_t* ptr_nif)
{
    //gate_size_t pos1, pos2;
    //gate_size_t namelen = gate_str16_length_max(ptr_row->Alias, sizeof(ptr_row->Alias) / sizeof(ptr_row->Alias[0]));

    gate_mem_clear(ptr_nif, sizeof(gate_netconfig_nif_t));

    if (ptr_row->InterfaceAndOperStatusFlags.FilterInterface)
    {
        return false;
    }

    /* get UID */
    gate_str_print_hex_uint32(&ptr_nif->uid[0], 8, ptr_row->InterfaceGuid.Data1, true);
    ptr_nif->uid[8] = '-';
    gate_str_print_hex_uint16(&ptr_nif->uid[9], 4, ptr_row->InterfaceGuid.Data2, true);
    ptr_nif->uid[13] = '-';
    gate_str_print_hex_uint16(&ptr_nif->uid[14], 4, ptr_row->InterfaceGuid.Data3, true);
    ptr_nif->uid[18] = '-';
    gate_str_print_hex_byte(&ptr_nif->uid[19], 2, ptr_row->InterfaceGuid.Data4[0], true);
    gate_str_print_hex_byte(&ptr_nif->uid[21], 2, ptr_row->InterfaceGuid.Data4[1], true);
    ptr_nif->uid[23] = '-';
    gate_str_print_hex_byte(&ptr_nif->uid[24], 2, ptr_row->InterfaceGuid.Data4[2], true);
    gate_str_print_hex_byte(&ptr_nif->uid[26], 2, ptr_row->InterfaceGuid.Data4[3], true);
    gate_str_print_hex_byte(&ptr_nif->uid[28], 2, ptr_row->InterfaceGuid.Data4[4], true);
    gate_str_print_hex_byte(&ptr_nif->uid[30], 2, ptr_row->InterfaceGuid.Data4[5], true);
    gate_str_print_hex_byte(&ptr_nif->uid[32], 2, ptr_row->InterfaceGuid.Data4[6], true);
    gate_str_print_hex_byte(&ptr_nif->uid[34], 2, ptr_row->InterfaceGuid.Data4[7], true);
    ptr_nif->uid[36] = '\0';

    gate_str_utf16_2_utf8(&ptr_row->Description[0], gate_str16_length(&ptr_row->Description[0]), ptr_nif->name, sizeof(ptr_nif->name));

    ptr_nif->index = (gate_size_t)ptr_row->InterfaceIndex;

    ptr_nif->type = convert_nif_type(ptr_row->Type);

    switch (ptr_row->OperStatus)
    {
        /* case GATE_IF_OPER_STATUS_NON_OPERATIONAL:	ptr_nif->status = GATE_NETCONFIG_STATUS_DISABLED; break; */
    case GATE_IF_OPER_STATUS_UNREACHABLE:		ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_NONFUNCT; break;
    case GATE_IF_OPER_STATUS_DISCONNECTED:		ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_DISCONNECTED; break;
    case GATE_IF_OPER_STATUS_CONNECTING:		ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_CONNECTING; break;
    case GATE_IF_OPER_STATUS_CONNECTED:			ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_CONNECTED; break;
    case GATE_IF_OPER_STATUS_OPERATIONAL:		ptr_nif->status = GATE_NETCONFIG_STATUS_ENABLED | GATE_NETCONFIG_STATUS_OPERATIONAL; break;
    default:									ptr_nif->status = GATE_NETCONFIG_STATUS_UNKNOWN; break;
    }

    print_mac(&ptr_row->PhysicalAddress[0], ptr_row->PhysicalAddressLength, ptr_nif->address, sizeof(ptr_nif->address));

    return true;
}



static gate_bool_t index_found(DWORD const* ptr_list, DWORD list_count, DWORD test_index)
{
    DWORD ndx;
    for (ndx = 0; ndx != list_count; ++ndx)
    {
        if (ptr_list[ndx] == test_index)
        {
            return true;
        }
    }
    return false;
}

gate_result_t gate_netconfig_enum_nifs(gate_netcfg_enum_nif_callback_t cb, void* userparam)
{
    gate_result_t result;
    ULONG infosize = 0;
    DWORD err_code;
    DWORD ndx;
    IP_ADAPTER_INFO* ptr_adainfo = NULL;
    IP_ADAPTER_INFO* ptr_info;
    MIB_IFTABLE* ptr_iftable = NULL;
    MIB_IFROW* ptr_row;
    PMIB_IF_TABLE2 ptr_iftable2 = NULL;
    MIB_IF_ROW2* ptr_row2;
    gate_netconfig_nif_t nif;
    DWORD handled_indexes[512];
    DWORD handled_indexes_count = 0;
    gate_bool_t canceled_by_callback = false;

    do
    {
        result = load_iphlpapi();
        GATE_BREAK_IF_FAILED(result);

        /* try winvista+ APIs first: */
        do
        {
            if (!iphlp.GetIfTable2 || !iphlp.FreeMibTable)
            {
                /* api not supported */
                break;
            }

            err_code = iphlp.GetIfTable2(&ptr_iftable2);
            if (NO_ERROR != err_code)
            {
                result = GATE_RESULT_FAILED;
                break;
            }

            for (ndx = 0; (ndx != ptr_iftable2->NumEntries) && !canceled_by_callback; ++ndx)
            {
                ptr_row2 = &ptr_iftable2->Table[ndx];
                if (index_found(handled_indexes, handled_indexes_count, ptr_row2->InterfaceIndex))
                {
                    /* this index was handled by previous code block*/
                    continue;
                }
                if (mibrow2_2_nif(ptr_row2, &nif))
                {
                    handled_indexes[handled_indexes_count] = (DWORD)nif.index;
                    ++handled_indexes_count;

                    canceled_by_callback = !cb(&nif, userparam);
                }
            }
        } while (0);

        if (canceled_by_callback)
        {
            break;
        }


        /* try Win2K API: */
        do
        {
            if (!iphlp.GetAdaptersInfo)
            {
                break;
            }
            infosize = sizeof(IP_ADAPTER_INFO);
            ptr_adainfo = (IP_ADAPTER_INFO*)gate_mem_alloc(infosize);
            if (!ptr_adainfo)
            {
                result = GATE_RESULT_OUTOFMEMORY;
                break;
            }
            err_code = iphlp.GetAdaptersInfo(ptr_adainfo, &infosize);
            if (err_code == ERROR_BUFFER_OVERFLOW)
            {
                ptr_adainfo = (IP_ADAPTER_INFO*)gate_mem_realloc(ptr_adainfo, infosize);
                if (!ptr_adainfo)
                {
                    result = GATE_RESULT_OUTOFMEMORY;
                    break;
                }
                err_code = iphlp.GetAdaptersInfo(ptr_adainfo, &infosize);
            }
            if (ERROR_SUCCESS != err_code)
            {
                result = GATE_RESULT_FAILED;
                break;
            }
            ptr_info = ptr_adainfo;
            do
            {
                if (index_found(handled_indexes, handled_indexes_count, ptr_info->Index) || canceled_by_callback)
                {
                    /* this index was handled by previous code block*/
                    continue;
                }

                if (info_2_nif(ptr_info, &nif))
                {
                    handled_indexes[handled_indexes_count] = (DWORD)nif.index;
                    ++handled_indexes_count;

                    canceled_by_callback = !cb(&nif, userparam);
                }
            } while (NULL != (ptr_info = ptr_info->Next));
        } while (0);

        if (canceled_by_callback)
        {
            break;
        }


        /* try NT4/Win9x API */
        do
        {
            if (!iphlp.GetIfTable)
            {
                break;
            }

            infosize = 0;
            iphlp.GetIfTable(NULL, &infosize, FALSE);
            if (infosize != 0)
            {
                infosize += 1024;
                ptr_iftable = (MIB_IFTABLE*)gate_mem_alloc((gate_size_t)infosize);
                if (ptr_iftable == NULL)
                {
                    result = GATE_RESULT_OUTOFMEMORY;
                    break;
                }
                gate_mem_clear(ptr_iftable, infosize);
                err_code = iphlp.GetIfTable(ptr_iftable, &infosize, FALSE);
                if (NO_ERROR != err_code)
                {
                    result = GATE_RESULT_FAILED;
                    break;
                }
                for (ndx = 0; (ndx != ptr_iftable->dwNumEntries) && !canceled_by_callback; ++ndx)
                {
                    ptr_row = &ptr_iftable->table[ndx];
                    if (index_found(handled_indexes, handled_indexes_count, ptr_row->dwIndex))
                    {
                        /* this index was handled by previous code block*/
                        continue;
                    }
                    if (mibrow_2_nif(ptr_row, &nif))
                    {
                        handled_indexes[handled_indexes_count] = (DWORD)nif.index;
                        ++handled_indexes_count;

                        canceled_by_callback = !cb(&nif, userparam);
                    }
                }
            }
        } while (0);

        if (canceled_by_callback)
        {
            break;
        }

    } while (0);

    if (ptr_iftable)
    {
        gate_mem_dealloc(ptr_iftable);
    }
    if (ptr_adainfo)
    {
        gate_mem_dealloc(ptr_adainfo);
    }
    if (ptr_iftable2)
    {
        iphlp.FreeMibTable(ptr_iftable2);
    }
    return result;
}

static void print_ipv4_addr(gate_strbuilder_t* ptr_builder, DWORD dwIP)
{
    gate_strbuilder_append_uint32(ptr_builder, (dwIP & 0x000000ff));
    gate_strbuilder_append_chars(ptr_builder, 1, '.');
    gate_strbuilder_append_uint32(ptr_builder, (dwIP & 0x0000ff00) >> 8);
    gate_strbuilder_append_chars(ptr_builder, 1, '.');
    gate_strbuilder_append_uint32(ptr_builder, (dwIP & 0x00ff0000) >> 16);
    gate_strbuilder_append_chars(ptr_builder, 1, '.');
    gate_strbuilder_append_uint32(ptr_builder, (dwIP & 0xff000000) >> 24);
}

static gate_bool_t ipaddrrow_to_netaddrr(PMIB_IPADDRROW row, gate_netconfig_address_t* addr)
{
    gate_strbuilder_t builder;

    gate_mem_clear(addr, sizeof(gate_netconfig_address_t));

    gate_strbuilder_create_static(&builder, addr->address, sizeof(addr->address), 0);
    print_ipv4_addr(&builder, row->dwAddr);

    gate_strbuilder_create_static(&builder, addr->mask, sizeof(addr->mask), 0);
    print_ipv4_addr(&builder, row->dwMask);

    addr->addrtype = GATE_NETCONFIG_ADDRTYPE_HOSTIP;
    addr->flags = 0;
    return true;
}

static gate_bool_t notify_all_addr_strings(gate_netconfig_address_t* ptr_target, IP_ADDR_STRING* ptr_addr_string, gate_bool_t add_mask, gate_enumint_t addr_type,
    gate_netcfg_enum_addresses_callback_t cb, void* userparam)
{
    gate_bool_t ret = true;
    gate_size_t addr_len;
    gate_size_t mask_len;

    while (ptr_addr_string && ret)
    {
        gate_mem_clear(ptr_target, sizeof(gate_netconfig_address_t));
        addr_len = gate_str_length(ptr_addr_string->IpAddress.String);
        gate_str_print_text(ptr_target->address, sizeof(ptr_target->address), ptr_addr_string->IpAddress.String, addr_len);
        if (add_mask)
        {
            mask_len = gate_str_length(ptr_addr_string->IpMask.String);
            gate_str_print_text(ptr_target->mask, sizeof(ptr_target->mask), ptr_addr_string->IpMask.String, mask_len);
        }
        ptr_target->addrtype = addr_type;
        ptr_target->flags = 0;

        if (addr_len > 0)
        {
            ret &= cb(ptr_target, userparam);
        }

        ptr_addr_string = ptr_addr_string->Next;
    }
    return true;
}

struct ipv6_cache
{
    DWORD adapter_index;
    BYTE addr[16];
    DWORD prefixlength;
};

static gate_bool_t notify_cached_ipv6_entries(struct ipv6_cache* cache, DWORD cache_length, DWORD index, gate_netconfig_address_t* ptr_target, gate_netcfg_enum_addresses_callback_t cb, void* userparam)
{
    gate_bool_t ret = true;
    DWORD n;
    struct ipv6_cache* entry;
    gate_strbuilder_t builder;

    for (n = 0; ret && (n != cache_length); ++n)
    {
        entry = &cache[n];
        if (entry->adapter_index != index)
        {
            continue;
        }
        gate_mem_clear(ptr_target, sizeof(gate_netconfig_address_t));
        gate_strbuilder_create_static(&builder, ptr_target->address, sizeof(ptr_target->address), 0);
        gate_strbuilder_append(&builder,
            GATE_PRINT_CSTR, "[", GATE_PRINT_H8, (entry->addr[0] & 0xff), GATE_PRINT_H8, (entry->addr[1] & 0xff),
            GATE_PRINT_CSTR, ":", GATE_PRINT_H8, (entry->addr[2] & 0xff), GATE_PRINT_H8, (entry->addr[3] & 0xff),
            GATE_PRINT_CSTR, ":", GATE_PRINT_H8, (entry->addr[4] & 0xff), GATE_PRINT_H8, (entry->addr[5] & 0xff),
            GATE_PRINT_CSTR, ":", GATE_PRINT_H8, (entry->addr[6] & 0xff), GATE_PRINT_H8, (entry->addr[7] & 0xff),
            GATE_PRINT_CSTR, ":", GATE_PRINT_H8, (entry->addr[8] & 0xff), GATE_PRINT_H8, (entry->addr[9] & 0xff),
            GATE_PRINT_CSTR, ":", GATE_PRINT_H8, (entry->addr[10] & 0xff), GATE_PRINT_H8, (entry->addr[11] & 0xff),
            GATE_PRINT_CSTR, ":", GATE_PRINT_H8, (entry->addr[12] & 0xff), GATE_PRINT_H8, (entry->addr[13] & 0xff),
            GATE_PRINT_CSTR, ":", GATE_PRINT_H8, (entry->addr[14] & 0xff), GATE_PRINT_H8, (entry->addr[15] & 0xff),
            GATE_PRINT_CSTR, "]", GATE_PRINT_END);

        if (entry->prefixlength)
        {
            gate_strbuilder_create_static(&builder, ptr_target->mask, sizeof(ptr_target->mask), 0);
            gate_strbuilder_append_uint32(&builder, entry->prefixlength);
        }
        ptr_target->addrtype = GATE_NETCONFIG_ADDRTYPE_HOSTIP;

        if (cb)
        {
            ret = cb(ptr_target, userparam);
        }
    }
    return ret;
}


/* minGW-32 does not support IPv6 headers */
typedef struct gate_in6_addr
{
    union {
        UCHAR	Byte[16];
        USHORT	Word[8];
    } u;
} GATE_IN6_ADDR;

#ifndef in_addr6
#define in_addr6 in6_addr
#endif

typedef struct gate_sockaddr_in6
{
    short	sin6_family;
    USHORT	sin6_port;
    ULONG	sin6_flowinfo;
    struct gate_in6_addr sin6_addr;
    ULONG	sin6_scope_id;
} gate_sockaddr_in6_t;

#ifndef _S6_un
#define _S6_un	u
#endif 

#ifndef _S6_u8
#define _S6_u8	Byte
#endif

#ifndef s6_addr
#define s6_addr	_S6_un._S6_u8
#endif


gate_result_t gate_netconfig_enum_addresses(gate_netconfig_nif_t const* nif, gate_netcfg_enum_addresses_callback_t cb, void* userparam)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    PMIB_IPADDRTABLE ptr_ipaddrtable = NULL;
    PMIB_IPADDRROW ptr_ipaddrrow = NULL;
    PIP_ADAPTER_INFO ptr_adapter_info = NULL;
    PIP_ADAPTER_INFO ptr_adapter;
    PIP_ADAPTER_ADDRESSES ptr_adapter_addrs = NULL;
    PIP_ADAPTER_ADDRESSES ptr_addrs = NULL;
    PIP_ADAPTER_UNICAST_ADDRESS ptr_uni_addr;
    ULONG buffer_size;
    ULONG flags;
    DWORD errcode;
    DWORD ndx;
    gate_netconfig_address_t addr;
    gate_bool_t continue_enum = true;
    DWORD handled_indexes[512];
    DWORD handled_indexes_count = 0;
    struct ipv6_cache ipv6[64];
    DWORD ipv6_count = 0;
    struct gate_sockaddr_in6* ptr_sin6;
    struct ipv6_cache* ipv6_entry;
    gate_size_t n;

    do
    {
        ret = load_iphlpapi();
        GATE_BREAK_IF_FAILED(ret);

        if (iphlp.GetAdaptersAddresses && continue_enum)
        {
            /* try windows XP+ API for IPv6 adapters only */
            flags = GAA_FLAG_INCLUDE_PREFIX /*| GAA_FLAG_SKIP_ANYCAST*/ | GAA_FLAG_SKIP_FRIENDLY_NAME | GAA_FLAG_SKIP_MULTICAST;
            buffer_size = sizeof(IP_ADAPTER_ADDRESSES);
            ptr_adapter_addrs = (PIP_ADAPTER_ADDRESSES)gate_mem_alloc(buffer_size);
            if (ptr_adapter_addrs == NULL)
            {
                ret = GATE_RESULT_OUTOFMEMORY;
                break;
            }

            errcode = iphlp.GetAdaptersAddresses(AF_INET6, flags, NULL, ptr_adapter_addrs, &buffer_size);
            if (ERROR_BUFFER_OVERFLOW == errcode)
            {
                buffer_size += 1024;
                ptr_adapter_addrs = (PIP_ADAPTER_ADDRESSES)gate_mem_realloc(ptr_adapter_addrs, buffer_size);
                if (ptr_adapter_addrs == NULL)
                {
                    ret = GATE_RESULT_OUTOFMEMORY;
                    break;
                }
                errcode = iphlp.GetAdaptersAddresses(AF_INET6, flags, NULL, ptr_adapter_addrs, &buffer_size);
            }
            if (errcode != ERROR_SUCCESS)
            {
                ret = GATE_RESULT_FAILED;
            }
            else
            {
                ret = GATE_RESULT_OK;
                ptr_addrs = ptr_adapter_addrs;
                for (; continue_enum && (ptr_addrs != NULL); ptr_addrs = ptr_addrs->Next)
                {
                    ndx = (ptr_addrs->IfIndex != 0) ? ptr_addrs->IfIndex : ptr_addrs->Ipv6IfIndex;
                    if (nif && (nif->index != ndx))
                    {
                        /* adapter index was not queried */
                        continue;
                    }
                    ptr_uni_addr = ptr_addrs->FirstUnicastAddress;
                    while (ptr_uni_addr)
                    {
                        switch (ptr_uni_addr->Address.lpSockaddr->sa_family)
                        {
                        case AF_INET6:
                        {
                            /* add ipV6 data to cache */
                            ptr_sin6 = (struct gate_sockaddr_in6*)ptr_uni_addr->Address.lpSockaddr;
                            ipv6_entry = &ipv6[ipv6_count];
                            ipv6_entry->adapter_index = ndx;
                            for (n = 0; n != 16; ++n)
                            {
                                ipv6_entry->addr[n] = ptr_sin6->sin6_addr.s6_addr[n];
                            }
                            ipv6_entry->prefixlength = ptr_uni_addr->OnLinkPrefixLength;
                            ++ipv6_count;
                            break;
                        }
                        }
                        ptr_uni_addr = ptr_uni_addr->Next;
                    }
                }
            }
        }

        if (iphlp.GetAdaptersInfo && continue_enum)
        {
            /* try Win2K/Win98 API */
            buffer_size = sizeof(IP_ADAPTER_INFO);
            ptr_adapter_info = (PIP_ADAPTER_INFO)gate_mem_alloc(buffer_size);
            if (ptr_adapter_info == NULL)
            {
                ret = GATE_RESULT_OUTOFMEMORY;
                break;
            }
            errcode = iphlp.GetAdaptersInfo(ptr_adapter_info, &buffer_size);
            if (errcode == ERROR_BUFFER_OVERFLOW)
            {
                ptr_adapter_info = (PIP_ADAPTER_INFO)gate_mem_realloc(ptr_adapter_info, buffer_size);
                if (ptr_adapter_info == NULL)
                {
                    ret = GATE_RESULT_OUTOFMEMORY;
                    break;
                }
                errcode = iphlp.GetAdaptersInfo(ptr_adapter_info, &buffer_size);
            }
            if (errcode != ERROR_SUCCESS)
            {
                ret = GATE_RESULT_FAILED;
            }
            else
            {
                ret = GATE_RESULT_OK;
                ptr_adapter = ptr_adapter_info;
                for (; continue_enum && (ptr_adapter != NULL); ptr_adapter = ptr_adapter->Next)
                {
                    if (nif && (nif->index != ptr_adapter->Index))
                    {
                        /* adapter index was not queried */
                        continue;
                    }
                    if (index_found(handled_indexes, handled_indexes_count, ptr_adapter->Index))
                    {
                        /* this nif index was already handled */
                        continue;
                    }

                    handled_indexes[handled_indexes_count] = ptr_adapter->Index;
                    ++handled_indexes_count;

                    if (cb && continue_enum)
                    {
                        /* take IP address: */
                        continue_enum = notify_all_addr_strings(&addr, &ptr_adapter->IpAddressList, true, GATE_NETCONFIG_ADDRTYPE_HOSTIP, cb, userparam);
                        if (continue_enum)
                        {
                            continue_enum = notify_all_addr_strings(&addr, &ptr_adapter->GatewayList, false, GATE_NETCONFIG_ADDRTYPE_GATEWAY, cb, userparam);
                            if (continue_enum)
                            {
                                continue_enum = notify_cached_ipv6_entries(ipv6, ipv6_count, ptr_adapter->Index, &addr, cb, userparam);
                            }
                        }
                    }
                }
            }
        }

        if (iphlp.GetIpAddrTable && continue_enum)
        {
            /* try NT4 API */

            buffer_size = sizeof(MIB_IPADDRTABLE);
            ptr_ipaddrtable = (PMIB_IPADDRTABLE)gate_mem_alloc(buffer_size);
            if (NULL == ptr_ipaddrtable)
            {
                ret = GATE_RESULT_OUTOFMEMORY;
                break;
            }

            errcode = iphlp.GetIpAddrTable(ptr_ipaddrtable, &buffer_size, FALSE);
            if (errcode == ERROR_INSUFFICIENT_BUFFER)
            {
                buffer_size += 1024;	/* increase the buffer just in case new addresses have been added in parallel */
                ptr_ipaddrtable = (PMIB_IPADDRTABLE)gate_mem_realloc(ptr_ipaddrtable, buffer_size);
                if (NULL == ptr_ipaddrtable)
                {
                    ret = GATE_RESULT_OUTOFMEMORY;
                    break;
                }
                errcode = iphlp.GetIpAddrTable(ptr_ipaddrtable, &buffer_size, FALSE);
            }
            if (errcode != NO_ERROR)
            {
                ret = GATE_RESULT_FAILED;
            }
            else
            {
                ret = GATE_RESULT_OK;
                for (ndx = 0; continue_enum && (ndx != ptr_ipaddrtable->dwNumEntries); ++ndx)
                {
                    ptr_ipaddrrow = &ptr_ipaddrtable->table[ndx];
                    if (nif && nif->index != ptr_ipaddrrow->dwIndex)
                    {
                        /* the entry is not covered by the given net-interface object */
                        continue;
                    }
                    if (index_found(handled_indexes, handled_indexes_count, ptr_ipaddrrow->dwIndex))
                    {
                        /* this nif index was already handled */
                        continue;
                    }

                    if (cb && ipaddrrow_to_netaddrr(ptr_ipaddrrow, &addr))
                    {
                        continue_enum = cb(&addr, userparam);
                    }
                }
            }
        }
        if (!continue_enum)
        {
            break;
        }

    } while (0);

    if (ptr_adapter_addrs)
    {
        gate_mem_dealloc(ptr_adapter_addrs);
    }

    if (ptr_ipaddrtable)
    {
        gate_mem_dealloc(ptr_ipaddrtable);
    }
    if (ptr_adapter_info)
    {
        gate_mem_dealloc(ptr_adapter_info);
    }

    return ret;
}

gate_result_t gate_netconfig_enable_nif(gate_netconfig_nif_t const* nif, gate_bool_t enabled)
{
    GATE_UNUSED_ARG(nif);
    GATE_UNUSED_ARG(enabled);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_netconfig_setup_nif_addresses(gate_netconfig_nif_t const* nif, gate_netconfig_address_t const* addresses, gate_size_t addresses_count)
{
    GATE_UNUSED_ARG(nif);
    GATE_UNUSED_ARG(addresses);
    GATE_UNUSED_ARG(addresses_count);
    return GATE_RESULT_NOTIMPLEMENTED;
}

#endif /* GATE_SYSTEM_NETCONFIG_WINAPI_IMPL */


#if defined(GATE_SYSTEM_NETCONFIG_POSIX_IMPL)

#include "gate/strings.h"
#include "gate/platforms.h"

#include <unistd.h>
#include <dlfcn.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/route.h>

#if !defined(GATE_SYS_ANDROID)
#	include <ifaddrs.h>
#else
struct ifaddrs
{
    struct ifaddrs* ifa_next;
    char* ifa_name;
    unsigned int ifa_flags;
    struct sockaddr* ifa_addr;
    struct sockaddr* ifa_netmask;
    union {
        struct sockaddr* ifu_broadaddr;
        struct sockaddr* ifu_dstaddr;
    } ifa_ifu;
    void* ifa_data;
};
#endif

#if defined(GATE_SYS_LINUX)
#	include <linux/netdevice.h>
#endif
#if defined(GATE_SYS_BSD)
#	include <sys/types.h>
#	include <sys/sysctl.h>
#endif

typedef int(*getifaddrs_func_type)(struct ifaddrs** ifap);
typedef void(*freeifaddrs_func_type)(struct ifaddrs* ifa);

typedef unsigned int (*if_nametoindex_func_type)(const char* ifname);
typedef char* (*if_indextoname_func_type)(unsigned int ifindex, char* ifname);

static getifaddrs_func_type getifaddrs_func = NULL;
static freeifaddrs_func_type freeifaddrs_func = NULL;
static if_nametoindex_func_type if_nametoindex_func = NULL;
static if_indextoname_func_type if_indextoname_func = NULL;

static void load_if_support_functions()
{
    getifaddrs_func = (getifaddrs_func_type)gate_posix_global_sym("getifaddrs");
    freeifaddrs_func = (freeifaddrs_func_type)gate_posix_global_sym("freeifaddrs");
    if_nametoindex_func = (if_nametoindex_func_type)gate_posix_global_sym("if_nametoindex");
    if_indextoname_func = (if_indextoname_func_type)gate_posix_global_sym("if_indextoname");
}

static int invoke_getifaddrs(struct ifaddrs** ifap)
{
    load_if_support_functions();
    if (!getifaddrs_func)
    {
        return -1;
    }
    return getifaddrs_func(ifap);
}

static unsigned int invoke_if_nametoindex(const char* ifname)
{
    load_if_support_functions();
    if (!if_nametoindex_func)
    {
        return 0;
    }
    return if_nametoindex_func(ifname);
}

static void invoke_freeifaddrs(struct ifaddrs* ifa)
{
    if (freeifaddrs_func && ifa)
    {
        freeifaddrs_func(ifa);
    }
}

static gate_bool_t run_ifreq(int sockfd, struct ifreq* ptr_req, char const* if_name, gate_size_t if_name_len, unsigned long request_id)
{
    gate_mem_clear(ptr_req, sizeof(struct ifreq));
    gate_str_print_text(ptr_req->ifr_name, sizeof(ptr_req->ifr_name), if_name, if_name_len);
    return (-1 != ioctl(sockfd, request_id, ptr_req));
}

static int get_if_flags(int sockfd, char const* if_name, gate_size_t if_name_len)
{
    int ret = 0;
    struct ifreq req;
    if (run_ifreq(sockfd, &req, if_name, if_name_len, SIOCGIFFLAGS))
    {
        ret = req.ifr_flags;
    }
    return ret;
}

static gate_bool_t get_if_hardware_info(int sockfd, char const* if_name, gate_size_t if_name_len, char* ptr_mac, gate_size_t mac_len, gate_enumint_t* ptr_type)
{
    struct ifreq req;
    gate_strbuilder_t builder;
    gate_uint8_t const* ptr_mac_bytes;<--- Unused variable: ptr_mac_bytes

#if defined(GATE_SYS_LINUX)
    if (run_ifreq(sockfd, &req, if_name, if_name_len, SIOCGIFHWADDR))
    {
        if (ptr_type)
        {
            switch (req.ifr_hwaddr.sa_family)
            {
            case ARPHRD_LOOPBACK:	*ptr_type = GATE_NETCONFIG_TYPE_LOOPBACK; break;
            case ARPHRD_ETHER:
            case ARPHRD_EETHER:		*ptr_type = GATE_NETCONFIG_TYPE_ETHERNET; break;
            case ARPHRD_PPP:		*ptr_type = GATE_NETCONFIG_TYPE_PPP; break;
            case ARPHRD_IEEE80211:	*ptr_type = GATE_NETCONFIG_TYPE_WLAN; break;
            default:				*ptr_type = GATE_NETCONFIG_TYPE_UNKNOWN; break;
            }
        }
        if (ptr_mac)
        {
            ptr_mac_bytes = (gate_uint8_t const*)&req.ifr_hwaddr.sa_data;
            gate_strbuilder_create_static(&builder, ptr_mac, mac_len, 0);
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[0], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[1], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[2], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[3], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[4], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[5], 1, false);
        }
        return true;
    }
#endif
#if defined(GATE_SYS_BSD)
    do
    {
        int sysctlparam[6] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, 0 };
        size_t needed = 0;
        char buf[1024];
        struct if_msghdr* msghdr = NULL;
        sysctlparam[5] = invoke_if_nametoindex(if_name);
        if (sysctlparam[5] == 0)
        {
            break;
        }
        if (sysctl(sysctlparam, 6, NULL, &needed, NULL, 0) < 0)
        {
            break;
        }
        if (sysctl(sysctlparam, 6, buf, &needed, NULL, 0) < 0)
        {
            break;
        }
        msghdr = (struct if_msghdr*)buf;

        if (ptr_type)
        {
            *ptr_type = GATE_NETCONFIG_TYPE_ETHERNET;
        }
        if (ptr_mac)
        {
            ptr_mac_bytes = (gate_uint8_t const*)msghdr;
            gate_strbuilder_create_static(&builder, ptr_mac, mac_len, 0);
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[0], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[1], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[2], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[3], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[4], 1, false);
            gate_strbuilder_append_chars(&builder, 1, ':');
            gate_strbuilder_append_hex(&builder, &ptr_mac_bytes[5], 1, false);
        }

        return true;
    } while (0);

#endif 
    return false;
}

static gate_enumint_t get_status_from_ifaddrs_list(struct ifaddrs** ptr_ifaddrs_list, gate_size_t list_count, char const* if_name, gate_size_t if_name_len, gate_bool_t remove_entry)
{
    gate_enumint_t ret = GATE_NETCONFIG_STATUS_UNKNOWN;
    gate_size_t ndx = 0;
    gate_size_t len;
    for (ndx = 0; ndx != list_count; ++ndx)
    {
        if (!ptr_ifaddrs_list[ndx])
        {
            continue;
        }
        len = gate_str_length(ptr_ifaddrs_list[ndx]->ifa_name);
        if (0 == gate_str_compare(if_name, if_name_len, ptr_ifaddrs_list[ndx]->ifa_name, len))
        {
            /* interface found */
            if (GATE_FLAG_ENABLED(ptr_ifaddrs_list[ndx]->ifa_flags, IFF_UP))
            {
                ret = GATE_NETCONFIG_STATUS_ENABLED;
            }
            else if (ret != GATE_NETCONFIG_STATUS_ENABLED)
            {
                ret = GATE_NETCONFIG_STATUS_DISABLED;
            }

            if (remove_entry)
            {
                ptr_ifaddrs_list[ndx] = NULL;
            }
        }
    }
    return ret;
}

gate_result_t gate_netconfig_enum_nifs(gate_netcfg_enum_nif_callback_t cb, void* userparam)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    int sockfd = -1;
    struct ifconf ifc = GATE_INIT_EMPTY;
    struct ifreq* ptr_ifr;
    struct ifreq* ptr_ifr_end;
    char buffer[8192];
    char const* if_name;
    gate_size_t if_name_len;
    gate_size_t counter;
    int result;
    int if_flags;
    gate_netconfig_nif_t nif_entry;
    struct ifaddrs* all_ifaddrs = NULL;
    struct ifaddrs* ptr_ifaddrs = NULL;
    struct ifaddrs* ifaddrs_lists[64] = GATE_INIT_EMPTY;
    gate_size_t ifaddrs_count = 0;
    gate_size_t ndx;
    gate_bool_t continue_iteration = true;

    do
    {
        result = invoke_getifaddrs(&all_ifaddrs);
        if (result == 0)
        {
            ptr_ifaddrs = all_ifaddrs;
            while (ptr_ifaddrs)
            {
                if (ifaddrs_count >= sizeof(ifaddrs_lists) / sizeof(ifaddrs_lists[0]))
                {
                    break;
                }
                ifaddrs_lists[ifaddrs_count] = ptr_ifaddrs;
                ++ifaddrs_count;
                ptr_ifaddrs = ptr_ifaddrs->ifa_next;
            }
        }

        sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd == -1)
        {
            ret = GATE_RESULT_FAILED;
            break;
        }

        ifc.ifc_len = sizeof(buffer);
        ifc.ifc_buf = buffer;

        result = ioctl(sockfd, SIOCGIFCONF, &ifc);
        if (result == -1)
        {
            ret = GATE_RESULT_FAILED;
            break;
        }

        if (!cb)
        {
            ret = GATE_RESULT_OK;
            break;
        }

        ptr_ifr = ifc.ifc_req;
        ptr_ifr_end = ptr_ifr + (ifc.ifc_len / sizeof(struct ifreq));
        counter = 1;
        for (; (ptr_ifr < ptr_ifr_end) && continue_iteration; ++ptr_ifr)
        {
            gate_mem_clear(&nif_entry, sizeof(nif_entry));

            if_name = ptr_ifr->ifr_name;
            if_name_len = gate_str_length(if_name);
            gate_str_print_text(nif_entry.name, sizeof(nif_entry.name), if_name, if_name_len);
            gate_str_print_text(nif_entry.uid, sizeof(nif_entry.uid), if_name, if_name_len);

            nif_entry.status = get_status_from_ifaddrs_list(ifaddrs_lists, ifaddrs_count, if_name, if_name_len, true);
            nif_entry.index = counter++;

            if_flags = get_if_flags(sockfd, if_name, if_name_len);
            if (GATE_FLAG_ENABLED(if_flags, IFF_LOOPBACK))
            {
                nif_entry.type = GATE_NETCONFIG_TYPE_LOOPBACK;
                nif_entry.status = GATE_NETCONFIG_STATUS_ENABLED;
            }
            else
            {
                get_if_hardware_info(sockfd, if_name, if_name_len, nif_entry.address, sizeof(nif_entry.address), &nif_entry.type);
            }

            continue_iteration = cb(&nif_entry, userparam);
        }

        for (ndx = 0; (ndx != ifaddrs_count) && continue_iteration; ++ndx)
        {
            if (!ifaddrs_lists[ndx])
            {
                continue;
            }

            gate_mem_clear(&nif_entry, sizeof(nif_entry));

            if_name = ifaddrs_lists[ndx]->ifa_name;
            if_name_len = gate_str_length(if_name);
            gate_str_print_text(nif_entry.name, sizeof(nif_entry.name), if_name, if_name_len);
            gate_str_print_text(nif_entry.uid, sizeof(nif_entry.uid), if_name, if_name_len);

            nif_entry.status = GATE_FLAG_ENABLED(ifaddrs_lists[ndx]->ifa_flags, IFF_UP)
                ? GATE_NETCONFIG_STATUS_ENABLED : GATE_NETCONFIG_STATUS_DISABLED;
            nif_entry.index = counter++;

            if (sockfd != -1)
            {
                get_if_hardware_info(sockfd, if_name, if_name_len, nif_entry.address, sizeof(nif_entry.address), &nif_entry.type);
            }

            continue_iteration = cb(&nif_entry, userparam);
        }

        ret = GATE_RESULT_OK;
    } while (0);

    if (sockfd != -1)
    {
        close(sockfd);
    }

    invoke_freeifaddrs(all_ifaddrs);

    return ret;
}

static void print_ipv4(char* buffer, gate_size_t buffer_len, struct sockaddr_in* in4)
{
    gate_strbuilder_t builder;
    uint32_t ip4 = ntohl(in4->sin_addr.s_addr);

    gate_strbuilder_create_static(&builder, buffer, buffer_len, 0);
    gate_strbuilder_append(&builder,
        GATE_PRINT_UI8, ((ip4 >> 24) & 0xff), GATE_PRINT_CSTR, ".",
        GATE_PRINT_UI8, ((ip4 >> 16) & 0xff), GATE_PRINT_CSTR, ".",
        GATE_PRINT_UI8, ((ip4 >> 8) & 0xff), GATE_PRINT_CSTR, ".",
        GATE_PRINT_UI8, ((ip4) & 0xff), GATE_PRINT_END);
}

static void print_ipv6(char* buffer, gate_size_t buffer_len, struct sockaddr_in6* in6)
{
    gate_strbuilder_t builder;
    unsigned char const* ptr = (unsigned char const*)in6->sin6_addr.s6_addr;
    gate_strbuilder_create_static(&builder, buffer, buffer_len, 0);

    gate_strbuilder_append(&builder,
        GATE_PRINT_CSTR, "[", GATE_PRINT_H8, ptr[0], GATE_PRINT_H8, ptr[1],
        GATE_PRINT_CSTR, ":", GATE_PRINT_H8, ptr[2], GATE_PRINT_H8, ptr[3],
        GATE_PRINT_CSTR, ":", GATE_PRINT_H8, ptr[4], GATE_PRINT_H8, ptr[5],
        GATE_PRINT_CSTR, ":", GATE_PRINT_H8, ptr[6], GATE_PRINT_H8, ptr[7],
        GATE_PRINT_CSTR, ":", GATE_PRINT_H8, ptr[8], GATE_PRINT_H8, ptr[9],
        GATE_PRINT_CSTR, ":", GATE_PRINT_H8, ptr[10], GATE_PRINT_H8, ptr[11],
        GATE_PRINT_CSTR, ":", GATE_PRINT_H8, ptr[12], GATE_PRINT_H8, ptr[13],
        GATE_PRINT_CSTR, ":", GATE_PRINT_H8, ptr[14], GATE_PRINT_H8, ptr[15],
        GATE_PRINT_CSTR, "]", GATE_PRINT_END);
}


gate_result_t gate_netconfig_enum_addresses(gate_netconfig_nif_t const* nif, gate_netcfg_enum_addresses_callback_t cb, void* userparam)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    struct ifaddrs* ptr_ifaddrs = NULL;
    struct ifaddrs* ptr_ifa;
    int result;
    char const* if_name;
    gate_size_t if_name_len;
    gate_netconfig_address_t addr;
    gate_bool_t continue_enum = true;

    do
    {
        result = invoke_getifaddrs(&ptr_ifaddrs);
        if (result == -1)
        {
            ret = GATE_RESULT_FAILED;
            break;
        }

        ret = GATE_RESULT_OK;
        ptr_ifa = ptr_ifaddrs;<--- Variable 'ptr_ifa' is reassigned a value before the old one has been used.
        for (ptr_ifa = ptr_ifaddrs; continue_enum && (ptr_ifa != NULL); ptr_ifa = ptr_ifa->ifa_next)<--- Variable 'ptr_ifa' is reassigned a value before the old one has been used.
        {
            if (0 != gate_str_comp(ptr_ifa->ifa_name, nif->uid))
            {
                continue;
            }
            switch (ptr_ifa->ifa_addr->sa_family)
            {
            case AF_INET:
            {
                gate_mem_clear(&addr, sizeof(addr));
                print_ipv4(addr.address, sizeof(addr.address), (struct sockaddr_in*)ptr_ifa->ifa_addr);
                print_ipv4(addr.mask, sizeof(addr.mask), (struct sockaddr_in*)ptr_ifa->ifa_netmask);
                addr.addrtype = GATE_NETCONFIG_ADDRTYPE_HOSTIP;
                break;
            }
            case AF_INET6:
            {
                gate_mem_clear(&addr, sizeof(addr));
                print_ipv6(addr.address, sizeof(addr.address), (struct sockaddr_in6*)ptr_ifa->ifa_addr);
                addr.addrtype = GATE_NETCONFIG_ADDRTYPE_HOSTIP;
                break;
            }
            default:
            {
                continue;
                break;
            }
            }
            if (cb)
            {
                continue_enum = cb(&addr, userparam);
            }
        }

    } while (0);

    if (ptr_ifaddrs)
    {
        invoke_freeifaddrs(ptr_ifaddrs);
    }
    return ret;
}

gate_result_t gate_netconfig_enable_nif(gate_netconfig_nif_t const* nif, gate_bool_t enabled)
{
    GATE_UNUSED_ARG(nif);
    GATE_UNUSED_ARG(enabled);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_netconfig_setup_nif_addresses(gate_netconfig_nif_t const* nif, gate_netconfig_address_t const* addresses, gate_size_t addresses_count)
{
    GATE_UNUSED_ARG(nif);
    GATE_UNUSED_ARG(addresses);
    GATE_UNUSED_ARG(addresses_count);
    return GATE_RESULT_NOTIMPLEMENTED;
}

#endif /* GATE_SYSTEM_NETCONFIG_POSIX_IMPL */




#if defined(GATE_SYSTEM_NETCONFIG_NO_IMPL)

gate_result_t gate_netconfig_enum_nifs(gate_netcfg_enum_nif_callback_t cb, void* userparam)
{
    GATE_UNUSED_ARG(cb);
    GATE_UNUSED_ARG(userparam);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_netconfig_enum_addresses(gate_netconfig_nif_t const* nif, gate_netcfg_enum_addresses_callback_t cb, void* userparam)
{
    GATE_UNUSED_ARG(nif);
    GATE_UNUSED_ARG(cb);
    GATE_UNUSED_ARG(userparam);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_netconfig_enable_nif(gate_netconfig_nif_t const* nif, gate_bool_t enabled)
{
    GATE_UNUSED_ARG(nif);
    GATE_UNUSED_ARG(enabled);
    return GATE_RESULT_NOTIMPLEMENTED;
}

gate_result_t gate_netconfig_setup_nif_addresses(gate_netconfig_nif_t const* nif, gate_netconfig_address_t const* addresses, gate_size_t addresses_count)
{
    GATE_UNUSED_ARG(nif);
    GATE_UNUSED_ARG(addresses);
    GATE_UNUSED_ARG(addresses_count);
    return GATE_RESULT_NOTIMPLEMENTED;
}

#endif /* GATE_SYSTEM_NETCONFIG_NO_IMPL */