Welcome to mirror list, hosted at ThFree Co, Russian Federation.

pal_networking.c « System.Native « Unix « Native « libraries « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 2e819aaa5c455f06d78d589cf9487f7e9e98e123 (plain)
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
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#include "pal_config.h"
#include "pal_networking.h"
#include "pal_io.h"
#include "pal_safecrt.h"
#include "pal_utilities.h"
#include <pal_networking_common.h>
#include <fcntl.h>

#include <stdlib.h>
#include <limits.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <assert.h>
#include <sys/time.h>
#if HAVE_EPOLL
#include <sys/epoll.h>
#elif HAVE_KQUEUE
#include <sys/types.h>
#include <sys/event.h>
#elif HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
#if HAVE_SYS_PROCINFO_H
#include <sys/proc_info.h>
#include <libproc.h>
#endif
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <net/if.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#if HAVE_SYS_SOCKIO_H
#include <sys/sockio.h>
#endif
#include <sys/un.h>
#if defined(__APPLE__) && __APPLE__
#include <sys/socketvar.h>
#endif
#if !HAVE_GETDOMAINNAME && HAVE_UTSNAME_DOMAINNAME
#include <sys/utsname.h>
#include <stdio.h>
#endif
#include <unistd.h>
#include <pwd.h>
#if HAVE_SENDFILE_4
#include <sys/sendfile.h>
#elif HAVE_SENDFILE_6
#include <sys/uio.h>
#endif
#if HAVE_GETIFADDRS
#include <ifaddrs.h>
#endif
#if HAVE_LINUX_CAN_H
#include <linux/can.h>
#endif
#if HAVE_SYS_FILIO_H
#include <sys/filio.h>
#endif

#if HAVE_KQUEUE
#if KEVENT_HAS_VOID_UDATA
static void* GetKeventUdata(uintptr_t udata)
{
    return (void*)udata;
}
static uintptr_t GetSocketEventData(void* udata)
{
    return (uintptr_t)udata;
}
#else
static intptr_t GetKeventUdata(uintptr_t udata)
{
    return (intptr_t)udata;
}
static uintptr_t GetSocketEventData(intptr_t udata)
{
    return (uintptr_t)udata;
}
#endif
#if KEVENT_REQUIRES_INT_PARAMS
static int GetKeventNchanges(int nchanges)
{
    return nchanges;
}
static int16_t GetKeventFilter(int16_t filter)
{
    return filter;
}
static uint16_t GetKeventFlags(uint16_t flags)
{
    return flags;
}
#else
static size_t GetKeventNchanges(int nchanges)
{
    return (size_t)nchanges;
}
static int16_t GetKeventFilter(uint32_t filter)
{
    return (int16_t)filter;
}
static uint16_t GetKeventFlags(uint32_t flags)
{
    return (uint16_t)flags;
}
#endif
#endif

#if !HAVE_IN_PKTINFO
// On platforms, such as FreeBSD, where in_pktinfo
// is not available, fallback to custom definition
// with required members.
struct in_pktinfo
{
    struct in_addr ipi_addr;
};
#define IP_PKTINFO IP_RECVDSTADDR
#endif

#if !defined(IPV6_ADD_MEMBERSHIP) && defined(IPV6_JOIN_GROUP)
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#endif

#if !defined(IPV6_DROP_MEMBERSHIP) && defined(IPV6_LEAVE_GROUP)
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif

enum
{
#if defined(__APPLE__) && __APPLE__
    LINGER_OPTION_NAME = SO_LINGER_SEC
#else
    LINGER_OPTION_NAME = SO_LINGER,
#endif
};

enum
{
    INET6_ADDRSTRLEN_MANAGED = 65 // Managed code has a longer max IPv6 string length
};

c_static_assert(GetHostErrorCodes_HOST_NOT_FOUND == HOST_NOT_FOUND);
c_static_assert(GetHostErrorCodes_TRY_AGAIN == TRY_AGAIN);
c_static_assert(GetHostErrorCodes_NO_RECOVERY == NO_RECOVERY);
c_static_assert(GetHostErrorCodes_NO_DATA == NO_DATA);
c_static_assert(GetHostErrorCodes_NO_ADDRESS == NO_ADDRESS);
c_static_assert(sizeof(uint8_t) == sizeof(char)); // We make casts from uint8_t to char so make sure it's legal

// sizeof_member(struct foo, bar) is not valid C++.
// The fix is to remove struct. That is not valid C.
// Use typedefs to make it valid C -- which are redundant but valid C++.
typedef struct iovec iovec;
typedef struct sockaddr sockaddr;
typedef struct xsocket xsocket;
typedef struct linger linger;

// We require that IOVector have the same layout as iovec.
c_static_assert(sizeof(IOVector) == sizeof(iovec));
c_static_assert(sizeof_member(IOVector, Base) == sizeof_member(iovec, iov_base));
c_static_assert(offsetof(IOVector, Base) == offsetof(iovec, iov_base));
c_static_assert(sizeof_member(IOVector, Count) == sizeof_member(iovec, iov_len));
c_static_assert(offsetof(IOVector, Count) == offsetof(iovec, iov_len));

#define Min(left,right) (((left) < (right)) ? (left) : (right))

static bool TryConvertAddressFamilyPlatformToPal(sa_family_t platformAddressFamily, int32_t* palAddressFamily)
{
    assert(palAddressFamily != NULL);

    switch (platformAddressFamily)
    {
        case AF_UNSPEC:
            *palAddressFamily = AddressFamily_AF_UNSPEC;
            return true;

        case AF_UNIX:
            *palAddressFamily = AddressFamily_AF_UNIX;
            return true;

        case AF_INET:
            *palAddressFamily = AddressFamily_AF_INET;
            return true;

        case AF_INET6:
            *palAddressFamily = AddressFamily_AF_INET6;
            return true;
#ifdef AF_PACKET
        case AF_PACKET:
            *palAddressFamily = AddressFamily_AF_PACKET;
            return true;
#endif
#ifdef AF_CAN
        case AF_CAN:
            *palAddressFamily = AddressFamily_AF_CAN;
            return true;
#endif
        default:
            *palAddressFamily = platformAddressFamily;
            return false;
    }
}

static bool TryConvertAddressFamilyPalToPlatform(int32_t palAddressFamily, sa_family_t* platformAddressFamily)
{
    assert(platformAddressFamily != NULL);

    switch (palAddressFamily)
    {
        case AddressFamily_AF_UNSPEC:
            *platformAddressFamily = AF_UNSPEC;
            return true;

        case AddressFamily_AF_UNIX:
            *platformAddressFamily = AF_UNIX;
            return true;

        case AddressFamily_AF_INET:
            *platformAddressFamily = AF_INET;
            return true;

        case AddressFamily_AF_INET6:
            *platformAddressFamily = AF_INET6;
            return true;
#ifdef AF_PACKET
        case AddressFamily_AF_PACKET:
            *platformAddressFamily = AF_PACKET;
            return true;
#endif
#ifdef AF_CAN
        case AddressFamily_AF_CAN:
            *platformAddressFamily = AF_CAN;
            return true;
#endif
        default:
            *platformAddressFamily = (sa_family_t)palAddressFamily;
            return false;
    }
}

static void ConvertByteArrayToIn6Addr(struct in6_addr* addr, const uint8_t* buffer, int32_t bufferLength)
{
    assert(bufferLength == NUM_BYTES_IN_IPV6_ADDRESS);
    memcpy_s(addr->s6_addr, NUM_BYTES_IN_IPV6_ADDRESS, buffer, (uint32_t)bufferLength);
}

static void ConvertIn6AddrToByteArray(uint8_t* buffer, int32_t bufferLength, const struct in6_addr* addr)
{
    assert(bufferLength == NUM_BYTES_IN_IPV6_ADDRESS);
    memcpy_s(buffer, (uint32_t)bufferLength, addr->s6_addr, NUM_BYTES_IN_IPV6_ADDRESS);
}

static void ConvertByteArrayToSockAddrIn6(struct sockaddr_in6* addr, const uint8_t* buffer, int32_t bufferLength)
{
    ConvertByteArrayToIn6Addr(&addr->sin6_addr, buffer, bufferLength);

    // Mark that this is INET6
    addr->sin6_family = AF_INET6;
}

static void ConvertByteArrayToInAddr(struct in_addr* addr, const uint8_t* buffer, int32_t bufferLength)
{
    assert(bufferLength == NUM_BYTES_IN_IPV4_ADDRESS);
    memcpy_s(&addr->s_addr, NUM_BYTES_IN_IPV4_ADDRESS, buffer, (uint32_t)bufferLength); // Send back in network byte order.
}

static void ConvertInAddrToByteArray(uint8_t* buffer, int32_t bufferLength, const struct in_addr* addr)
{
    assert(bufferLength == NUM_BYTES_IN_IPV4_ADDRESS);
    memcpy_s(buffer, (uint32_t)bufferLength, &addr->s_addr, NUM_BYTES_IN_IPV4_ADDRESS); // Send back in network byte order.
}

static void ConvertByteArrayToSockAddrIn(struct sockaddr_in* addr, const uint8_t* buffer, int32_t bufferLength)
{
    ConvertByteArrayToInAddr(&addr->sin_addr, buffer, bufferLength);

    addr->sin_family = AF_INET;
}

static int32_t ConvertGetAddrInfoAndGetNameInfoErrorsToPal(int32_t error)
{
    switch (error)
    {
        case 0:
            return 0;
        case EAI_AGAIN:
            return GetAddrInfoErrorFlags_EAI_AGAIN;
        case EAI_BADFLAGS:
            return GetAddrInfoErrorFlags_EAI_BADFLAGS;
#ifdef EAI_FAIL
        case EAI_FAIL:
            return GetAddrInfoErrorFlags_EAI_FAIL;
#endif
        case EAI_FAMILY:
            return GetAddrInfoErrorFlags_EAI_FAMILY;
        case EAI_MEMORY:
            return GetAddrInfoErrorFlags_EAI_MEMORY;
        case EAI_NONAME:
#ifdef EAI_NODATA
        case EAI_NODATA:
#endif
            return GetAddrInfoErrorFlags_EAI_NONAME;
    }

    assert_err(0, "Unknown AddrInfo error flag", error);
    return -1;
}

static int32_t CopySockAddrToIPAddress(sockaddr* addr, sa_family_t family, IPAddress* ipAddress)
{
    if (family == AF_INET)
    {
        struct sockaddr_in* inetSockAddr = (struct sockaddr_in*)addr;

        ConvertInAddrToByteArray(ipAddress->Address, NUM_BYTES_IN_IPV4_ADDRESS, &inetSockAddr->sin_addr);
        ipAddress->IsIPv6 = 0;
        return 0;
    }
    else if (family == AF_INET6)
    {
        struct sockaddr_in6* inet6SockAddr = (struct sockaddr_in6*)addr;

        ConvertIn6AddrToByteArray(ipAddress->Address, NUM_BYTES_IN_IPV6_ADDRESS, &inet6SockAddr->sin6_addr);
        ipAddress->IsIPv6 = 1;
        ipAddress->ScopeId = inet6SockAddr->sin6_scope_id;
        return 0;
    }

    return -1;
}

int32_t SystemNative_GetHostEntryForName(const uint8_t* address, int32_t addressFamily, HostEntry* entry)
{
    if (address == NULL || entry == NULL)
    {
        return GetAddrInfoErrorFlags_EAI_BADARG;
    }

    int32_t ret = GetAddrInfoErrorFlags_EAI_SUCCESS;

    struct addrinfo* info = NULL;
#if HAVE_GETIFADDRS
    struct ifaddrs* addrs = NULL;
#endif

    sa_family_t platformFamily;
    if (!TryConvertAddressFamilyPalToPlatform(addressFamily, &platformFamily))
    {
        return GetAddrInfoErrorFlags_EAI_FAMILY;
    }

    struct addrinfo hint;
    memset(&hint, 0, sizeof(struct addrinfo));
    hint.ai_flags = AI_CANONNAME;
    hint.ai_family = platformFamily;

    int result = getaddrinfo((const char*)address, NULL, &hint, &info);
    if (result != 0)
    {
        return ConvertGetAddrInfoAndGetNameInfoErrorsToPal(result);
    }

    entry->CanonicalName = NULL;
    entry->Aliases = NULL;
    entry->IPAddressList = NULL;
    entry->IPAddressCount = 0;

    // Find the canonical name for this host (if any) and count the number of IP end points.
    for (struct addrinfo* ai = info; ai != NULL; ai = ai->ai_next)
    {
        // If we haven't found a canonical name yet and this addrinfo has one, copy it
        if ((entry->CanonicalName == NULL) && (ai->ai_canonname != NULL))
        {
            entry->CanonicalName = (uint8_t*)strdup(ai->ai_canonname);
            if (entry->CanonicalName == NULL)
            {
                ret = ConvertGetAddrInfoAndGetNameInfoErrorsToPal(EAI_MEMORY);
                goto cleanup;
            }
        }

        if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6)
        {
            entry->IPAddressCount++;
        }
    }

#if HAVE_GETIFADDRS
    char name[_POSIX_HOST_NAME_MAX];
    result = gethostname((char*)name, _POSIX_HOST_NAME_MAX);

    bool includeIPv4Loopback = true;
    bool includeIPv6Loopback = true;

    if (result == 0 && strcasecmp((const char*)address, name) == 0)
    {
        // Get all interface addresses if the host name corresponds to the local host.
        result = getifaddrs(&addrs);

        // If getifaddrs fails, just skip it, the data are not crucial for the result.
        if (result == 0)
        {
            // Count the number of IP end points.
            for (struct ifaddrs* ifa = addrs; ifa != NULL; ifa = ifa->ifa_next)
            {
                if (ifa->ifa_addr == NULL)
                {
                    continue;
                }

                // Skip the interface if it isn't UP.
                if ((ifa->ifa_flags & IFF_UP) == 0)
                {
                    continue;
                }

                if (ifa->ifa_addr->sa_family == AF_INET)
                {
                    // Remember if there's at least one non-loopback address for IPv4, so that they will be skipped.
                    if ((ifa->ifa_flags & IFF_LOOPBACK) == 0)
                    {
                        includeIPv4Loopback = false;
                    }

                    entry->IPAddressCount++;
                }
                else if (ifa->ifa_addr->sa_family == AF_INET6)
                {
                    // Remember if there's at least one non-loopback address for IPv6, so that they will be skipped.
                    if ((ifa->ifa_flags & IFF_LOOPBACK) == 0)
                    {
                        includeIPv6Loopback = false;
                    }

                    entry->IPAddressCount++;
                }
            }
        }
    }
#endif

    if (entry->IPAddressCount > 0)
    {
        entry->IPAddressList = (IPAddress*)calloc((size_t)entry->IPAddressCount, sizeof(IPAddress));
        if (entry->IPAddressList == NULL)
        {
            ret = ConvertGetAddrInfoAndGetNameInfoErrorsToPal(EAI_MEMORY);
            goto cleanup;
        }

        IPAddress* ipAddressList = entry->IPAddressList;

        for (struct addrinfo* ai = info; ai != NULL; ai = ai->ai_next)
        {
            if (CopySockAddrToIPAddress(ai->ai_addr, (sa_family_t)ai->ai_family, ipAddressList) == 0)
            {
                ++ipAddressList;
            }
        }

#if HAVE_GETIFADDRS
        if (addrs != NULL)
        {
            for (struct ifaddrs* ifa = addrs; ifa != NULL; ifa = ifa->ifa_next)
            {
                if (ifa->ifa_addr == NULL)
                {
                    continue;
                }

                // Skip the interface if it isn't UP.
                if ((ifa->ifa_flags & IFF_UP) == 0)
                {
                    continue;
                }

                // Skip loopback addresses if at least one interface has non-loopback one.
                if ((!includeIPv4Loopback && ifa->ifa_addr->sa_family == AF_INET && (ifa->ifa_flags & IFF_LOOPBACK) != 0) ||
                    (!includeIPv6Loopback && ifa->ifa_addr->sa_family == AF_INET6 && (ifa->ifa_flags & IFF_LOOPBACK) != 0))
                {
                    entry->IPAddressCount--;
                    continue;
                }

                if (CopySockAddrToIPAddress(ifa->ifa_addr, ifa->ifa_addr->sa_family, ipAddressList) == 0)
                {
                    ++ipAddressList;
                }
            }
        }
#endif
    }

cleanup:
    if (info != NULL)
    {
        freeaddrinfo(info);
    }

#if HAVE_GETIFADDRS
    if (addrs != NULL)
    {
        freeifaddrs(addrs);
    }
#endif

    // If the returned code is not success, the FreeHostEntry will not be called from the managed code.
    if (ret != GetAddrInfoErrorFlags_EAI_SUCCESS)
    {
        SystemNative_FreeHostEntry(entry);
    }

    return ret;
}

void SystemNative_FreeHostEntry(HostEntry* entry)
{
    if (entry != NULL)
    {
        free(entry->CanonicalName);
        free(entry->IPAddressList);

        entry->CanonicalName = NULL;
        entry->IPAddressList = NULL;
        entry->IPAddressCount = 0;
    }
}

// There were several versions of glibc that had the flags parameter of getnameinfo unsigned
#if HAVE_GETNAMEINFO_SIGNED_FLAGS
typedef int32_t NativeFlagsType;
#else
typedef uint32_t NativeFlagsType;
#endif

static inline NativeFlagsType ConvertGetNameInfoFlagsToNative(int32_t flags)
{
    NativeFlagsType outFlags = 0;
    if ((flags & GetAddrInfoErrorFlags_NI_NAMEREQD) == GetAddrInfoErrorFlags_NI_NAMEREQD)
    {
        outFlags |= NI_NAMEREQD;
    }
    if ((flags & GetAddrInfoErrorFlags_NI_NUMERICHOST) == GetAddrInfoErrorFlags_NI_NUMERICHOST)
    {
        outFlags |= NI_NUMERICHOST;
    }

    return outFlags;
}

int32_t SystemNative_GetNameInfo(const uint8_t* address,
                                 int32_t addressLength,
                                 int8_t isIPv6,
                                 uint8_t* host,
                                 int32_t hostLength,
                                 uint8_t* service,
                                 int32_t serviceLength,
                                 int32_t flags)
{
    assert(address != NULL);
    assert(addressLength > 0);
    assert((host != NULL) || (service != NULL));
    assert((hostLength > 0) || (serviceLength > 0));

    NativeFlagsType nativeFlags = ConvertGetNameInfoFlagsToNative(flags);
    int32_t result;

    if (isIPv6)
    {
        struct sockaddr_in6 addr;
        memset(&addr, 0, sizeof(struct sockaddr_in6));
        ConvertByteArrayToSockAddrIn6(&addr, address, addressLength);
        result = getnameinfo((const struct sockaddr*)&addr,
                             sizeof(struct sockaddr_in6),
                             (char*)host,
                             (uint32_t)hostLength,
                             (char*)service,
                             (uint32_t)serviceLength,
                             (int)nativeFlags);
    }
    else
    {
        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(struct sockaddr_in));
        ConvertByteArrayToSockAddrIn(&addr, address, addressLength);
        result = getnameinfo((const struct sockaddr*)&addr,
                             sizeof(struct sockaddr_in),
                             (char*)host,
                             (uint32_t)hostLength,
                             (char*)service,
                             (uint32_t)serviceLength,
                             (int)nativeFlags);
    }

    return ConvertGetAddrInfoAndGetNameInfoErrorsToPal(result);
}

int32_t SystemNative_GetDomainName(uint8_t* name, int32_t nameLength)
{
    assert(name != NULL);
    assert(nameLength > 0);

#if HAVE_GETDOMAINNAME
#if HAVE_GETDOMAINNAME_SIZET
    size_t namelen = (uint32_t)nameLength;
#else
    int namelen = nameLength;
#endif

    return getdomainname((char*)name, namelen);
#elif HAVE_UTSNAME_DOMAINNAME
    // On Android, there's no getdomainname but we can use uname to fetch the domain name
    // of the current device
    size_t namelen = (uint32_t)nameLength;
    struct utsname  uts;

    // If uname returns an error, bail out.
    if (uname(&uts) == -1)
    {
        return -1;
    }

    // If we don't have enough space to copy the name, bail out.
    if (strlen(uts.domainname) >= namelen)
    {
        errno = EINVAL;
        return -1;
    }

    // Copy the domain name
    SafeStringCopy((char*)name, namelen, uts.domainname);
    return 0;
#else
    // GetDomainName is not supported on this platform.
    errno = ENOTSUP;
    return -1;
#endif
}

int32_t SystemNative_GetHostName(uint8_t* name, int32_t nameLength)
{
    assert(name != NULL);
    assert(nameLength > 0);

    size_t unsignedSize = (uint32_t)nameLength;
    return gethostname((char*)name, unsignedSize);
}

static bool IsInBounds(const void* void_baseAddr, size_t len, const void* void_valueAddr, size_t valueSize)
{
    const uint8_t* baseAddr = (const uint8_t*)void_baseAddr;
    const uint8_t* valueAddr = (const uint8_t*)void_valueAddr;

    return valueAddr >= baseAddr && (valueAddr + valueSize) <= (baseAddr + len);
}

int32_t SystemNative_GetIPSocketAddressSizes(int32_t* ipv4SocketAddressSize, int32_t* ipv6SocketAddressSize)
{
    if (ipv4SocketAddressSize == NULL || ipv6SocketAddressSize == NULL)
    {
        return Error_EFAULT;
    }

    *ipv4SocketAddressSize = sizeof(struct sockaddr_in);
    *ipv6SocketAddressSize = sizeof(struct sockaddr_in6);
    return Error_SUCCESS;
}

int32_t SystemNative_GetAddressFamily(const uint8_t* socketAddress, int32_t socketAddressLen, int32_t* addressFamily)
{
    if (socketAddress == NULL || addressFamily == NULL || socketAddressLen < 0)
    {
        return Error_EFAULT;
    }

    const struct sockaddr* sockAddr = (const struct sockaddr*)socketAddress;
    if (!IsInBounds(sockAddr, (size_t)socketAddressLen, &sockAddr->sa_family, sizeof_member(sockaddr, sa_family)))
    {
        return Error_EFAULT;
    }

    if (!TryConvertAddressFamilyPlatformToPal(sockAddr->sa_family, addressFamily))
    {
        *addressFamily = AddressFamily_AF_UNKNOWN;
    }

    return Error_SUCCESS;
}

int32_t SystemNative_SetAddressFamily(uint8_t* socketAddress, int32_t socketAddressLen, int32_t addressFamily)
{
    struct sockaddr* sockAddr = (struct sockaddr*)socketAddress;
    if (sockAddr == NULL || socketAddressLen < 0 ||
        !IsInBounds(sockAddr, (size_t)socketAddressLen, &sockAddr->sa_family, sizeof_member(sockaddr, sa_family)))
    {
        return Error_EFAULT;
    }

    if (!TryConvertAddressFamilyPalToPlatform(addressFamily, &sockAddr->sa_family))
    {
        return Error_EAFNOSUPPORT;
    }

    return Error_SUCCESS;
}

int32_t SystemNative_GetPort(const uint8_t* socketAddress, int32_t socketAddressLen, uint16_t* port)
{
    if (socketAddress == NULL)
    {
        return Error_EFAULT;
    }

    const struct sockaddr* sockAddr = (const struct sockaddr*)socketAddress;
    if (!IsInBounds(sockAddr, (size_t)socketAddressLen, &sockAddr->sa_family, sizeof_member(sockaddr, sa_family)))
    {
        return Error_EFAULT;
    }

    switch (sockAddr->sa_family)
    {
        case AF_INET:
        {
            if (socketAddressLen < 0 || (size_t)socketAddressLen < sizeof(struct sockaddr_in))
            {
                return Error_EFAULT;
            }

            *port = ntohs(((const struct sockaddr_in*)socketAddress)->sin_port);
            return Error_SUCCESS;
        }

        case AF_INET6:
        {
            if (socketAddressLen < 0 || (size_t)socketAddressLen < sizeof(struct sockaddr_in6))
            {
                return Error_EFAULT;
            }

            *port = ntohs(((const struct sockaddr_in6*)socketAddress)->sin6_port);
            return Error_SUCCESS;
        }

        default:
            return Error_EAFNOSUPPORT;
    }
}

int32_t SystemNative_SetPort(uint8_t* socketAddress, int32_t socketAddressLen, uint16_t port)
{
    if (socketAddress == NULL)
    {
        return Error_EFAULT;
    }

    const struct sockaddr* sockAddr = (const struct sockaddr*)socketAddress;
    if (!IsInBounds(sockAddr, (size_t)socketAddressLen, &sockAddr->sa_family, sizeof_member(sockaddr, sa_family)))
    {
        return Error_EFAULT;
    }

    switch (sockAddr->sa_family)
    {
        case AF_INET:
        {
            if (socketAddressLen < 0 || (size_t)socketAddressLen < sizeof(struct sockaddr_in))
            {
                return Error_EFAULT;
            }

            ((struct sockaddr_in*)socketAddress)->sin_port = htons(port);
            return Error_SUCCESS;
        }

        case AF_INET6:
        {
            if (socketAddressLen < 0 || (size_t)socketAddressLen < sizeof(struct sockaddr_in6))
            {
                return Error_EFAULT;
            }

            ((struct sockaddr_in6*)socketAddress)->sin6_port = htons(port);
            return Error_SUCCESS;
        }

        default:
            return Error_EAFNOSUPPORT;
    }
}

int32_t SystemNative_GetIPv4Address(const uint8_t* socketAddress, int32_t socketAddressLen, uint32_t* address)
{
    if (socketAddress == NULL || address == NULL || socketAddressLen < 0 ||
        (size_t)socketAddressLen < sizeof(struct sockaddr_in))
    {
        return Error_EFAULT;
    }

    const struct sockaddr* sockAddr = (const struct sockaddr*)socketAddress;
    if (!IsInBounds(sockAddr, (size_t)socketAddressLen, &sockAddr->sa_family, sizeof_member(sockaddr, sa_family)))
    {
        return Error_EFAULT;
    }

    if (sockAddr->sa_family != AF_INET)
    {
        return Error_EINVAL;
    }

    *address = ((const struct sockaddr_in*)socketAddress)->sin_addr.s_addr;
    return Error_SUCCESS;
}

int32_t SystemNative_SetIPv4Address(uint8_t* socketAddress, int32_t socketAddressLen, uint32_t address)
{
    if (socketAddress == NULL || socketAddressLen < 0 || (size_t)socketAddressLen < sizeof(struct sockaddr_in))
    {
        return Error_EFAULT;
    }

    struct sockaddr* sockAddr = (struct sockaddr*)socketAddress;
    if (!IsInBounds(sockAddr, (size_t)socketAddressLen, &sockAddr->sa_family, sizeof_member(sockaddr, sa_family)))
    {
        return Error_EFAULT;
    }

    if (sockAddr->sa_family != AF_INET)
    {
        return Error_EINVAL;
    }

    struct sockaddr_in* inetSockAddr = (struct sockaddr_in*)sockAddr;

    inetSockAddr->sin_family = AF_INET;
    inetSockAddr->sin_addr.s_addr = address;
    return Error_SUCCESS;
}

int32_t SystemNative_GetIPv6Address(
    const uint8_t* socketAddress, int32_t socketAddressLen, uint8_t* address, int32_t addressLen, uint32_t* scopeId)
{
    if (socketAddress == NULL || address == NULL || scopeId == NULL || socketAddressLen < 0 ||
        (size_t)socketAddressLen < sizeof(struct sockaddr_in6) || addressLen < NUM_BYTES_IN_IPV6_ADDRESS)
    {
        return Error_EFAULT;
    }

    const struct sockaddr* sockAddr = (const struct sockaddr*)socketAddress;
    if (!IsInBounds(sockAddr, (size_t)socketAddressLen, &sockAddr->sa_family, sizeof_member(sockaddr, sa_family)))
    {
        return Error_EFAULT;
    }

    if (sockAddr->sa_family != AF_INET6)
    {
        return Error_EINVAL;
    }

    const struct sockaddr_in6* inet6SockAddr = (const struct sockaddr_in6*)sockAddr;
    ConvertIn6AddrToByteArray(address, addressLen, &inet6SockAddr->sin6_addr);
    *scopeId = inet6SockAddr->sin6_scope_id;

    return Error_SUCCESS;
}

int32_t
SystemNative_SetIPv6Address(uint8_t* socketAddress, int32_t socketAddressLen, uint8_t* address, int32_t addressLen, uint32_t scopeId)
{
    if (socketAddress == NULL || address == NULL || socketAddressLen < 0 ||
        (size_t)socketAddressLen < sizeof(struct sockaddr_in6) || addressLen < NUM_BYTES_IN_IPV6_ADDRESS)
    {
        return Error_EFAULT;
    }

    struct sockaddr* sockAddr = (struct sockaddr*)socketAddress;
    if (!IsInBounds(sockAddr, (size_t)socketAddressLen, &sockAddr->sa_family, sizeof_member(sockaddr, sa_family)))
    {
        return Error_EFAULT;
    }

    if (sockAddr->sa_family != AF_INET6)
    {
        return Error_EINVAL;
    }

    struct sockaddr_in6* inet6SockAddr = (struct sockaddr_in6*)sockAddr;
    ConvertByteArrayToSockAddrIn6(inet6SockAddr, address, addressLen);
    inet6SockAddr->sin6_family = AF_INET6;
    inet6SockAddr->sin6_flowinfo = 0;
    inet6SockAddr->sin6_scope_id = scopeId;

    return Error_SUCCESS;
}

static int8_t IsStreamSocket(int socket)
{
    int type;
    socklen_t length = sizeof(int);
    return getsockopt(socket, SOL_SOCKET, SO_TYPE, &type, &length) == 0
           && type == SOCK_STREAM;
}

static void ConvertMessageHeaderToMsghdr(struct msghdr* header, const MessageHeader* messageHeader, int socket)
{
    // sendmsg/recvmsg can return EMSGSIZE when msg_iovlen is greather than IOV_MAX.
    // We avoid this for stream sockets by truncating msg_iovlen to IOV_MAX. This is ok since sendmsg is
    // not required to send all data and recvmsg can be called again to receive more.
    int iovlen = (int)messageHeader->IOVectorCount;
    if (iovlen > IOV_MAX && IsStreamSocket(socket))
    {
        iovlen = (int)IOV_MAX;
    }
    header->msg_name = messageHeader->SocketAddress;
    header->msg_namelen = (socklen_t)messageHeader->SocketAddressLen;
    header->msg_iov = (struct iovec*)messageHeader->IOVectors;
    header->msg_iovlen = (__typeof__(header->msg_iovlen))iovlen;
    header->msg_control = messageHeader->ControlBuffer;
    header->msg_controllen = (uint32_t)messageHeader->ControlBufferLen;
    header->msg_flags = 0;
}

int32_t SystemNative_GetControlMessageBufferSize(int32_t isIPv4, int32_t isIPv6)
{
    // Note: it is possible that the address family of the socket is neither
    //       AF_INET nor AF_INET6. In this case both inputs will be 0 and
    //       the controll message buffer size should be zero.
    return (isIPv4 != 0 ? CMSG_SPACE(sizeof(struct in_pktinfo)) : 0) + (isIPv6 != 0 ? CMSG_SPACE(sizeof(struct in6_pktinfo)) : 0);
}

static int32_t GetIPv4PacketInformation(struct cmsghdr* controlMessage, IPPacketInformation* packetInfo)
{
    assert(controlMessage != NULL);
    assert(packetInfo != NULL);

    if (controlMessage->cmsg_len < sizeof(struct in_pktinfo))
    {
        assert(false && "expected a control message large enough to hold an in_pktinfo value");
        return 0;
    }

    struct in_pktinfo* pktinfo = (struct in_pktinfo*)CMSG_DATA(controlMessage);
    ConvertInAddrToByteArray(&packetInfo->Address.Address[0], NUM_BYTES_IN_IPV4_ADDRESS, &pktinfo->ipi_addr);
#if HAVE_IN_PKTINFO
    packetInfo->InterfaceIndex = (int32_t)pktinfo->ipi_ifindex;
#elif HAVE_GETIFADDRS
    packetInfo->InterfaceIndex = 0;

    struct ifaddrs* addrs;
    if (getifaddrs(&addrs) == 0)
    {
        struct ifaddrs* addrs_head = addrs;
        while (addrs != NULL)
        {
            if (addrs->ifa_addr->sa_family == AF_INET && ((struct sockaddr_in*)addrs->ifa_addr)->sin_addr.s_addr == pktinfo->ipi_addr.s_addr)
            {
                packetInfo->InterfaceIndex = (int32_t)if_nametoindex(addrs->ifa_name);
                break;
            }
            addrs = addrs->ifa_next;
        }
        freeifaddrs(addrs_head);
    }
#else
    // assume the first interface, we have no other methods
    packetInfo->InterfaceIndex = 0;
#endif

    return 1;
}

static int32_t GetIPv6PacketInformation(struct cmsghdr* controlMessage, IPPacketInformation* packetInfo)
{
    assert(controlMessage != NULL);
    assert(packetInfo != NULL);

    if (controlMessage->cmsg_len < sizeof(struct in6_pktinfo))
    {
        assert(false && "expected a control message large enough to hold an in6_pktinfo value");
        return 0;
    }

    struct in6_pktinfo* pktinfo = (struct in6_pktinfo*)CMSG_DATA(controlMessage);
    ConvertIn6AddrToByteArray(&packetInfo->Address.Address[0], NUM_BYTES_IN_IPV6_ADDRESS, &pktinfo->ipi6_addr);
    packetInfo->Address.IsIPv6 = 1;
    packetInfo->InterfaceIndex = (int32_t)pktinfo->ipi6_ifindex;

    return 1;
}

static struct cmsghdr* GET_CMSG_NXTHDR(struct msghdr* mhdr, struct cmsghdr* cmsg)
{
#ifndef __GLIBC__
// Tracking issue: #6312
// In musl-libc, CMSG_NXTHDR typecasts char* to struct cmsghdr* which causes
// clang to throw sign-compare warning. This is to suppress the warning
// inline.
// There is also a problem in the CMSG_NXTHDR macro in musl-libc.
// It compares signed and unsigned value and clang warns about that.
// So we suppress the warning inline too.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wsign-compare"
#endif
    return CMSG_NXTHDR(mhdr, cmsg);
#ifndef __GLIBC__
#pragma clang diagnostic pop
#endif
}

int32_t
SystemNative_TryGetIPPacketInformation(MessageHeader* messageHeader, int32_t isIPv4, IPPacketInformation* packetInfo)
{
    if (messageHeader == NULL || packetInfo == NULL)
    {
        return 0;
    }

    struct msghdr header;
    ConvertMessageHeaderToMsghdr(&header, messageHeader, -1);

    struct cmsghdr* controlMessage = CMSG_FIRSTHDR(&header);
    if (isIPv4 != 0)
    {
        for (; controlMessage != NULL && controlMessage->cmsg_len > 0;
             controlMessage = GET_CMSG_NXTHDR(&header, controlMessage))
        {
            if (controlMessage->cmsg_level == IPPROTO_IP && controlMessage->cmsg_type == IP_PKTINFO)
            {
                return GetIPv4PacketInformation(controlMessage, packetInfo);
            }
        }
    }
    else
    {
        for (; controlMessage != NULL && controlMessage->cmsg_len > 0;
             controlMessage = GET_CMSG_NXTHDR(&header, controlMessage))
        {
            if (controlMessage->cmsg_level == IPPROTO_IPV6 && controlMessage->cmsg_type == IPV6_PKTINFO)
            {
                return GetIPv6PacketInformation(controlMessage, packetInfo);
            }
        }
    }

    return 0;
}

static int8_t GetMulticastOptionName(int32_t multicastOption, int8_t isIPv6, int* optionName)
{
    switch (multicastOption)
    {
        case MulticastOption_MULTICAST_ADD:
            *optionName = isIPv6 ? IPV6_ADD_MEMBERSHIP : IP_ADD_MEMBERSHIP;
            return true;

        case MulticastOption_MULTICAST_DROP:
            *optionName = isIPv6 ? IPV6_DROP_MEMBERSHIP : IP_DROP_MEMBERSHIP;
            return true;

        case MulticastOption_MULTICAST_IF:
            *optionName = isIPv6 ? IPV6_MULTICAST_IF : IP_MULTICAST_IF;
            return true;

        default:
            return false;
    }
}

int32_t SystemNative_GetIPv4MulticastOption(intptr_t socket, int32_t multicastOption, IPv4MulticastOption* option)
{
    if (option == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int optionName;
    if (!GetMulticastOptionName(multicastOption, 0, &optionName))
    {
        return Error_EINVAL;
    }

#if HAVE_IP_MREQN
    struct ip_mreqn opt;
#else
    struct ip_mreq opt;
#endif
    socklen_t len = sizeof(opt);
    int err = getsockopt(fd, IPPROTO_IP, optionName, &opt, &len);
    if (err != 0)
    {
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    memset(option, 0, sizeof(IPv4MulticastOption));
    option->MulticastAddress = opt.imr_multiaddr.s_addr;
#if HAVE_IP_MREQN
    option->LocalAddress = opt.imr_address.s_addr;
    option->InterfaceIndex = opt.imr_ifindex;
#else
    option->LocalAddress = opt.imr_interface.s_addr;
    option->InterfaceIndex = 0;
#endif
    return Error_SUCCESS;
}

int32_t SystemNative_SetIPv4MulticastOption(intptr_t socket, int32_t multicastOption, IPv4MulticastOption* option)
{
    if (option == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int optionName;
    if (!GetMulticastOptionName(multicastOption, 0, &optionName))
    {
        return Error_EINVAL;
    }

#if HAVE_IP_MREQN
    struct ip_mreqn opt;
    memset(&opt, 0, sizeof(struct ip_mreqn));
    opt.imr_multiaddr.s_addr = option->MulticastAddress;
    opt.imr_address.s_addr = option->LocalAddress;
    opt.imr_ifindex = option->InterfaceIndex;
#else
    struct ip_mreq opt;
    memset(&opt, 0, sizeof(struct ip_mreq));
    opt.imr_multiaddr.s_addr = option->MulticastAddress;
    opt.imr_interface.s_addr = option->LocalAddress;
    if (option->InterfaceIndex != 0)
    {
        return Error_ENOPROTOOPT;
    }
#endif
    int err = setsockopt(fd, IPPROTO_IP, optionName, &opt, sizeof(opt));
    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_GetIPv6MulticastOption(intptr_t socket, int32_t multicastOption, IPv6MulticastOption* option)
{
    if (option == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int optionName;
    if (!GetMulticastOptionName(multicastOption, 1, &optionName))
    {
        return Error_EINVAL;
    }

    struct ipv6_mreq opt;
    socklen_t len = sizeof(opt);
    int err = getsockopt(fd, IPPROTO_IPV6, optionName, &opt, &len);
    if (err != 0)
    {
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    ConvertIn6AddrToByteArray(&option->Address.Address[0], NUM_BYTES_IN_IPV6_ADDRESS, &opt.ipv6mr_multiaddr);
    option->InterfaceIndex = (int32_t)opt.ipv6mr_interface;
    return Error_SUCCESS;
}

int32_t SystemNative_SetIPv6MulticastOption(intptr_t socket, int32_t multicastOption, IPv6MulticastOption* option)
{
    if (option == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int optionName;
    if (!GetMulticastOptionName(multicastOption, 1, &optionName))
    {
        return Error_EINVAL;
    }

    struct ipv6_mreq opt;
    memset(&opt, 0, sizeof(struct ipv6_mreq));

    opt.ipv6mr_interface =
#if IPV6MR_INTERFACE_UNSIGNED
        (unsigned int)option->InterfaceIndex;
#else
        option->InterfaceIndex;
#endif

    ConvertByteArrayToIn6Addr(&opt.ipv6mr_multiaddr, &option->Address.Address[0], NUM_BYTES_IN_IPV6_ADDRESS);

    int err = setsockopt(fd, IPPROTO_IPV6, optionName, &opt, sizeof(opt));
    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

#if defined(__APPLE__) && __APPLE__
static int32_t GetMaxLingerTime(void)
{
    static volatile int32_t MaxLingerTime = -1;
    c_static_assert(sizeof_member(xsocket, so_linger) == 2);

    // OS X does not define the linger time in seconds by default, but in ticks.
    // Furthermore, when SO_LINGER_SEC is used, the value is simply scaled by
    // the number of ticks per second and then the result is used to set the
    // underlying linger time. Unfortunately, the underlying linger time is
    // stored as a `short` and out-of-range values are simply truncated to fit
    // within 16 bits and then reinterpreted as 2's complement signed integers.
    // This results in some *very* strange behavior and a rather low limit for
    // the linger time. Instead of admitting this behavior, we determine the
    // maximum linger time in seconds and return an error if the input is out
    // of range.
    int32_t maxLingerTime = MaxLingerTime;
    if (maxLingerTime == -1)
    {
        long ticksPerSecond = sysconf(_SC_CLK_TCK);
        maxLingerTime = (int32_t)(32767 / ticksPerSecond);
        MaxLingerTime = maxLingerTime;
    }

    return maxLingerTime;
}
#else
static int32_t GetMaxLingerTime(void)
{
    // On other platforms, the maximum linger time is locked to the smaller of
    // 65535 (the maximum time for winsock) and the maximum signed value that
    // will fit in linger::l_linger.

    return Min(65535U, (1U << (sizeof_member(linger, l_linger) * 8 - 1)) - 1);
}
#endif

int32_t SystemNative_GetLingerOption(intptr_t socket, LingerOption* option)
{
    if (option == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    struct linger opt;
    socklen_t len = sizeof(opt);
    int err = getsockopt(fd, SOL_SOCKET, LINGER_OPTION_NAME, &opt, &len);
    if (err != 0)
    {
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    memset(option, 0, sizeof(LingerOption));
    option->OnOff = opt.l_onoff;
    option->Seconds = opt.l_linger;
    return Error_SUCCESS;
}

int32_t SystemNative_SetLingerOption(intptr_t socket, LingerOption* option)
{
    if (option == NULL)
    {
        return Error_EFAULT;
    }

    if (option->OnOff != 0 && (option->Seconds < 0 || option->Seconds > GetMaxLingerTime()))
    {
        return Error_EINVAL;
    }

    int fd = ToFileDescriptor(socket);

    struct linger opt;
    memset(&opt, 0, sizeof(struct linger));
    opt.l_onoff = option->OnOff;
    opt.l_linger = option->Seconds;
    int err = setsockopt(fd, SOL_SOCKET, LINGER_OPTION_NAME, &opt, sizeof(opt));

#if defined(__APPLE__) && __APPLE__
    if (err != 0 && errno == EINVAL)
    {
        // On OSX, SO_LINGER can return EINVAL if the other end of the socket is already closed.
        // In that case, there is nothing for this end of the socket to do, so there's no reason to "linger."
        // Windows and Linux do not return errors in this case, so we'll simulate success on OSX as well.
        err = 0;
    }
#endif

    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

static int32_t SetTimeoutOption(int32_t socket, int32_t millisecondsTimeout, int optionName)
{
    if (millisecondsTimeout < 0)
    {
        return Error_EINVAL;
    }

    struct timeval timeout;
    timeout.tv_sec = millisecondsTimeout / 1000;
    timeout.tv_usec = (millisecondsTimeout % 1000) * 1000;

    int err = setsockopt(socket, SOL_SOCKET, optionName, &timeout, sizeof(timeout));
    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_SetReceiveTimeout(intptr_t socket, int32_t millisecondsTimeout)
{
    return SetTimeoutOption(ToFileDescriptor(socket), millisecondsTimeout, SO_RCVTIMEO);
}

int32_t SystemNative_SetSendTimeout(intptr_t socket, int32_t millisecondsTimeout)
{
    return SetTimeoutOption(ToFileDescriptor(socket), millisecondsTimeout, SO_SNDTIMEO);
}

static int8_t ConvertSocketFlagsPalToPlatform(int32_t palFlags, int* platformFlags)
{
    const int32_t SupportedFlagsMask = SocketFlags_MSG_OOB | SocketFlags_MSG_PEEK | SocketFlags_MSG_DONTROUTE | SocketFlags_MSG_TRUNC | SocketFlags_MSG_CTRUNC;

    if ((palFlags & ~SupportedFlagsMask) != 0)
    {
        return false;
    }

    *platformFlags = ((palFlags & SocketFlags_MSG_OOB) == 0 ? 0 : MSG_OOB) |
                     ((palFlags & SocketFlags_MSG_PEEK) == 0 ? 0 : MSG_PEEK) |
                     ((palFlags & SocketFlags_MSG_DONTROUTE) == 0 ? 0 : MSG_DONTROUTE) |
                     ((palFlags & SocketFlags_MSG_TRUNC) == 0 ? 0 : MSG_TRUNC) |
                     ((palFlags & SocketFlags_MSG_CTRUNC) == 0 ? 0 : MSG_CTRUNC);

    return true;
}

static int32_t ConvertSocketFlagsPlatformToPal(int platformFlags)
{
    const int SupportedFlagsMask = MSG_OOB | MSG_DONTROUTE | MSG_TRUNC | MSG_CTRUNC;

    platformFlags &= SupportedFlagsMask;

    return ((platformFlags & MSG_OOB) == 0 ? 0 : SocketFlags_MSG_OOB) |
           ((platformFlags & MSG_DONTROUTE) == 0 ? 0 : SocketFlags_MSG_DONTROUTE) |
           ((platformFlags & MSG_TRUNC) == 0 ? 0 : SocketFlags_MSG_TRUNC) |
           ((platformFlags & MSG_CTRUNC) == 0 ? 0 : SocketFlags_MSG_CTRUNC);
}

int32_t SystemNative_Receive(intptr_t socket, void* buffer, int32_t bufferLen, int32_t flags, int32_t* received)
{
    if (buffer == NULL || bufferLen < 0 || received == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int socketFlags;
    if (!ConvertSocketFlagsPalToPlatform(flags, &socketFlags))
    {
        return Error_ENOTSUP;
    }

    ssize_t res;
    while ((res = recv(fd, buffer, (size_t)bufferLen, socketFlags)) < 0 && errno == EINTR);

    if (res != -1)
    {
        *received = (int32_t)res;
        return Error_SUCCESS;
    }

    *received = 0;
    return SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_ReceiveMessage(intptr_t socket, MessageHeader* messageHeader, int32_t flags, int64_t* received)
{
    if (messageHeader == NULL || received == NULL || messageHeader->SocketAddressLen < 0 ||
        messageHeader->ControlBufferLen < 0 || messageHeader->IOVectorCount < 0)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int socketFlags;
    if (!ConvertSocketFlagsPalToPlatform(flags, &socketFlags))
    {
        return Error_ENOTSUP;
    }

    struct msghdr header;
    ConvertMessageHeaderToMsghdr(&header, messageHeader, fd);

    ssize_t res;
    while ((res = recvmsg(fd, &header, socketFlags)) < 0 && errno == EINTR);

    assert(header.msg_name == messageHeader->SocketAddress); // should still be the same location as set in ConvertMessageHeaderToMsghdr
    assert(header.msg_control == messageHeader->ControlBuffer);

    assert((int32_t)header.msg_namelen <= messageHeader->SocketAddressLen);
    messageHeader->SocketAddressLen = Min((int32_t)header.msg_namelen, messageHeader->SocketAddressLen);

    assert(header.msg_controllen <= (size_t)messageHeader->ControlBufferLen);
    messageHeader->ControlBufferLen = Min((int32_t)header.msg_controllen, messageHeader->ControlBufferLen);

    messageHeader->Flags = ConvertSocketFlagsPlatformToPal(header.msg_flags);

    if (res != -1)
    {
        *received = res;
        return Error_SUCCESS;
    }

    *received = 0;
    return SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_Send(intptr_t socket, void* buffer, int32_t bufferLen, int32_t flags, int32_t* sent)
{
    if (buffer == NULL || bufferLen < 0 || sent == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int socketFlags;
    if (!ConvertSocketFlagsPalToPlatform(flags, &socketFlags))
    {
        return Error_ENOTSUP;
    }

    ssize_t res;
#if defined(__APPLE__) && __APPLE__
    // possible OSX kernel bug: https://github.com/dotnet/runtime/issues/27221
    while ((res = send(fd, buffer, (size_t)bufferLen, socketFlags)) < 0 && (errno == EINTR || errno == EPROTOTYPE));
#else
    while ((res = send(fd, buffer, (size_t)bufferLen, socketFlags)) < 0 && errno == EINTR);
#endif
    if (res != -1)
    {
        *sent = (int32_t)res;
        return Error_SUCCESS;
    }

    *sent = 0;
    return SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_SendMessage(intptr_t socket, MessageHeader* messageHeader, int32_t flags, int64_t* sent)
{
    if (messageHeader == NULL || sent == NULL || messageHeader->SocketAddressLen < 0 ||
        messageHeader->ControlBufferLen < 0 || messageHeader->IOVectorCount < 0)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int socketFlags;
    if (!ConvertSocketFlagsPalToPlatform(flags, &socketFlags))
    {
        return Error_ENOTSUP;
    }

    struct msghdr header;
    ConvertMessageHeaderToMsghdr(&header, messageHeader, fd);

    ssize_t res;
#if defined(__APPLE__) && __APPLE__
    // possible OSX kernel bug: https://github.com/dotnet/runtime/issues/27221
    while ((res = sendmsg(fd, &header, socketFlags)) < 0 && (errno == EINTR || errno == EPROTOTYPE));
#else
    while ((res = sendmsg(fd, &header, socketFlags)) < 0 && errno == EINTR);
#endif
    if (res != -1)
    {
        *sent = res;
        return Error_SUCCESS;
    }

    *sent = 0;
    return SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_Accept(intptr_t socket, uint8_t* socketAddress, int32_t* socketAddressLen, intptr_t* acceptedSocket)
{
    if (socketAddress == NULL || socketAddressLen == NULL || acceptedSocket == NULL || *socketAddressLen < 0)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    socklen_t addrLen = (socklen_t)*socketAddressLen;
    int accepted;
#if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
    while ((accepted = accept4(fd, (struct sockaddr*)socketAddress, &addrLen, SOCK_CLOEXEC)) < 0 && errno == EINTR);
#else
    while ((accepted = accept(fd, (struct sockaddr*)socketAddress, &addrLen)) < 0 && errno == EINTR);
#if defined(FD_CLOEXEC)
    // macOS does not have accept4 but it can set _CLOEXEC on descriptor.
    // Unlike accept4 it is not atomic and the fd can leak child process.
    if ((accepted != -1) && fcntl(accepted, F_SETFD, FD_CLOEXEC) != 0)
    {
        // Preserve and return errno from fcntl. close() may reset errno to OK.
        int oldErrno = errno;
        close(accepted);
        accepted = -1;
        errno = oldErrno;
    }
#endif
#endif
#if !defined(__linux__)
    // On macOS and FreeBSD new socket inherits flags from accepting fd.
    // Our socket code expects new socket to be in blocking mode by default.
    if ((accepted != -1) && SystemNative_FcntlSetIsNonBlocking(accepted, 0) != 0)
    {
        int oldErrno = errno;
        close(accepted);
        accepted = -1;
        errno = oldErrno;
    }
#endif
    if (accepted == -1)
    {
        *acceptedSocket = -1;
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    assert(addrLen <= (socklen_t)*socketAddressLen);
    *socketAddressLen = (int32_t)addrLen;
    *acceptedSocket = accepted;
    return Error_SUCCESS;
}

int32_t SystemNative_Bind(intptr_t socket, int32_t protocolType, uint8_t* socketAddress, int32_t socketAddressLen)
{
    if (socketAddress == NULL || socketAddressLen < 0)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    // On Windows, Bind during TCP_WAIT is allowed.
    // On Unix, we set SO_REUSEADDR to get the same behavior.
    if (protocolType == ProtocolType_PT_TCP)
    {
        int optionValue = 1;
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optionValue, sizeof(int));
    }

    int err = bind(
        fd,
        (struct sockaddr*)socketAddress,
        (socklen_t)socketAddressLen);

    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_Connect(intptr_t socket, uint8_t* socketAddress, int32_t socketAddressLen)
{
    if (socketAddress == NULL || socketAddressLen < 0)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int err;
    while ((err = connect(fd, (struct sockaddr*)socketAddress, (socklen_t)socketAddressLen)) < 0 && errno == EINTR);
    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_GetPeerName(intptr_t socket, uint8_t* socketAddress, int32_t* socketAddressLen)
{
    if (socketAddress == NULL || socketAddressLen == NULL || *socketAddressLen < 0)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    socklen_t addrLen = (socklen_t)*socketAddressLen;
    int err = getpeername(fd, (struct sockaddr*)socketAddress, &addrLen);
    if (err != 0)
    {
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    *socketAddressLen = (int32_t)addrLen;
    return Error_SUCCESS;
}

int32_t SystemNative_GetSockName(intptr_t socket, uint8_t* socketAddress, int32_t* socketAddressLen)
{
    if (socketAddress == NULL || socketAddressLen == NULL || *socketAddressLen < 0)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    socklen_t addrLen = (socklen_t)*socketAddressLen;
    int err = getsockname(fd, (struct sockaddr*)socketAddress, &addrLen);
    if (err != 0)
    {
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    assert(addrLen <= (socklen_t)*socketAddressLen);
    *socketAddressLen = (int32_t)addrLen;
    return Error_SUCCESS;
}

int32_t SystemNative_Listen(intptr_t socket, int32_t backlog)
{
    int fd = ToFileDescriptor(socket);
    int err = listen(fd, backlog);
    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_Shutdown(intptr_t socket, int32_t socketShutdown)
{
    return Common_Shutdown(socket, socketShutdown);
}

int32_t SystemNative_GetSocketErrorOption(intptr_t socket, int32_t* error)
{
    if (error == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int socketErrno;
    socklen_t optLen = sizeof(socketErrno);
    int err = getsockopt(fd, SOL_SOCKET, SO_ERROR, &socketErrno, &optLen);
    if (err != 0)
    {
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    assert(optLen == sizeof(socketErrno));
    *error = SystemNative_ConvertErrorPlatformToPal(socketErrno);
    return Error_SUCCESS;
}

static bool TryGetPlatformSocketOption(int32_t socketOptionLevel, int32_t socketOptionName, int* optLevel, int* optName)
{
    switch (socketOptionLevel)
    {
        case SocketOptionLevel_SOL_SOCKET:
            *optLevel = SOL_SOCKET;

            switch (socketOptionName)
            {
                case SocketOptionName_SO_DEBUG:
                    *optName = SO_DEBUG;
                    return true;

                case SocketOptionName_SO_ACCEPTCONN:
                    *optName = SO_ACCEPTCONN;
                    return true;

                case SocketOptionName_SO_REUSEADDR:
                    *optName = SO_REUSEADDR;
                    return true;

                case SocketOptionName_SO_KEEPALIVE:
                    *optName = SO_KEEPALIVE;
                    return true;

                case SocketOptionName_SO_DONTROUTE:
                    *optName = SO_DONTROUTE;
                    return true;

                case SocketOptionName_SO_BROADCAST:
                    *optName = SO_BROADCAST;
                    return true;

                // case SocketOptionName_SO_USELOOPBACK:

                case SocketOptionName_SO_LINGER:
                    *optName = SO_LINGER;
                    return true;

                case SocketOptionName_SO_OOBINLINE:
                    *optName = SO_OOBINLINE;
                    return true;

                // case SocketOptionName_SO_DONTLINGER:

                // case SocketOptionName_SO_EXCLUSIVEADDRUSE:

                case SocketOptionName_SO_SNDBUF:
                    *optName = SO_SNDBUF;
                    return true;

                case SocketOptionName_SO_RCVBUF:
                    *optName = SO_RCVBUF;
                    return true;

                case SocketOptionName_SO_SNDLOWAT:
                    *optName = SO_SNDLOWAT;
                    return true;

                case SocketOptionName_SO_RCVLOWAT:
                    *optName = SO_RCVLOWAT;
                    return true;

                case SocketOptionName_SO_SNDTIMEO:
                    *optName = SO_SNDTIMEO;
                    return true;

                case SocketOptionName_SO_RCVTIMEO:
                    *optName = SO_RCVTIMEO;
                    return true;

                case SocketOptionName_SO_ERROR:
                    *optName = SO_ERROR;
                    return true;

                case SocketOptionName_SO_TYPE:
                    *optName = SO_TYPE;
                    return true;

                // case SocketOptionName_SO_MAXCONN:

                default:
                    return false;
            }

        case SocketOptionLevel_SOL_IP:
            *optLevel = IPPROTO_IP;

            switch (socketOptionName)
            {
                case SocketOptionName_SO_IP_OPTIONS:
                    *optName = IP_OPTIONS;
                    return true;

                case SocketOptionName_SO_IP_HDRINCL:
                    *optName = IP_HDRINCL;
                    return true;

                case SocketOptionName_SO_IP_TOS:
                    *optName = IP_TOS;
                    return true;

                case SocketOptionName_SO_IP_TTL:
                    *optName = IP_TTL;
                    return true;

                case SocketOptionName_SO_IP_MULTICAST_IF:
                    *optName = IP_MULTICAST_IF;
                    return true;

                case SocketOptionName_SO_IP_MULTICAST_TTL:
                    *optName = IP_MULTICAST_TTL;
                    return true;

                case SocketOptionName_SO_IP_MULTICAST_LOOP:
                    *optName = IP_MULTICAST_LOOP;
                    return true;

                case SocketOptionName_SO_IP_ADD_MEMBERSHIP:
                    *optName = IP_ADD_MEMBERSHIP;
                    return true;

                case SocketOptionName_SO_IP_DROP_MEMBERSHIP:
                    *optName = IP_DROP_MEMBERSHIP;
                    return true;

#ifdef IP_MTU_DISCOVER
                case SocketOptionName_SO_IP_DONTFRAGMENT:
                    *optName = IP_MTU_DISCOVER; // option values will also need to be translated
                    return true;
#endif

#ifdef IP_ADD_SOURCE_MEMBERSHIP
                case SocketOptionName_SO_IP_ADD_SOURCE_MEMBERSHIP:
                    *optName = IP_ADD_SOURCE_MEMBERSHIP;
                    return true;
#endif

#ifdef IP_DROP_SOURCE_MEMBERSHIP
                case SocketOptionName_SO_IP_DROP_SOURCE_MEMBERSHIP:
                    *optName = IP_DROP_SOURCE_MEMBERSHIP;
                    return true;
#endif

#ifdef IP_BLOCK_SOURCE
                case SocketOptionName_SO_IP_BLOCK_SOURCE:
                    *optName = IP_BLOCK_SOURCE;
                    return true;
#endif

#ifdef IP_UNBLOCK_SOURCE
                case SocketOptionName_SO_IP_UNBLOCK_SOURCE:
                    *optName = IP_UNBLOCK_SOURCE;
                    return true;
#endif

                case SocketOptionName_SO_IP_PKTINFO:
                    *optName = IP_PKTINFO;
                    return true;

                default:
                    return false;
            }

        case SocketOptionLevel_SOL_IPV6:
            *optLevel = IPPROTO_IPV6;

            switch (socketOptionName)
            {
                case SocketOptionName_SO_IPV6_HOPLIMIT:
                    *optName = IPV6_HOPLIMIT;
                    return true;

                // case SocketOptionName_SO_IPV6_PROTECTION_LEVEL:

                case SocketOptionName_SO_IPV6_V6ONLY:
                    *optName = IPV6_V6ONLY;
                    return true;

                case SocketOptionName_SO_IP_PKTINFO:
                    *optName = IPV6_RECVPKTINFO;
                    return true;

                case SocketOptionName_SO_IP_MULTICAST_IF:
                    *optName = IPV6_MULTICAST_IF;
                    return true;

                case SocketOptionName_SO_IP_MULTICAST_TTL:
                    *optName = IPV6_MULTICAST_HOPS;
                    return true;
                case SocketOptionName_SO_IP_TTL:
                    *optName = IPV6_UNICAST_HOPS;
                    return true;

                default:
                    return false;
            }

        case SocketOptionLevel_SOL_TCP:
            *optLevel = IPPROTO_TCP;

            switch (socketOptionName)
            {
                case SocketOptionName_SO_TCP_NODELAY:
                    *optName = TCP_NODELAY;
                    return true;

                // case SocketOptionName_SO_TCP_BSDURGENT:

                case SocketOptionName_SO_TCP_KEEPALIVE_RETRYCOUNT:
                    *optName = TCP_KEEPCNT;
                    return true;

                case SocketOptionName_SO_TCP_KEEPALIVE_TIME:
                    *optName =
                    #if HAVE_TCP_H_TCP_KEEPALIVE
                        TCP_KEEPALIVE;
                    #else
                        TCP_KEEPIDLE;
                    #endif
                    return true;

                case SocketOptionName_SO_TCP_KEEPALIVE_INTERVAL:
                    *optName = TCP_KEEPINTVL;
                    return true;

                default:
                    return false;
            }

        case SocketOptionLevel_SOL_UDP:
            *optLevel = IPPROTO_UDP;

            switch (socketOptionName)
            {
                // case SocketOptionName_SO_UDP_NOCHECKSUM:

                // case SocketOptionName_SO_UDP_CHECKSUM_COVERAGE:

                // case SocketOptionName_SO_UDP_UPDATEACCEPTCONTEXT:

                // case SocketOptionName_SO_UDP_UPDATECONNECTCONTEXT:

                default:
                    return false;
            }

        default:
            return false;
    }
}

static bool TryConvertSocketTypePlatformToPal(int platformSocketType, int32_t* palSocketType)
{
    assert(palSocketType != NULL);

    switch (platformSocketType)
    {
        case SOCK_STREAM:
            *palSocketType = SocketType_SOCK_STREAM;
            return true;

        case SOCK_DGRAM:
            *palSocketType = SocketType_SOCK_DGRAM;
            return true;

        case SOCK_RAW:
            *palSocketType = SocketType_SOCK_RAW;
            return true;

#ifdef SOCK_RDM
        case SOCK_RDM:
            *palSocketType = SocketType_SOCK_RDM;
            return true;
#endif

        case SOCK_SEQPACKET:
            *palSocketType = SocketType_SOCK_SEQPACKET;
            return true;

        default:
            *palSocketType = (int32_t)platformSocketType;
            return false;
    }
}

int32_t SystemNative_GetSockOpt(
    intptr_t socket, int32_t socketOptionLevel, int32_t socketOptionName, uint8_t* optionValue, int32_t* optionLen)
{
    if (optionLen == NULL || *optionLen < 0)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    //
    // Handle some special cases for compatibility with Windows and OSX
    //
    if (socketOptionLevel == SocketOptionLevel_SOL_SOCKET)
    {
        if (socketOptionName == SocketOptionName_SO_EXCLUSIVEADDRUSE || socketOptionName == SocketOptionName_SO_REUSEADDR)
        {
            if (*optionLen != sizeof(int32_t))
            {
                return Error_EINVAL;
            }

#ifdef SO_REUSEPORT
            socklen_t optLen = (socklen_t)*optionLen;
            // On Unix, SO_REUSEPORT controls the ability to bind multiple sockets to the same address.
            int err = getsockopt(fd, SOL_SOCKET, SO_REUSEPORT, optionValue, &optLen);

            if (err != 0)
            {
                return SystemNative_ConvertErrorPlatformToPal(errno);
            }

            int value = *(int32_t*)optionValue;

            // macOS returns non-zero values other than 1.
            value = value == 0 ? 0 : 1;

            // SocketOptionName_SO_EXCLUSIVEADDRUSE is inverse of SocketOptionName_SO_REUSEADDR (see comment in SystemNative_SetSockOpt).
            if (socketOptionName == SocketOptionName_SO_EXCLUSIVEADDRUSE)
            {
                value = value == 0 ? 1 : 0;
            }
            *(int32_t*)optionValue = value;
#else // !SO_REUSEPORT
            *optionValue = 0;
#endif
            return Error_SUCCESS;
        }
#if defined(__APPLE__) && HAVE_SYS_PROCINFO_H
        // OSX does not have SO_ACCEPTCONN getsockopt.
        else if (socketOptionName == SocketOptionName_SO_ACCEPTCONN)
        {
            if (*optionLen != sizeof(int32_t))
            {
                return Error_EINVAL;
            }

            struct socket_fdinfo fdi;
            if (proc_pidfdinfo(getpid(), fd, PROC_PIDFDSOCKETINFO, &fdi, sizeof(fdi)) < sizeof(fdi))
            {
                return SystemNative_ConvertErrorPlatformToPal(errno);
            }
            int value = (fdi.psi.soi_options & SO_ACCEPTCONN) != 0;
            *(int32_t*)optionValue = value;
            return Error_SUCCESS;
        }
#endif
    }

    int optLevel, optName;
    if (!TryGetPlatformSocketOption(socketOptionLevel, socketOptionName, &optLevel, &optName))
    {
        return Error_ENOTSUP;
    }

    socklen_t optLen = (socklen_t)*optionLen;
    int err = getsockopt(fd, optLevel, optName, optionValue, &optLen);

    if (err != 0)
    {
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

#ifdef IP_MTU_DISCOVER
    // Handle some special cases for compatibility with Windows
    if (socketOptionLevel == SocketOptionLevel_SOL_IP)
    {
        if (socketOptionName == SocketOptionName_SO_IP_DONTFRAGMENT)
        {
            *optionValue = *optionValue == IP_PMTUDISC_DO ? 1 : 0;
        }
    }
#endif

    if (socketOptionLevel == SocketOptionLevel_SOL_SOCKET)
    {
        if (socketOptionName == SocketOptionName_SO_TYPE)
        {
            if (optLen != sizeof(int) ||             // getsockopt didn't return an int.
                *optionLen < (int)sizeof(int32_t) || // optionValue can't fit an int32_t.
                !TryConvertSocketTypePlatformToPal(*(int*)optionValue, (int32_t*)optionValue))
            {
                return Error_ENOTSUP;
            }
            optLen = sizeof(int32_t);
        }
    }

    assert(optLen <= (socklen_t)*optionLen);
    *optionLen = (int32_t)optLen;
    return Error_SUCCESS;
}

int32_t SystemNative_GetRawSockOpt(
    intptr_t socket, int32_t socketOptionLevel, int32_t socketOptionName, uint8_t* optionValue, int32_t* optionLen)
{
    if (optionLen == NULL || *optionLen < 0)
    {
        return Error_EFAULT;
    }

    socklen_t optLen = (socklen_t)*optionLen;
    int err = getsockopt(ToFileDescriptor(socket), socketOptionLevel, socketOptionName, optionValue, &optLen);
    if (err != 0)
    {
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    assert(optLen <= (socklen_t)*optionLen);
    *optionLen = (int32_t)optLen;
    return Error_SUCCESS;
}

int32_t
SystemNative_SetSockOpt(intptr_t socket, int32_t socketOptionLevel, int32_t socketOptionName, uint8_t* optionValue, int32_t optionLen)
{
    if (optionLen < 0 || optionValue == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    //
    // Handle some special cases for compatibility with Windows
    //
    if (socketOptionLevel == SocketOptionLevel_SOL_SOCKET)
    {
        // Windows supports 3 address reuse modes:
        // - reuse not allowed        (SO_EXCLUSIVEADDRUSE=1, SO_REUSEADDR=0)
        // - reuse explicily allowed  (SO_EXCLUSIVEADDRUSE=0, SO_REUSEADDR=1)
        // - reuse implicitly allowed (SO_EXCLUSIVEADDRUSE=0, SO_REUSEADDR=0)
        // On Unix we can reuse or not, there is no implicit reuse.
        // We make both SocketOptionName_SO_REUSEADDR and SocketOptionName_SO_EXCLUSIVEADDRUSE control SO_REUSEPORT/SO_REUSEADDR.
        if (socketOptionName == SocketOptionName_SO_EXCLUSIVEADDRUSE || socketOptionName == SocketOptionName_SO_REUSEADDR)
        {
#ifdef SO_REUSEPORT
            if (optionLen != sizeof(int32_t))
            {
                return Error_EINVAL;
            }

            int value = *(int32_t*)optionValue;

            // SocketOptionName_SO_EXCLUSIVEADDRUSE is inverse of SocketOptionName_SO_REUSEADDR.
            if (socketOptionName == SocketOptionName_SO_EXCLUSIVEADDRUSE)
            {
                if ((value != 0) && (value != 1))
                {
                    return Error_EINVAL;
                }
                else
                {
                    value = value == 0 ? 1 : 0;
                }
            }

            // An application that sets SO_REUSEPORT/SO_REUSEADDR can reuse the endpoint with another
            // application that sets the same option. If one application sets SO_REUSEPORT and another
            // sets SO_REUSEADDR the second application will fail to bind. We set both options, this
            // enables reuse with applications that set one or both options.
            int err = setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &value, (socklen_t)optionLen);
            if (err == 0)
            {
                err = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &value, (socklen_t)optionLen);
            }
            return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
#else // !SO_REUSEPORT
            return Error_SUCCESS;
#endif
        }
    }
#ifdef IP_MTU_DISCOVER
    else if (socketOptionLevel == SocketOptionLevel_SOL_IP)
    {
        if (socketOptionName == SocketOptionName_SO_IP_DONTFRAGMENT)
        {
            *optionValue = *optionValue != 0 ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
        }
    }
#endif

    int optLevel, optName;
    if (!TryGetPlatformSocketOption(socketOptionLevel, socketOptionName, &optLevel, &optName))
    {
        return Error_ENOTSUP;
    }

    int err = setsockopt(fd, optLevel, optName, optionValue, (socklen_t)optionLen);
    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_SetRawSockOpt(
    intptr_t socket, int32_t socketOptionLevel, int32_t socketOptionName, uint8_t* optionValue, int32_t optionLen)
{
    if (optionLen < 0 || optionValue == NULL)
    {
        return Error_EFAULT;
    }

    int err = setsockopt(ToFileDescriptor(socket), socketOptionLevel, socketOptionName, optionValue, (socklen_t)optionLen);
    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

static bool TryConvertSocketTypePalToPlatform(int32_t palSocketType, int* platformSocketType)
{
    assert(platformSocketType != NULL);

    switch (palSocketType)
    {
        case SocketType_SOCK_STREAM:
            *platformSocketType = SOCK_STREAM;
            return true;

        case SocketType_SOCK_DGRAM:
            *platformSocketType = SOCK_DGRAM;
            return true;

        case SocketType_SOCK_RAW:
            *platformSocketType = SOCK_RAW;
            return true;

#ifdef SOCK_RDM
        case SocketType_SOCK_RDM:
            *platformSocketType = SOCK_RDM;
            return true;
#endif

        case SocketType_SOCK_SEQPACKET:
            *platformSocketType = SOCK_SEQPACKET;
            return true;

        default:
            *platformSocketType = (int)palSocketType;
            return false;
    }
}

static bool TryConvertProtocolTypePalToPlatform(int32_t palAddressFamily, int32_t palProtocolType, int* platformProtocolType)
{
    assert(platformProtocolType != NULL);

    switch(palAddressFamily)
    {
#ifdef AF_PACKET
        case AddressFamily_AF_PACKET:
            // protocol is the IEEE 802.3 protocol number in network order.
            *platformProtocolType = palProtocolType;
            return true;
#endif
#if HAVE_LINUX_CAN_H
        case AddressFamily_AF_CAN:
            switch (palProtocolType)
            {
                case ProtocolType_PT_UNSPECIFIED:
                    *platformProtocolType = 0;
                    return true;

                case ProtocolType_PT_RAW:
                    *platformProtocolType = CAN_RAW;
                    return true;

                default:
                    *platformProtocolType = (int)palProtocolType;
                    return false;
            }
#endif
        case AddressFamily_AF_INET:
            switch (palProtocolType)
            {
                case ProtocolType_PT_UNSPECIFIED:
                    *platformProtocolType = 0;
                    return true;

                case ProtocolType_PT_ICMP:
                    *platformProtocolType = IPPROTO_ICMP;
                    return true;

                case ProtocolType_PT_TCP:
                    *platformProtocolType = IPPROTO_TCP;
                    return true;

                case ProtocolType_PT_UDP:
                    *platformProtocolType = IPPROTO_UDP;
                    return true;

                case ProtocolType_PT_IGMP:
                    *platformProtocolType = IPPROTO_IGMP;
                    return true;

                case ProtocolType_PT_RAW:
                    *platformProtocolType = IPPROTO_RAW;
                    return true;

                default:
                    *platformProtocolType = (int)palProtocolType;
                    return false;
                }

        case AddressFamily_AF_INET6:
            switch (palProtocolType)
            {
                case ProtocolType_PT_UNSPECIFIED:
                    *platformProtocolType = 0;
                    return true;

                case ProtocolType_PT_ICMPV6:
                case ProtocolType_PT_ICMP:
                    *platformProtocolType = IPPROTO_ICMPV6;
                    return true;

                case ProtocolType_PT_TCP:
                    *platformProtocolType = IPPROTO_TCP;
                    return true;

                case ProtocolType_PT_UDP:
                    *platformProtocolType = IPPROTO_UDP;
                    return true;

                case ProtocolType_PT_IGMP:
                    *platformProtocolType = IPPROTO_IGMP;
                    return true;

                case ProtocolType_PT_RAW:
                    *platformProtocolType = IPPROTO_RAW;
                    return true;

                case ProtocolType_PT_DSTOPTS:
                    *platformProtocolType = IPPROTO_DSTOPTS;
                    return true;

                case ProtocolType_PT_NONE:
                    *platformProtocolType = IPPROTO_NONE;
                    return true;

                case ProtocolType_PT_ROUTING:
                    *platformProtocolType = IPPROTO_ROUTING;
                    return true;

                case ProtocolType_PT_FRAGMENT:
                    *platformProtocolType = IPPROTO_FRAGMENT;
                    return true;

                default:
                    *platformProtocolType = (int)palProtocolType;
                    return false;
            }

        default:
            switch (palProtocolType)
            {
                case ProtocolType_PT_UNSPECIFIED:
                    *platformProtocolType = 0;
                    return true;
                default:
                    *platformProtocolType = (int)palProtocolType;
                    return false;
            }
    }
}

static bool TryConvertProtocolTypePlatformToPal(int32_t palAddressFamily, int platformProtocolType, int32_t* palProtocolType)
{
    assert(palProtocolType != NULL);

    switch (palAddressFamily)
    {
#ifdef AF_PACKET
        case AddressFamily_AF_PACKET:
            // protocol is the IEEE 802.3 protocol number in network order.
            *palProtocolType = platformProtocolType;
            return true;
#endif
#if HAVE_LINUX_CAN_H
        case AddressFamily_AF_CAN:
            switch (platformProtocolType)
            {
                case 0:
                    *palProtocolType = ProtocolType_PT_UNSPECIFIED;
                    return true;

                case CAN_RAW:
                    *palProtocolType = ProtocolType_PT_RAW;
                    return true;

                default:
                    *palProtocolType = (int)platformProtocolType;
                    return false;
            }
#endif
        case AddressFamily_AF_INET:
            switch (platformProtocolType)
            {
                case 0:
                    *palProtocolType = ProtocolType_PT_UNSPECIFIED;
                    return true;

                case IPPROTO_ICMP:
                    *palProtocolType = ProtocolType_PT_ICMP;
                    return true;

                case IPPROTO_TCP:
                    *palProtocolType = ProtocolType_PT_TCP;
                    return true;

                case IPPROTO_UDP:
                    *palProtocolType = ProtocolType_PT_UDP;
                    return true;

                case IPPROTO_IGMP:
                    *palProtocolType = ProtocolType_PT_IGMP;
                    return true;

                case IPPROTO_RAW:
                    *palProtocolType = ProtocolType_PT_RAW;
                    return true;

                default:
                    *palProtocolType = (int32_t)(intptr_t)palProtocolType;
                    return false;
            }

        case AddressFamily_AF_INET6:
            switch (platformProtocolType)
            {
                case 0:
                    *palProtocolType = ProtocolType_PT_UNSPECIFIED;
                    return true;

                case IPPROTO_ICMPV6:
                    *palProtocolType = ProtocolType_PT_ICMPV6;
                    return true;

                case IPPROTO_TCP:
                    *palProtocolType = ProtocolType_PT_TCP;
                    return true;

                case IPPROTO_UDP:
                    *palProtocolType = ProtocolType_PT_UDP;
                    return true;

                case IPPROTO_IGMP:
                    *palProtocolType = ProtocolType_PT_IGMP;
                    return true;

                case IPPROTO_RAW:
                    *palProtocolType = ProtocolType_PT_RAW;
                    return true;

                case IPPROTO_DSTOPTS:
                    *palProtocolType = ProtocolType_PT_DSTOPTS;
                    return true;

                case IPPROTO_NONE:
                    *palProtocolType = ProtocolType_PT_NONE;
                    return true;

                case IPPROTO_ROUTING:
                    *palProtocolType = ProtocolType_PT_ROUTING;
                    return true;

                case IPPROTO_FRAGMENT:
                    *palProtocolType = ProtocolType_PT_FRAGMENT;
                    return true;

                default:
                    *palProtocolType = (int)platformProtocolType;
                    return false;
            }

        default:
            switch (platformProtocolType)
            {
                case 0:
                    *palProtocolType = ProtocolType_PT_UNSPECIFIED;
                    return true;
                default:
                    *palProtocolType = (int)platformProtocolType;
                    return false;
            }
    }
}

int32_t SystemNative_Socket(int32_t addressFamily, int32_t socketType, int32_t protocolType, intptr_t* createdSocket)
{
    if (createdSocket == NULL)
    {
        return Error_EFAULT;
    }

    sa_family_t platformAddressFamily;
    int platformSocketType, platformProtocolType;

    if (!TryConvertAddressFamilyPalToPlatform(addressFamily, &platformAddressFamily))
    {
        *createdSocket = -1;
        return Error_EAFNOSUPPORT;
    }

    if (!TryConvertSocketTypePalToPlatform(socketType, &platformSocketType))
    {
        *createdSocket = -1;
        return Error_EPROTOTYPE;
    }

    if (!TryConvertProtocolTypePalToPlatform(addressFamily, protocolType, &platformProtocolType))
    {
        *createdSocket = -1;
        return Error_EPROTONOSUPPORT;
    }

#ifdef SOCK_CLOEXEC
    platformSocketType |= SOCK_CLOEXEC;
#endif
    *createdSocket = socket(platformAddressFamily, platformSocketType, platformProtocolType);
    if (*createdSocket == -1)
    {
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

#ifndef SOCK_CLOEXEC
    fcntl(ToFileDescriptor(*createdSocket), F_SETFD, FD_CLOEXEC); // ignore any failures; this is best effort
#endif
    return Error_SUCCESS;
}

int32_t SystemNative_GetSocketType(intptr_t socket, int32_t* addressFamily, int32_t* socketType, int32_t* protocolType, int32_t* isListening)
{
    if (addressFamily == NULL || socketType == NULL || protocolType == NULL || isListening == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

#if HAVE_SYS_PROCINFO_H
    struct socket_fdinfo fdi;
    if (proc_pidfdinfo(getpid(), fd, PROC_PIDFDSOCKETINFO, &fdi, sizeof(fdi)) < sizeof(fdi))
    {
        return Error_EFAULT;
    }

    if (!TryConvertAddressFamilyPlatformToPal((sa_family_t)fdi.psi.soi_family, addressFamily))
    {
        *addressFamily = AddressFamily_AF_UNKNOWN;
    }

    if (!TryConvertSocketTypePlatformToPal(fdi.psi.soi_type, socketType))
    {
        *socketType = SocketType_UNKNOWN;
    }

    if (!TryConvertProtocolTypePlatformToPal(*addressFamily, fdi.psi.soi_protocol, protocolType))
    {
        *protocolType = ProtocolType_PT_UNKNOWN;
    }

    *isListening = (fdi.psi.soi_options & SO_ACCEPTCONN) != 0;
#else
#ifdef SO_DOMAIN
    int domainValue;
    socklen_t domainLength = sizeof(int);
    if (getsockopt(fd, SOL_SOCKET, SO_DOMAIN, &domainValue, &domainLength) != 0 ||
        !TryConvertAddressFamilyPlatformToPal((sa_family_t)domainValue, addressFamily))
#endif
    {
        *addressFamily = AddressFamily_AF_UNKNOWN;
    }

#ifdef SO_TYPE
    int typeValue;
    socklen_t typeLength = sizeof(int);
    if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &typeValue, &typeLength) != 0 ||
        !TryConvertSocketTypePlatformToPal(typeValue, socketType))
#endif
    {
        *socketType = SocketType_UNKNOWN;
    }

#ifdef SO_PROTOCOL
    int protocolValue;
    socklen_t protocolLength = sizeof(int);
    if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL, &protocolValue, &protocolLength) != 0 ||
        !TryConvertProtocolTypePlatformToPal(*addressFamily, protocolValue, protocolType))
#endif
    {
        *protocolType = ProtocolType_PT_UNKNOWN;
    }

    int listeningValue;
    socklen_t listeningLength = sizeof(int);
    if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &listeningValue, &listeningLength) == 0)
    {
        *isListening = (listeningValue != 0);
    }
    else
    {
        *isListening = 0;
    }
#endif
    return Error_SUCCESS;
}

int32_t SystemNative_GetAtOutOfBandMark(intptr_t socket, int32_t* atMark)
{
    if (atMark == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int result;
    int err;
    while ((err = ioctl(fd, SIOCATMARK, &result)) < 0 && errno == EINTR);
    if (err == -1)
    {
        *atMark = 0;
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    *atMark = (int32_t)result;
    return Error_SUCCESS;
}

int32_t SystemNative_GetBytesAvailable(intptr_t socket, int32_t* available)
{
    if (available == NULL)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(socket);

    int result;
    int err;
    while ((err = ioctl(fd, FIONREAD, &result)) < 0 && errno == EINTR);
    if (err == -1)
    {
        *available = 0;
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    *available = (int32_t)result;
    return Error_SUCCESS;
}

#if HAVE_EPOLL

static const size_t SocketEventBufferElementSize = sizeof(struct epoll_event) > sizeof(SocketEvent) ? sizeof(struct epoll_event) : sizeof(SocketEvent);

static int GetSocketEvents(uint32_t events)
{
    int asyncEvents = (((events & EPOLLIN) != 0) ? SocketEvents_SA_READ : 0) | (((events & EPOLLOUT) != 0) ? SocketEvents_SA_WRITE : 0) |
                      (((events & EPOLLRDHUP) != 0) ? SocketEvents_SA_READCLOSE : 0) |
                      (((events & EPOLLHUP) != 0) ? SocketEvents_SA_CLOSE : 0) | (((events & EPOLLERR) != 0) ? SocketEvents_SA_ERROR : 0);

    return asyncEvents;
}

static uint32_t GetEPollEvents(SocketEvents events)
{
    return (((events & SocketEvents_SA_READ) != 0) ? EPOLLIN : 0) | (((events & SocketEvents_SA_WRITE) != 0) ? EPOLLOUT : 0) |
           (((events & SocketEvents_SA_READCLOSE) != 0) ? EPOLLRDHUP : 0) | (((events & SocketEvents_SA_CLOSE) != 0) ? EPOLLHUP : 0) |
           (((events & SocketEvents_SA_ERROR) != 0) ? EPOLLERR : 0);
}

static int32_t CreateSocketEventPortInner(int32_t* port)
{
    assert(port != NULL);

    int epollFd = epoll_create1(EPOLL_CLOEXEC);
    if (epollFd == -1)
    {
        *port = -1;
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    *port = epollFd;
    return Error_SUCCESS;
}

static int32_t CloseSocketEventPortInner(int32_t port)
{
    int err = close(port);
    return err == 0 || (err < 0 && errno == EINTR) ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

static int32_t TryChangeSocketEventRegistrationInner(
    int32_t port, int32_t socket, SocketEvents currentEvents, SocketEvents newEvents, uintptr_t data)
{
    assert(currentEvents != newEvents);

    int op = EPOLL_CTL_MOD;
    if (currentEvents == SocketEvents_SA_NONE)
    {
        op = EPOLL_CTL_ADD;
    }
    else if (newEvents == SocketEvents_SA_NONE)
    {
        op = EPOLL_CTL_DEL;
    }

    struct epoll_event evt;
    memset(&evt, 0, sizeof(struct epoll_event));
    evt.events = GetEPollEvents(newEvents) | (unsigned int)EPOLLET;
    evt.data.ptr = (void*)data;
    int err = epoll_ctl(port, op, socket, &evt);
    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

static void ConvertEventEPollToSocketAsync(SocketEvent* sae, struct epoll_event* epoll)
{
    assert(sae != NULL);
    assert(epoll != NULL);

    // epoll does not play well with disconnected connection-oriented sockets, frequently
    // reporting spurious EPOLLHUP events. Fortunately, EPOLLHUP may be handled as an
    // EPOLLIN | EPOLLOUT event: the usual processing for these events will recognize and
    // handle the HUP condition.
    uint32_t events = epoll->events;
    if ((events & EPOLLHUP) != 0)
    {
        events = (events & ((uint32_t)~EPOLLHUP)) | EPOLLIN | EPOLLOUT;
    }

    memset(sae, 0, sizeof(SocketEvent));
    sae->Data = (uintptr_t)epoll->data.ptr;
    sae->Events = GetSocketEvents(events);
}

static int32_t WaitForSocketEventsInner(int32_t port, SocketEvent* buffer, int32_t* count)
{
    assert(buffer != NULL);
    assert(count != NULL);
    assert(*count >= 0);

    struct epoll_event* events = (struct epoll_event*)buffer;
    int numEvents;
    while ((numEvents = epoll_wait(port, events, *count, -1)) < 0 && errno == EINTR);
    if (numEvents == -1)
    {
        *count = 0;
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    // We should never see 0 events. Given an infinite timeout, epoll_wait will never return
    // 0 events even if there are no file descriptors registered with the epoll fd. In
    // that case, the wait will block until a file descriptor is added and an event occurs
    // on the added file descriptor.
    assert(numEvents != 0);
    assert(numEvents <= *count);

    if (sizeof(struct epoll_event) < sizeof(SocketEvent))
    {
        // Copy backwards to avoid overwriting earlier data.
        for (int i = numEvents - 1; i >= 0; i--)
        {
            // This copy is made deliberately to avoid overwriting data.
            struct epoll_event evt = events[i];
            ConvertEventEPollToSocketAsync(&buffer[i], &evt);
        }
    }
    else
    {
        // Copy forwards for better cache behavior
        for (int i = 0; i < numEvents; i++)
        {
            // This copy is made deliberately to avoid overwriting data.
            struct epoll_event evt = events[i];
            ConvertEventEPollToSocketAsync(&buffer[i], &evt);
        }
    }

    *count = numEvents;
    return Error_SUCCESS;
}

#elif HAVE_KQUEUE

c_static_assert(sizeof(SocketEvent) <= sizeof(struct kevent));
static const size_t SocketEventBufferElementSize = sizeof(struct kevent);

static SocketEvents GetSocketEvents(int16_t filter, uint16_t flags)
{
    int32_t events;
    switch (filter)
    {
        case EVFILT_READ:
            events = SocketEvents_SA_READ;
            if ((flags & EV_EOF) != 0)
            {
                events |= SocketEvents_SA_READCLOSE;
            }
            break;

        case EVFILT_WRITE:
            events = SocketEvents_SA_WRITE;

            // kqueue does not play well with disconnected connection-oriented sockets, frequently
            // reporting spurious EOF events. Fortunately, EOF may be handled as an EVFILT_READ |
            // EVFILT_WRITE event: the usual processing for these events will recognize and
            // handle the EOF condition.
            if ((flags & EV_EOF) != 0)
            {
                events |= SocketEvents_SA_READ;
            }
            break;

        default:
            assert_msg(0, "unexpected kqueue filter type", (int)filter);
            return SocketEvents_SA_NONE;
    }

    if ((flags & EV_ERROR) != 0)
    {
        events |= SocketEvents_SA_ERROR;
    }

    return (SocketEvents)events;
}

static int32_t CreateSocketEventPortInner(int32_t* port)
{
    assert(port != NULL);

    int kqueueFd = kqueue();
    if (kqueueFd == -1)
    {
        *port = -1;
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    *port = kqueueFd;
    return Error_SUCCESS;
}

static int32_t CloseSocketEventPortInner(int32_t port)
{
    int err = close(port);
    return err == 0 || (err < 0 && errno == EINTR) ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

static int32_t TryChangeSocketEventRegistrationInner(
    int32_t port, int32_t socket, SocketEvents currentEvents, SocketEvents newEvents, uintptr_t data)
{
#ifdef EV_RECEIPT
    const uint16_t AddFlags = EV_ADD | EV_CLEAR | EV_RECEIPT;
    const uint16_t RemoveFlags = EV_DELETE | EV_RECEIPT;
#else
    const uint16_t AddFlags = EV_ADD | EV_CLEAR;
    const uint16_t RemoveFlags = EV_DELETE;
#endif

    assert(currentEvents != newEvents);

    int32_t changes = currentEvents ^ newEvents;
    int8_t readChanged = (changes & SocketEvents_SA_READ) != 0;
    int8_t writeChanged = (changes & SocketEvents_SA_WRITE) != 0;

    struct kevent events[2];
    int err;

    int i = 0;
    if (readChanged)
    {
        EV_SET(&events[i++],
               (uint64_t)socket,
               EVFILT_READ,
               (newEvents & SocketEvents_SA_READ) == 0 ? RemoveFlags : AddFlags,
               0,
               0,
               GetKeventUdata(data));
#if defined(__FreeBSD__)
        // Issue: #30698
        // FreeBSD seems to have some issue when setting read/write events together.
        // As a workaround use separate kevent() calls.
        if (writeChanged)
        {
            while ((err = kevent(port, events, GetKeventNchanges(i), NULL, 0, NULL)) < 0 && errno == EINTR);
            if (err != 0)
            {
                return SystemNative_ConvertErrorPlatformToPal(errno);
            }
            i = 0;
        }
#endif
    }

    if (writeChanged)
    {
        EV_SET(&events[i++],
               (uint64_t)socket,
               EVFILT_WRITE,
               (newEvents & SocketEvents_SA_WRITE) == 0 ? RemoveFlags : AddFlags,
               0,
               0,
               GetKeventUdata(data));
    }

    while ((err = kevent(port, events, GetKeventNchanges(i), NULL, 0, NULL)) < 0 && errno == EINTR);
    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

static int32_t WaitForSocketEventsInner(int32_t port, SocketEvent* buffer, int32_t* count)
{
    assert(buffer != NULL);
    assert(count != NULL);
    assert(*count >= 0);

    struct kevent* events = (struct kevent*)buffer;
    int numEvents;
    while ((numEvents = kevent(port, NULL, 0, events, GetKeventNchanges(*count), NULL)) < 0 && errno == EINTR);
    if (numEvents == -1)
    {
        *count = -1;
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

    // We should never see 0 events. Given an infinite timeout, kevent will never return
    // 0 events even if there are no file descriptors registered with the kqueue fd. In
    // that case, the wait will block until a file descriptor is added and an event occurs
    // on the added file descriptor.
    assert(numEvents != 0);
    assert(numEvents <= *count);

    for (int i = 0; i < numEvents; i++)
    {
        // This copy is made deliberately to avoid overwriting data.
        struct kevent evt = events[i];
        memset(&buffer[i], 0, sizeof(SocketEvent));
        buffer[i].Data = GetSocketEventData(evt.udata);
        buffer[i].Events = GetSocketEvents(GetKeventFilter(evt.filter), GetKeventFlags(evt.flags));
    }

    *count = numEvents;
    return Error_SUCCESS;
}

#else
static const size_t SocketEventBufferElementSize = 0;

static SocketEvents GetSocketEvents(int16_t filter, uint16_t flags)
{
    return SocketEvents_SA_NONE;
}
static int32_t CloseSocketEventPortInner(int32_t port)
{
    return Error_ENOSYS;
}
static int32_t CreateSocketEventPortInner(int32_t* port)
{
    return Error_ENOSYS;
}
static int32_t TryChangeSocketEventRegistrationInner(
    int32_t port, int32_t socket, SocketEvents currentEvents, SocketEvents newEvents,
uintptr_t data)
{
    return Error_ENOSYS;
}
static int32_t WaitForSocketEventsInner(int32_t port, SocketEvent* buffer, int32_t* count)
{
    return Error_ENOSYS;
}

#endif

int32_t SystemNative_CreateSocketEventPort(intptr_t* port)
{
    if (port == NULL)
    {
        return Error_EFAULT;
    }

    int fd;
    int32_t error = CreateSocketEventPortInner(&fd);
    *port = fd;
    return error;
}

int32_t SystemNative_CloseSocketEventPort(intptr_t port)
{
    return CloseSocketEventPortInner(ToFileDescriptor(port));
}

int32_t SystemNative_CreateSocketEventBuffer(int32_t count, SocketEvent** buffer)
{
    if (buffer == NULL || count < 0)
    {
        return Error_EFAULT;
    }

    size_t bufferSize;
    if (!multiply_s(SocketEventBufferElementSize, (size_t)count, &bufferSize) ||
        (*buffer = (SocketEvent*)malloc(bufferSize)) == NULL)
    {
        return Error_ENOMEM;
    }

    return Error_SUCCESS;
}

int32_t SystemNative_FreeSocketEventBuffer(SocketEvent* buffer)
{
    free(buffer);
    return Error_SUCCESS;
}

int32_t
SystemNative_TryChangeSocketEventRegistration(intptr_t port, intptr_t socket, int32_t currentEvents, int32_t newEvents, uintptr_t data)
{
    int portFd = ToFileDescriptor(port);
    int socketFd = ToFileDescriptor(socket);

    const int32_t SupportedEvents = SocketEvents_SA_READ | SocketEvents_SA_WRITE | SocketEvents_SA_READCLOSE | SocketEvents_SA_CLOSE | SocketEvents_SA_ERROR;

    if ((currentEvents & ~SupportedEvents) != 0 || (newEvents & ~SupportedEvents) != 0)
    {
        return Error_EINVAL;
    }

    if (currentEvents == newEvents)
    {
        return Error_SUCCESS;
    }

    return TryChangeSocketEventRegistrationInner(
        portFd, socketFd, (SocketEvents)currentEvents, (SocketEvents)newEvents, data);
}

int32_t SystemNative_WaitForSocketEvents(intptr_t port, SocketEvent* buffer, int32_t* count)
{
    if (buffer == NULL || count == NULL || *count < 0)
    {
        return Error_EFAULT;
    }

    int fd = ToFileDescriptor(port);

    return WaitForSocketEventsInner(fd, buffer, count);
}

int32_t SystemNative_PlatformSupportsDualModeIPv4PacketInfo(void)
{
#if HAVE_SUPPORT_FOR_DUAL_MODE_IPV4_PACKET_INFO
    return 1;
#else
    return 0;
#endif
}

static char* GetNameFromUid(uid_t uid)
{
    size_t bufferLength = 512;
    while (1)
    {
        char *buffer = (char*)malloc(bufferLength);
        if (buffer == NULL)
            return NULL;

        struct passwd pw;
        struct passwd* result;
        if (getpwuid_r(uid, &pw, buffer, bufferLength, &result) == 0)
        {
            if (result == NULL)
            {
                errno = ENOENT;
                free(buffer);
                return NULL;
            }
            else
            {
                char* name = strdup(pw.pw_name);
                free(buffer);
                return name;
            }
        }

        free(buffer);
        size_t tmpBufferLength;
        if (errno != ERANGE || !multiply_s(bufferLength, (size_t)2, &tmpBufferLength))
        {
            return NULL;
        }
        bufferLength = tmpBufferLength;
    }
}

char* SystemNative_GetPeerUserName(intptr_t socket)
{
    uid_t euid;
    return SystemNative_GetPeerID(socket, &euid) == 0 ?
        GetNameFromUid(euid) :
        NULL;
}

void SystemNative_GetDomainSocketSizes(int32_t* pathOffset, int32_t* pathSize, int32_t* addressSize)
{
    assert(pathOffset != NULL);
    assert(pathSize != NULL);
    assert(addressSize != NULL);

    struct sockaddr_un domainSocket;

    *pathOffset = offsetof(struct sockaddr_un, sun_path);
    *pathSize = sizeof(domainSocket.sun_path);
    *addressSize = sizeof(domainSocket);
}

int32_t SystemNative_GetMaximumAddressSize(void)
{
    return sizeof(struct sockaddr_storage);
}

int32_t SystemNative_Disconnect(intptr_t socket)
{
    int fd = ToFileDescriptor(socket);
    int err;

#if defined(__linux__)
    // On Linux, we can disconnect a socket by connecting to AF_UNSPEC.
    // For TCP sockets, this causes an abortive close.

    struct sockaddr addr;
    memset(&addr, 0, sizeof(addr));
    addr.sa_family = AF_UNSPEC;

    err = connect(fd, &addr, sizeof(addr));
    if (err != 0) 
    {
        // On some older kernels connect(AF_UNSPEC) may fail. Fall back to shutdown in these cases:
        err = shutdown(fd, SHUT_RDWR);
    } 
#elif HAVE_DISCONNECTX
    // disconnectx causes a FIN close on OSX. It's the best we can do.
    err = disconnectx(fd, SAE_ASSOCID_ANY, SAE_CONNID_ANY);
#else
    // best-effort, this may cause a FIN close.
    err = shutdown(fd, SHUT_RDWR);
#endif

    return err == 0 ? Error_SUCCESS : SystemNative_ConvertErrorPlatformToPal(errno);
}

int32_t SystemNative_SendFile(intptr_t out_fd, intptr_t in_fd, int64_t offset, int64_t count, int64_t* sent)
{
    assert(sent != NULL);

    int outfd = ToFileDescriptor(out_fd);
    int infd = ToFileDescriptor(in_fd);

#if HAVE_SENDFILE_4
    off_t offtOffset = (off_t)offset;

    ssize_t res;
    while ((res = sendfile(outfd, infd, &offtOffset, (size_t)count)) < 0 && errno == EINTR);
    if (res != -1)
    {
        *sent = res;
        return Error_SUCCESS;
    }

    *sent = 0;
    return SystemNative_ConvertErrorPlatformToPal(errno);

#elif HAVE_SENDFILE_6 || HAVE_SENDFILE_7
    *sent = 0;
    while (1) // in case we need to retry for an EINTR
    {
        off_t len = count;
#if HAVE_SENDFILE_7
        ssize_t res = sendfile(infd, outfd, (off_t)offset, (size_t)count, NULL, &len, 0);
#else
        ssize_t res = sendfile(infd, outfd, (off_t)offset, &len, NULL, 0);
#endif
        assert(len >= 0);

        // If the call succeeded, store the number of bytes sent, and return.  We add
        // rather than copy len because a previous call to sendfile could have sent bytes
        // but been interrupted by EINTR, in which case we need to add to that.
        if (res != -1)
        {
            *sent += len;
            return Error_SUCCESS;
        }

        // We got an error. If sendfile "fails" with EINTR or EAGAIN, it may have sent
        // some data that needs to be counted.
        if (errno == EAGAIN || errno == EINTR)
        {
            *sent += len;
            offset += len;
            count -= len;

            // If we actually transferred everything in spite of the error, return success.
            assert(count >= 0);
            if (count == 0) return Error_SUCCESS;

            // For EINTR, loop around and go again.
            if (errno == EINTR) continue;
        }

        // For everything other than EINTR, bail.
        return SystemNative_ConvertErrorPlatformToPal(errno);
    }

#else
    // If we ever need to run on a platform that doesn't have sendfile,
    // we can implement this with a simple read/send loop.  For now,
    // we just mark it as not supported.
    (void)outfd;
    (void)infd;
    (void)offset;
    (void)count;
    *sent = 0;
    errno = ENOTSUP;
    return SystemNative_ConvertErrorPlatformToPal(errno);
#endif
}

uint32_t SystemNative_InterfaceNameToIndex(char* interfaceName)
{
    assert(interfaceName != NULL);
    if (interfaceName[0] == '%')
        interfaceName++;
    return if_nametoindex(interfaceName);
}