File: Socket.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (3063 lines) | stat: -rw-r--r-- 95,078 bytes parent folder | download
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
// System.Net.Sockets.Socket.cs
//
// Authors:
//	Phillip Pearson (pp@myelin.co.nz)
//	Dick Porter <dick@ximian.com>
//	Gonzalo Paniagua Javier (gonzalo@ximian.com)
//	Sridhar Kulkarni (sridharkulkarni@gmail.com)
//	Brian Nickel (brian.nickel@gmail.com)
//	Ludovic Henry (ludovic@xamarin.com)
//
// Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
//    http://www.myelin.co.nz
// (c) 2004-2011 Novell, Inc. (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;
using System.Net.Configuration;
using System.Text;
using System.Timers;
using System.Net.NetworkInformation;

namespace System.Net.Sockets
{
	public partial class Socket : IDisposable
	{
		const int SOCKET_CLOSED_CODE = 10004;
		const string TIMEOUT_EXCEPTION_MSG = "A connection attempt failed because the connected party did not properly respond" +
			"after a period of time, or established connection failed because connected host has failed to respond";

		/* true if we called Close_icall */
		bool is_closed;

		bool is_listening;
		bool useOverlappedIO;

		int linger_timeout;

		AddressFamily addressFamily;
		SocketType socketType;
		ProtocolType protocolType;

		/* the field "m_Handle" is looked up by name by the runtime */
		internal SafeSocketHandle m_Handle;

		/*
		 * This EndPoint is used when creating new endpoints. Because
		 * there are many types of EndPoints possible,
		 * seed_endpoint.Create(addr) is used for creating new ones.
		 * As such, this value is set on Bind, SentTo, ReceiveFrom,
		 * Connect, etc.
		 */
		internal EndPoint seed_endpoint = null;

		internal SemaphoreSlim ReadSem = new SemaphoreSlim (1, 1);
		internal SemaphoreSlim WriteSem = new SemaphoreSlim (1, 1);

		internal bool is_blocking = true;
		internal bool is_bound;

		/* When true, the socket was connected at the time of the last IO operation */
		internal bool is_connected;

		int m_IntCleanedUp;
		internal bool connect_in_progress;

#if MONO_WEB_DEBUG
		static int nextId;
		internal readonly int ID = ++nextId;
#else
		internal readonly int ID;
#endif

		#region Constructors


		public Socket (SocketInformation socketInformation)
		{
			this.is_listening      = (socketInformation.Options & SocketInformationOptions.Listening) != 0;
			this.is_connected      = (socketInformation.Options & SocketInformationOptions.Connected) != 0;
			this.is_blocking       = (socketInformation.Options & SocketInformationOptions.NonBlocking) == 0;
			this.useOverlappedIO = (socketInformation.Options & SocketInformationOptions.UseOnlyOverlappedIO) != 0;

			var result = Mono.DataConverter.Unpack ("iiiil", socketInformation.ProtocolInformation, 0);

			this.addressFamily = (AddressFamily) (int) result [0];
			this.socketType = (SocketType) (int) result [1];
			this.protocolType = (ProtocolType) (int) result [2];
			this.is_bound = (ProtocolType) (int) result [3] != 0;
			this.m_Handle = new SafeSocketHandle ((IntPtr) (long) result [4], true);

			InitializeSockets ();

			SocketDefaults ();
		}

		/* private constructor used by Accept, which already has a socket handle to use */
		internal Socket(AddressFamily family, SocketType type, ProtocolType proto, SafeSocketHandle safe_handle)
		{
			this.addressFamily = family;
			this.socketType = type;
			this.protocolType = proto;
			
			this.m_Handle = safe_handle;
			this.is_connected = true;

			InitializeSockets ();	
		}

		void SocketDefaults ()
		{
			try {
				/* Need to test IPv6 further */
				if (addressFamily == AddressFamily.InterNetwork
					// || addressFamily == AddressFamily.InterNetworkV6
				) {
					/* This is the default, but it probably has nasty side
					 * effects on Linux, as the socket option is kludged by
					 * turning on or off PMTU discovery... */
					this.DontFragment = false;
					if (protocolType == ProtocolType.Tcp)
						this.NoDelay = false;
				// The socket was created successfully; enable IPV6_V6ONLY by default for normal AF_INET6 sockets.
				// This fails on raw sockets so we just let them be in default state.
				} else if (addressFamily == AddressFamily.InterNetworkV6 && socketType != SocketType.Raw) {
					this.DualMode = true;
				}

				/* Microsoft sets these to 8192, but we are going to keep them
				 * both to the OS defaults as these have a big performance impact.
				 * on WebClient performance. */
				// this.ReceiveBufferSize = 8192;
				// this.SendBufferSize = 8192;
			} catch (SocketException) {
			}
		}

		/* Creates a new system socket, returning the handle */
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static IntPtr Socket_icall (AddressFamily family, SocketType type, ProtocolType proto, out int error);

#endregion

#region Properties

		public int Available {
			get {
				ThrowIfDisposedAndClosed ();

				int ret, error;
				ret = Available_internal (m_Handle, out error);

				if (error != 0)
					throw new SocketException (error);

				return ret;
			}
		}

		static int Available_internal (SafeSocketHandle safeHandle, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return Available_icall (safeHandle.DangerousGetHandle (), out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		/* Returns the amount of data waiting to be read on socket */
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static int Available_icall (IntPtr socket, out int error);

		// FIXME: import from referencesource
		public bool EnableBroadcast {
			get {
				ThrowIfDisposedAndClosed ();

				if (protocolType != ProtocolType.Udp)
					throw new SocketException ((int) SocketError.ProtocolOption);

				return ((int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast)) != 0;
			}
			set {
				ThrowIfDisposedAndClosed ();

				if (protocolType != ProtocolType.Udp)
					throw new SocketException ((int) SocketError.ProtocolOption);

				SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, value ? 1 : 0);
			}
		}

		public bool IsBound {
			get {
				return is_bound;
			}
		}

		// FIXME: import from referencesource
		public bool MulticastLoopback {
			get {
				ThrowIfDisposedAndClosed ();

				/* Even though this option can be set for TCP sockets on Linux, throw
				 * this exception anyway to be compatible (the MSDN docs say
				 * "Setting this property on a Transmission Control Protocol (TCP)
				 * socket will have no effect." but the MS runtime throws the
				 * exception...) */
				if (protocolType == ProtocolType.Tcp)
					throw new SocketException ((int)SocketError.ProtocolOption);

				switch (addressFamily) {
				case AddressFamily.InterNetwork:
					return ((int) GetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)) != 0;
				case AddressFamily.InterNetworkV6:
					return ((int) GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback)) != 0;
				default:
					throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
				}
			}
			set {
				ThrowIfDisposedAndClosed ();

				/* Even though this option can be set for TCP sockets on Linux, throw
				 * this exception anyway to be compatible (the MSDN docs say
				 * "Setting this property on a Transmission Control Protocol (TCP)
				 * socket will have no effect." but the MS runtime throws the
				 * exception...) */
				if (protocolType == ProtocolType.Tcp)
					throw new SocketException ((int)SocketError.ProtocolOption);

				switch (addressFamily) {
				case AddressFamily.InterNetwork:
					SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, value ? 1 : 0);
					break;
				case AddressFamily.InterNetworkV6:
					SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback, value ? 1 : 0);
					break;
				default:
					throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
				}
			}
		}

		// Wish:  support non-IP endpoints.
		public EndPoint LocalEndPoint {
			get {
				ThrowIfDisposedAndClosed ();

				/* If the seed EndPoint is null, Connect, Bind, etc has not yet
				 * been called. MS returns null in this case. */
				if (seed_endpoint == null)
					return null;

				int error;
				SocketAddress sa = LocalEndPoint_internal (m_Handle, (int) addressFamily, out error);

				if (error != 0)
					throw new SocketException (error);

				return seed_endpoint.Create (sa);
			}
		}

		static SocketAddress LocalEndPoint_internal (SafeSocketHandle safeHandle, int family, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return LocalEndPoint_icall (safeHandle.DangerousGetHandle (), family, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		/* Returns the local endpoint details in addr and port */
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static SocketAddress LocalEndPoint_icall (IntPtr socket, int family, out int error);

		public bool Blocking {
			get { return is_blocking; }
			set {
				ThrowIfDisposedAndClosed ();

				int error;
				Blocking_internal (m_Handle, value, out error);

				if (error != 0)
					throw new SocketException (error);

				is_blocking = value;
			}
		}

		static void Blocking_internal (SafeSocketHandle safeHandle, bool block, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Blocking_icall (safeHandle.DangerousGetHandle (), block, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		internal extern static void Blocking_icall (IntPtr socket, bool block, out int error);

		public bool Connected {
			get { return is_connected; }
			internal set { is_connected = value; }
		}

		// FIXME: import from referencesource
		public bool NoDelay {
			get {
				ThrowIfDisposedAndClosed ();
				ThrowIfUdp ();

				return ((int) GetSocketOption (SocketOptionLevel.Tcp, SocketOptionName.NoDelay)) != 0;
			}

			set {
				ThrowIfDisposedAndClosed ();
				ThrowIfUdp ();
				SetSocketOption (SocketOptionLevel.Tcp, SocketOptionName.NoDelay, value ? 1 : 0);
			}
		}

		public EndPoint RemoteEndPoint {
			get {
				ThrowIfDisposedAndClosed ();

				/* If the seed EndPoint is null, Connect, Bind, etc has
				 * not yet been called. MS returns null in this case. */
				if (!is_connected || seed_endpoint == null)
					return null;

				int error;
				SocketAddress sa = RemoteEndPoint_internal (m_Handle, (int) addressFamily, out error);

				if (error != 0)
					throw new SocketException (error);

				return seed_endpoint.Create (sa);
			}
		}

		static SocketAddress RemoteEndPoint_internal (SafeSocketHandle safeHandle, int family, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return RemoteEndPoint_icall (safeHandle.DangerousGetHandle (), family, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		/* Returns the remote endpoint details in addr and port */
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static SocketAddress RemoteEndPoint_icall (IntPtr socket, int family, out int error);

		internal SafeHandle SafeHandle
		{
			get { return m_Handle; }
		}

#endregion

#region Select

		public static void Select (IList checkRead, IList checkWrite, IList checkError, int microSeconds)
		{
			var list = new List<Socket> ();
			AddSockets (list, checkRead, "checkRead");
			AddSockets (list, checkWrite, "checkWrite");
			AddSockets (list, checkError, "checkError");

			if (list.Count == 3)
				throw new ArgumentNullException ("checkRead, checkWrite, checkError", "All the lists are null or empty.");

			/* The 'sockets' array contains:
			 *  - READ socket 0-n, null,
			 *  - WRITE socket 0-n, null,
			 *  - ERROR socket 0-n, null */
			Socket [] sockets = list.ToArray ();

			int error;
			Select_icall (ref sockets, microSeconds, out error);

			if (error != 0)
				throw new SocketException (error);

			if (sockets == null) {
				if (checkRead != null)
					checkRead.Clear ();
				if (checkWrite != null)
					checkWrite.Clear ();
				if (checkError != null)
					checkError.Clear ();
				return;
			}

			int mode = 0;
			int count = sockets.Length;
			IList currentList = checkRead;
			int currentIdx = 0;
			for (int i = 0; i < count; i++) {
				Socket sock = sockets [i];
				if (sock == null) { // separator
					if (currentList != null) {
						// Remove non-signaled sockets after the current one
						int to_remove = currentList.Count - currentIdx;
						for (int k = 0; k < to_remove; k++)
							currentList.RemoveAt (currentIdx);
					}
					currentList = (mode == 0) ? checkWrite : checkError;
					currentIdx = 0;
					mode++;
					continue;
				}

				if (mode == 1 && currentList == checkWrite && !sock.is_connected) {
					if ((int) sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error) == 0)
						sock.is_connected = true;
				}

				/* Remove non-signaled sockets before the current one */
				while (((Socket) currentList [currentIdx]) != sock)
					currentList.RemoveAt (currentIdx);

				currentIdx++;
			}
		}

		static void AddSockets (List<Socket> sockets, IList list, string name)
		{
			if (list != null) {
				foreach (Socket sock in list) {
					if (sock == null) // MS throws a NullRef
						throw new ArgumentNullException (name, "Contains a null element");
					sockets.Add (sock);
				}
			}

			sockets.Add (null);
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void Select_icall (ref Socket [] sockets, int microSeconds, out int error);

#endregion

#region Poll

		public bool Poll (int microSeconds, SelectMode mode)
		{
			ThrowIfDisposedAndClosed ();

			if (mode != SelectMode.SelectRead && mode != SelectMode.SelectWrite && mode != SelectMode.SelectError)
				throw new NotSupportedException ("'mode' parameter is not valid.");

			int error;
			bool result = Poll_internal (m_Handle, mode, microSeconds, out error);

			if (error != 0)
				throw new SocketException (error);

			if (mode == SelectMode.SelectWrite && result && !is_connected) {
				/* Update the is_connected state; for non-blocking Connect()
				 * this is when we can find out that the connect succeeded. */
				if ((int) GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error) == 0)
					is_connected = true;
			}

			return result;
		}

		static bool Poll_internal (SafeSocketHandle safeHandle, SelectMode mode, int timeout, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return Poll_icall (safeHandle.DangerousGetHandle (), mode, timeout, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static bool Poll_icall (IntPtr socket, SelectMode mode, int timeout, out int error);

#endregion

#region Accept

		public Socket Accept()
		{
			ThrowIfDisposedAndClosed ();

			int error = 0;
			SafeSocketHandle safe_handle = Accept_internal (this.m_Handle, out error, is_blocking);

			if (error != 0) {
				if (is_closed)
					error = SOCKET_CLOSED_CODE;
				throw new SocketException(error);
			}

			Socket accepted = new Socket (this.AddressFamily, this.SocketType, this.ProtocolType, safe_handle) {
				seed_endpoint = this.seed_endpoint,
				Blocking = this.Blocking,
			};

			return accepted;
		}

		internal void Accept (Socket acceptSocket)
		{
			ThrowIfDisposedAndClosed ();

			int error = 0;
			SafeSocketHandle safe_handle = Accept_internal (this.m_Handle, out error, is_blocking);

			if (error != 0) {
				if (is_closed)
					error = SOCKET_CLOSED_CODE;
				throw new SocketException (error);
			}

			acceptSocket.addressFamily = this.AddressFamily;
			acceptSocket.socketType = this.SocketType;
			acceptSocket.protocolType = this.ProtocolType;
			acceptSocket.m_Handle = safe_handle;
			acceptSocket.is_connected = true;
			acceptSocket.seed_endpoint = this.seed_endpoint;
			acceptSocket.Blocking = this.Blocking;

			// FIXME: figure out what if anything else needs to be reset
		}

		public bool AcceptAsync (SocketAsyncEventArgs e)
		{
			// NO check is made whether e != null in MS.NET (NRE is thrown in such case)

			ThrowIfDisposedAndClosed ();

			if (!is_bound)
				throw new InvalidOperationException ("You must call the Bind method before performing this operation.");
			if (!is_listening)
				throw new InvalidOperationException ("You must call the Listen method before performing this operation.");
			if (e.BufferList != null)
				throw new ArgumentException ("Multiple buffers cannot be used with this method.");
			if (e.Count < 0)
				throw new ArgumentOutOfRangeException ("e.Count");

			Socket acceptSocket = e.AcceptSocket;
			if (acceptSocket != null) {
				if (acceptSocket.is_bound || acceptSocket.is_connected)
					throw new InvalidOperationException ("AcceptSocket: The socket must not be bound or connected.");
			}

			InitSocketAsyncEventArgs (e, AcceptAsyncCallback, e, SocketOperation.Accept);

			QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, e.socket_async_result));

			return true;
		}

		static AsyncCallback AcceptAsyncCallback = new AsyncCallback (ares => {
			SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;

			if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
				throw new InvalidOperationException ("No operation in progress");

			try {
				e.AcceptSocket = e.CurrentSocket.EndAccept (ares);
			} catch (SocketException ex) {
				e.SocketError = ex.SocketErrorCode;
			} catch (ObjectDisposedException) {
				e.SocketError = SocketError.OperationAborted;
			} finally {
				if (e.AcceptSocket == null)
					e.AcceptSocket = new Socket (e.CurrentSocket.AddressFamily, e.CurrentSocket.SocketType, e.CurrentSocket.ProtocolType, null);
				e.Complete_internal ();
			}
		});

		public IAsyncResult BeginAccept(AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (!is_bound || !is_listening)
				throw new InvalidOperationException ();

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Accept);

			QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptCallback, sockares));

			return sockares;
		}

		static IOAsyncCallback BeginAcceptCallback = new IOAsyncCallback (ares => {
			SocketAsyncResult sockares = (SocketAsyncResult) ares;
			Socket acc_socket = null;
			try {
				if (sockares.AcceptSocket == null) {
					acc_socket = sockares.socket.Accept ();
				} else {
					acc_socket = sockares.AcceptSocket;
					sockares.socket.Accept (acc_socket);
				}

			} catch (Exception e) {
				sockares.Complete (e);
				return;
			}
			sockares.Complete (acc_socket);
		});

		public IAsyncResult BeginAccept (Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (receiveSize < 0)
				throw new ArgumentOutOfRangeException ("receiveSize", "receiveSize is less than zero");

			if (acceptSocket != null) {
				ThrowIfDisposedAndClosed (acceptSocket);

				if (acceptSocket.IsBound)
					throw new InvalidOperationException ();

				/* For some reason the MS runtime
				 * barfs if the new socket is not TCP,
				 * even though it's just about to blow
				 * away all those parameters
				 */
				if (acceptSocket.ProtocolType != ProtocolType.Tcp)
					throw new SocketException ((int)SocketError.InvalidArgument);
			}

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.AcceptReceive) {
				Buffer = new byte [receiveSize],
				Offset = 0,
				Size = receiveSize,
				SockFlags = SocketFlags.None,
				AcceptSocket = acceptSocket,
			};

			QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginAcceptReceiveCallback, sockares));

			return sockares;
		}

		static IOAsyncCallback BeginAcceptReceiveCallback = new IOAsyncCallback (ares => {
			SocketAsyncResult sockares = (SocketAsyncResult) ares;
			Socket acc_socket = null;

			try {
				if (sockares.AcceptSocket == null) {
					acc_socket = sockares.socket.Accept ();
				} else {
					acc_socket = sockares.AcceptSocket;
					sockares.socket.Accept (acc_socket);
				}
			} catch (Exception e) {
				sockares.Complete (e);
				return;
			}

			/* It seems the MS runtime special-cases 0-length requested receive data.  See bug 464201. */
			int total = 0;
			if (sockares.Size > 0) {
				try {
					SocketError error;
					total = acc_socket.Receive (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out error);
					if (error != 0) {
						sockares.Complete (new SocketException ((int) error));
						return;
					}
				} catch (Exception e) {
					sockares.Complete (e);
					return;
				}
			}

			sockares.Complete (acc_socket, total);
		});

		public Socket EndAccept (IAsyncResult asyncResult)
		{
			int bytes;
			byte[] buffer;
			return EndAccept (out buffer, out bytes, asyncResult);
		}

		public Socket EndAccept (out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
		{
			ThrowIfDisposedAndClosed ();

			SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndAccept", "asyncResult");

			if (!sockares.IsCompleted)
				sockares.AsyncWaitHandle.WaitOne ();

			sockares.CheckIfThrowDelayedException ();

			buffer = sockares.Buffer.ToArray ();
			bytesTransferred = sockares.Total;

			return sockares.AcceptedSocket;
		}

		static SafeSocketHandle Accept_internal (SafeSocketHandle safeHandle, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				var ret = Accept_icall (safeHandle.DangerousGetHandle (), out error, blocking);
				return new SafeSocketHandle (ret, true);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}

		/* Creates a new system socket, returning the handle */
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static IntPtr Accept_icall (IntPtr sock, out int error, bool blocking);

#endregion

#region Bind

		public void Bind (EndPoint localEP)
		{
#if FEATURE_NO_BSD_SOCKETS
			throw new PlatformNotSupportedException ("System.Net.Sockets.Socket:Bind is not supported on this platform.");
#else
			ThrowIfDisposedAndClosed ();

			if (localEP == null)
				throw new ArgumentNullException("localEP");
				
			var ipEndPoint = localEP as IPEndPoint;
			if (ipEndPoint != null) {
				localEP = RemapIPEndPoint (ipEndPoint);	
			}
			
			int error;
			Bind_internal (m_Handle, localEP.Serialize(), out error);

			if (error != 0)
				throw new SocketException (error);
			if (error == 0)
				is_bound = true;

			seed_endpoint = localEP;
#endif // FEATURE_NO_BSD_SOCKETS
		}

		private static void Bind_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Bind_icall (safeHandle.DangerousGetHandle (), sa, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		// Creates a new system socket, returning the handle
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		private extern static void Bind_icall (IntPtr sock, SocketAddress sa, out int error);

#endregion

#region Listen

		public void Listen (int backlog)
		{
			ThrowIfDisposedAndClosed ();

			if (!is_bound)
				throw new SocketException ((int) SocketError.InvalidArgument);

			int error;
			Listen_internal(m_Handle, backlog, out error);

			if (error != 0)
				throw new SocketException (error);

			is_listening = true;
		}

		static void Listen_internal (SafeSocketHandle safeHandle, int backlog, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Listen_icall (safeHandle.DangerousGetHandle (), backlog, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void Listen_icall (IntPtr sock, int backlog, out int error);

#endregion

#region Connect

		public void Connect (IPAddress address, int port)
		{
			Connect (new IPEndPoint (address, port));
		}

		public void Connect (string host, int port)
		{
			Connect (Dns.GetHostAddresses (host), port);
		}

		public void Connect (EndPoint remoteEP)
		{
			ThrowIfDisposedAndClosed ();

			if (remoteEP == null)
				throw new ArgumentNullException ("remoteEP");

			IPEndPoint ep = remoteEP as IPEndPoint;
			/* Dgram uses Any to 'disconnect' */
			if (ep != null && socketType != SocketType.Dgram) {
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
					throw new SocketException ((int) SocketError.AddressNotAvailable);
			}

			if (is_listening)
				throw new InvalidOperationException ();
				
			if (ep != null) {
				remoteEP = RemapIPEndPoint (ep);
			}

			SocketAddress serial = remoteEP.Serialize ();

			int error = 0;
			Connect_internal (m_Handle, serial, out error, is_blocking);

			if (error == 0 || error == 10035)
				seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets

			if (error != 0) {
				if (is_closed)
					error = SOCKET_CLOSED_CODE;
				throw new SocketException (error);
			}

			is_connected = !(socketType == SocketType.Dgram && ep != null && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)));
			is_bound = true;
		}

		public bool ConnectAsync (SocketAsyncEventArgs e)
		{
			// NO check is made whether e != null in MS.NET (NRE is thrown in such case)

			ThrowIfDisposedAndClosed ();

			if (is_listening)
				throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
			if (e.RemoteEndPoint == null)
				throw new ArgumentNullException ("remoteEP");

			InitSocketAsyncEventArgs (e, null, e, SocketOperation.Connect);

			try {
				IPAddress [] addresses;
				SocketAsyncResult ares;
				bool pending;

				/*
				 * Both BeginSConnect() and BeginMConnect() now return a `bool` indicating whether or
				 * not an async operation is pending.
				 */

				if (!GetCheckedIPs (e, out addresses)) {
					//NOTE: DualMode may cause Socket's RemoteEndpoint to differ in AddressFamily from the
					// SocketAsyncEventArgs, but the SocketAsyncEventArgs itself is not changed

					ares = new SocketAsyncResult (this, ConnectAsyncCallback, e, SocketOperation.Connect) {
						EndPoint = e.RemoteEndPoint
					};

					pending = BeginSConnect (ares);
				} else {
					DnsEndPoint dep = (DnsEndPoint)e.RemoteEndPoint;

					if (addresses == null)
						throw new ArgumentNullException ("addresses");
					if (addresses.Length == 0)
						throw new ArgumentException ("Empty addresses list");
					if (this.AddressFamily != AddressFamily.InterNetwork && this.AddressFamily != AddressFamily.InterNetworkV6)
						throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
					if (dep.Port <= 0 || dep.Port > 65535)
						throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");

					ares = new SocketAsyncResult (this, ConnectAsyncCallback, e, SocketOperation.Connect) {
						Addresses = addresses,
						Port = dep.Port,
					};

					is_connected = false;

					pending = BeginMConnect (ares);
				}

				if (!pending) {
					/*
					 * On synchronous completion, the async callback will not be invoked.
					 *
					 * We need to call `EndConnect ()` here to close the socket and make sure
					 * that any pending exceptions are properly propagated.
					 *
					 * Note that we're not calling `e.Complete ()` (or resetting `e.in_progress`) here.
					 */
					e.CurrentSocket.EndConnect (ares);
				}

				return pending;
			} catch (SocketException exc) {
				e.SocketError = exc.SocketErrorCode;
				e.socket_async_result.Complete (exc, true);
				return false;
			} catch (Exception exc) {
				e.socket_async_result.Complete (exc, true);
				return false;
			}
		}

		public static void CancelConnectAsync (SocketAsyncEventArgs e)
		{
			if (e == null)
				throw new ArgumentNullException("e");

			if (e.in_progress != 0 && e.LastOperation == SocketAsyncOperation.Connect)
				e.CurrentSocket?.Close ();
		}

		static AsyncCallback ConnectAsyncCallback = new AsyncCallback (ares => {
			SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;

			if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
				throw new InvalidOperationException ("No operation in progress");

			try {
				e.CurrentSocket.EndConnect (ares);
			} catch (SocketException se) {
				e.SocketError = se.SocketErrorCode;
			} catch (ObjectDisposedException) {
				e.SocketError = SocketError.OperationAborted;
			} finally {
				e.Complete_internal ();
			}
		});

		public IAsyncResult BeginConnect (string host, int port, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (host == null)
				throw new ArgumentNullException ("host");
			if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6)
				throw new NotSupportedException ("This method is valid only for sockets in the InterNetwork and InterNetworkV6 families");
			if (port <= 0 || port > 65535)
				throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
			if (is_listening)
				throw new InvalidOperationException ();

			var sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
				Port = port
			};

			var dnsRequest = Dns.GetHostAddressesAsync (host);
			dnsRequest.ContinueWith (t => {
				if (t.IsFaulted)
					sockares.Complete (t.Exception.InnerException);
				else if (t.IsCanceled)
					sockares.Complete (new OperationCanceledException ());
				else {
					sockares.Addresses = t.Result;
					BeginMConnect (sockares);
				}
			}, TaskScheduler.Default);

			return sockares;
		}

		public IAsyncResult BeginConnect (EndPoint remoteEP, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (remoteEP == null)
				throw new ArgumentNullException ("remoteEP");
			if (is_listening)
				throw new InvalidOperationException ();

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
				EndPoint = remoteEP,
			};

			BeginSConnect (sockares);
			return sockares;
		}

		public IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (addresses == null)
				throw new ArgumentNullException ("addresses");
			if (addresses.Length == 0)
				throw new ArgumentException ("Empty addresses list");
			if (this.AddressFamily != AddressFamily.InterNetwork && this.AddressFamily != AddressFamily.InterNetworkV6)
				throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
			if (port <= 0 || port > 65535)
				throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
			if (is_listening)
				throw new InvalidOperationException ();

			SocketAsyncResult sockares = new SocketAsyncResult (this, requestCallback, state, SocketOperation.Connect) {
				Addresses = addresses,
				Port = port,
			};

			is_connected = false;

			BeginMConnect (sockares);
			return sockares;
		}

		static bool BeginMConnect (SocketAsyncResult sockares)
		{
			Exception exc = null;

			for (int i = sockares.CurrentAddress; i < sockares.Addresses.Length; i++) {
				try {
					sockares.CurrentAddress++;
					sockares.EndPoint = new IPEndPoint (sockares.Addresses [i], sockares.Port);

					if (!sockares.socket.CanTryAddressFamily(sockares.EndPoint.AddressFamily))
						continue;

					return BeginSConnect (sockares);
				} catch (Exception e) {
					exc = e;
				}
			}

			sockares.Complete (exc, true);
			return false;
			throw exc;
		}

		static bool BeginSConnect (SocketAsyncResult sockares)
		{
			EndPoint remoteEP = sockares.EndPoint;
			// Bug #75154: Connect() should not succeed for .Any addresses.
			if (remoteEP is IPEndPoint) {
				IPEndPoint ep = (IPEndPoint) remoteEP;
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
					sockares.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
					return false;
				}

				sockares.EndPoint = remoteEP = sockares.socket.RemapIPEndPoint (ep);
			}

			if (!sockares.socket.CanTryAddressFamily(sockares.EndPoint.AddressFamily)) {
				sockares.Complete (new ArgumentException(SR.net_invalidAddressList), true);
				return false;
			}

			int error = 0;

			if (sockares.socket.connect_in_progress) {
				// This could happen when multiple IPs are used
				// Calling connect() again will reset the connection attempt and cause
				// an error. Better to just close the socket and move on.
				sockares.socket.connect_in_progress = false;
				sockares.socket.m_Handle.Dispose ();
				sockares.socket.m_Handle = new SafeSocketHandle (Socket_icall (sockares.socket.addressFamily, sockares.socket.socketType, sockares.socket.protocolType, out error), true);
				if (error != 0) {
					sockares.Complete (new SocketException (error), true);
					return false;
				}
			}

			bool blk = sockares.socket.is_blocking;
			if (blk)
				sockares.socket.Blocking = false;
			Connect_internal (sockares.socket.m_Handle, remoteEP.Serialize (), out error, false);
			if (blk)
				sockares.socket.Blocking = true;

			if (error == 0) {
				// succeeded synch
				sockares.socket.is_connected = true;
				sockares.socket.is_bound = true;
				sockares.Complete (true);
				return false;
			}

			if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
				// error synch
				sockares.socket.is_connected = false;
				sockares.socket.is_bound = false;
				sockares.Complete (new SocketException (error), true);
				return false;
			}

			// continue asynch
			sockares.socket.is_connected = false;
			sockares.socket.is_bound = false;
			sockares.socket.connect_in_progress = true;

			IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginConnectCallback, sockares));
			return true;
		}

		static IOAsyncCallback BeginConnectCallback = new IOAsyncCallback (ares => {
			SocketAsyncResult sockares = (SocketAsyncResult) ares;

			if (sockares.EndPoint == null) {
				sockares.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
				return;
			}

			try {
				int error = (int) sockares.socket.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);

				if (error == 0) {
					sockares.socket.seed_endpoint = sockares.EndPoint;
					sockares.socket.is_connected = true;
					sockares.socket.is_bound = true;
					sockares.socket.connect_in_progress = false;
					sockares.error = 0;
					sockares.Complete ();
					return;
				}

				if (sockares.Addresses == null) {
					sockares.socket.connect_in_progress = false;
					sockares.Complete (new SocketException (error));
					return;
				}

				if (sockares.CurrentAddress >= sockares.Addresses.Length) {
					sockares.Complete (new SocketException (error));
					return;
				}

				BeginMConnect (sockares);
			} catch (Exception e) {
				sockares.socket.connect_in_progress = false;
				sockares.Complete (e);
			}
		});

		public void EndConnect (IAsyncResult asyncResult)
		{
			ThrowIfDisposedAndClosed ();

			SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndConnect", "asyncResult");

			if (!sockares.IsCompleted)
				sockares.AsyncWaitHandle.WaitOne();

			sockares.CheckIfThrowDelayedException();
		}

		static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				Connect_icall (safeHandle.DangerousGetHandle (), sa, out error, blocking);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}

		/* Connects to the remote address */
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void Connect_icall (IntPtr sock, SocketAddress sa, out int error, bool blocking);

		/* Returns :
		 *  - false when it is ok to use RemoteEndPoint
		 *  - true when addresses must be used (and addresses could be null/empty) */
		bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
		{
			addresses = null;

			// Connect to the first address that match the host name, like:
			// http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
			// while skipping entries that do not match the address family
			DnsEndPoint dep = e.RemoteEndPoint as DnsEndPoint;
			if (dep != null) {
				addresses = Dns.GetHostAddresses (dep.Host);

				if (dep.AddressFamily == AddressFamily.Unspecified)
					return true;

				int last_valid = 0;
				for (int i = 0; i < addresses.Length; ++i) {
					if (addresses [i].AddressFamily != dep.AddressFamily)
						continue;

					addresses [last_valid++] = addresses [i];
				}

				if (last_valid != addresses.Length)
					Array.Resize (ref addresses, last_valid);
				return true;
			} else {
				e.SetConnectByNameError (null);
				return false;
			}
		}

#endregion

#region Disconnect

		/* According to the docs, the MS runtime will throw PlatformNotSupportedException
		 * if the platform is newer than w2k.  We should be able to cope... */
		public void Disconnect (bool reuseSocket)
		{
			ThrowIfDisposedAndClosed ();

			int error = 0;
			Disconnect_internal (m_Handle, reuseSocket, out error);

			if (error != 0) {
				if (error == 50) {
					/* ERROR_NOT_SUPPORTED */
					throw new PlatformNotSupportedException ();
				} else {
					throw new SocketException (error);
				}
			}

			is_connected = false;
			if (reuseSocket) {
				/* Do managed housekeeping here... */
			}
		}

		public bool DisconnectAsync (SocketAsyncEventArgs e)
		{
			// NO check is made whether e != null in MS.NET (NRE is thrown in such case)

			ThrowIfDisposedAndClosed ();

			InitSocketAsyncEventArgs (e, DisconnectAsyncCallback, e, SocketOperation.Disconnect);

			IOSelector.Add (e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, e.socket_async_result));

			return true;
		}

		static AsyncCallback DisconnectAsyncCallback = new AsyncCallback (ares => {
			SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;

			if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
				throw new InvalidOperationException ("No operation in progress");

			try {
				e.CurrentSocket.EndDisconnect (ares);
			} catch (SocketException ex) {
				e.SocketError = ex.SocketErrorCode;
			} catch (ObjectDisposedException) {
				e.SocketError = SocketError.OperationAborted;
			} finally {
				e.Complete_internal ();
			}
		});

		public IAsyncResult BeginDisconnect (bool reuseSocket, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Disconnect) {
				ReuseSocket = reuseSocket,
			};

			IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, sockares));

			return sockares;
		}

		static IOAsyncCallback BeginDisconnectCallback = new IOAsyncCallback (ares => {
			SocketAsyncResult sockares = (SocketAsyncResult) ares;

			try {
				sockares.socket.Disconnect (sockares.ReuseSocket);
			} catch (Exception e) {
				sockares.Complete (e);
				return;
			}

			sockares.Complete ();
		});

		public void EndDisconnect (IAsyncResult asyncResult)
		{
			ThrowIfDisposedAndClosed ();

			SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndDisconnect", "asyncResult");

			if (!sockares.IsCompleted)
				sockares.AsyncWaitHandle.WaitOne ();

			sockares.CheckIfThrowDelayedException ();
		}

		static void Disconnect_internal (SafeSocketHandle safeHandle, bool reuse, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Disconnect_icall (safeHandle.DangerousGetHandle (), reuse, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void Disconnect_icall (IntPtr sock, bool reuse, out int error);

#endregion

#region Receive

		public int Receive (byte [] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			int nativeError;
			int ret;
			unsafe {
				fixed (byte* pbuffer = buffer) {
					ret = Receive_internal (m_Handle, &pbuffer[offset], size, socketFlags, out nativeError, is_blocking);
				}
			}

			errorCode = (SocketError) nativeError;
			if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
				is_connected = false;
				is_bound = false;
			} else {
				is_connected = true;
			}

			return ret;
		}

		int Receive (Memory<byte> buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
		{
			ThrowIfDisposedAndClosed ();

			int nativeError;
			int ret;
			unsafe {
				using (var handle = buffer.Slice (offset, size).Pin ()) {
					ret = Receive_internal (m_Handle, (byte*)handle.Pointer, size, socketFlags, out nativeError, is_blocking);
				}
			}

			errorCode = (SocketError) nativeError;
			if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
				is_connected = false;
				is_bound = false;
			} else {
				is_connected = true;
			}

			return ret;
		}

		[CLSCompliant (false)]
		public int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
		{
			ThrowIfDisposedAndClosed ();

			if (buffers == null || buffers.Count == 0)
				throw new ArgumentNullException ("buffers");

			int numsegments = buffers.Count;
			int nativeError;
			int ret;

			GCHandle[] gch = new GCHandle[numsegments];
			try {
				unsafe {
					fixed (WSABUF* bufarray = new WSABUF[numsegments]) {
						for (int i = 0; i < numsegments; i++) {
							ArraySegment<byte> segment = buffers[i];

							if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
								throw new ArgumentOutOfRangeException ("segment");

							try {} finally {
								gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
							}

							bufarray[i].len = segment.Count;
							bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
						}

						ret = Receive_internal (m_Handle, bufarray, numsegments, socketFlags, out nativeError, is_blocking);
					}
				}
			} finally {
				for (int i = 0; i < numsegments; i++) {
					if (gch[i].IsAllocated)
						gch[i].Free ();
				}
			}

			errorCode = (SocketError) nativeError;

			return ret;
		}

		public int Receive(Span<byte> buffer, SocketFlags socketFlags, out SocketError errorCode)
		{
			byte[] tempBuffer = new byte[buffer.Length];
			int result = Receive(tempBuffer, 0, tempBuffer.Length, socketFlags, out errorCode);
			tempBuffer.CopyTo (buffer);
			return result;
		}

		public int Send(ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out SocketError errorCode)
		{
			byte[] bufferBytes = buffer.ToArray();
			return Send(bufferBytes, 0, bufferBytes.Length, socketFlags, out errorCode);
		}

		public int Receive (Span<byte> buffer, SocketFlags socketFlags)
		{
			byte[] tempBuffer = new byte[buffer.Length];
			int ret = Receive (tempBuffer, SocketFlags.None);
			tempBuffer.CopyTo (buffer);
			return ret;
		}

		public int Receive (Span<byte> buffer) => Receive (buffer, SocketFlags.None);

		public bool ReceiveAsync (SocketAsyncEventArgs e)
		{
			// NO check is made whether e != null in MS.NET (NRE is thrown in such case)

			ThrowIfDisposedAndClosed ();

			// LAME SPEC: the ArgumentException is never thrown, instead an NRE is
			// thrown when e.Buffer and e.BufferList are null (works fine when one is
			// set to a valid object)
			if (e.MemoryBuffer.Equals (default) && e.BufferList == null)
				throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");

			if (e.BufferList != null) {
				InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.ReceiveGeneric);

				e.socket_async_result.Buffers = e.BufferList;

				QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, e.socket_async_result));
			} else {
				InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.Receive);

				e.socket_async_result.Buffer = e.MemoryBuffer;
				e.socket_async_result.Offset = e.Offset;
				e.socket_async_result.Size = e.Count;

				QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, e.socket_async_result));
			}

			return true;
		}

		static AsyncCallback ReceiveAsyncCallback = new AsyncCallback (ares => {
			SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;

			if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
				throw new InvalidOperationException ("No operation in progress");

			try {
				e.SetBytesTransferred (e.CurrentSocket.EndReceive (ares));
			} catch (SocketException se){
				e.SocketError = se.SocketErrorCode;
			} catch (ObjectDisposedException) {
				e.SocketError = SocketError.OperationAborted;
			} finally {
				e.Complete_internal ();
			}
		});

		public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			/* As far as I can tell from the docs and from experimentation, a pointer to the
			 * SocketError parameter is not supposed to be saved for the async parts.  And as we don't
			 * set any socket errors in the setup code, we just have to set it to Success. */
			errorCode = SocketError.Success;

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Receive) {
				Buffer = buffer,
				Offset = offset,
				Size = size,
				SockFlags = socketFlags,
			};

			QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, sockares));

			return sockares;
		}

		static IOAsyncCallback BeginReceiveCallback = new IOAsyncCallback (ares => {
			SocketAsyncResult sockares = (SocketAsyncResult) ares;
			int total = 0;

			try {
				unsafe {
					using (var pbuffer = sockares.Buffer.Slice (sockares.Offset, sockares.Size).Pin ()) {
						total = Receive_internal (sockares.socket.m_Handle, (byte*)pbuffer.Pointer, sockares.Size, sockares.SockFlags, out sockares.error, sockares.socket.is_blocking);
					}
				}
			} catch (Exception e) {
				sockares.Complete (e);
				return;
			}

			sockares.Complete (total);
		});

		[CLSCompliant (false)]
		public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (buffers == null)
				throw new ArgumentNullException ("buffers");

			/* I assume the same SocketError semantics as above */
			errorCode = SocketError.Success;

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveGeneric) {
				Buffers = buffers,
				SockFlags = socketFlags,
			};

			QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, sockares));

			return sockares;
		}

		static IOAsyncCallback BeginReceiveGenericCallback = new IOAsyncCallback (ares => {
			SocketAsyncResult sockares = (SocketAsyncResult) ares;
			int total = 0;

			try {
				total = sockares.socket.Receive (sockares.Buffers, sockares.SockFlags);
			} catch (Exception e) {
				sockares.Complete (e);
				return;
			}

			sockares.Complete (total);
		});

		public int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
		{
			ThrowIfDisposedAndClosed ();

			SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceive", "asyncResult");

			if (!sockares.IsCompleted)
				sockares.AsyncWaitHandle.WaitOne ();

			errorCode = sockares.ErrorCode;

			if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress)
				is_connected = false;

			// If no socket error occurred, call CheckIfThrowDelayedException in case there are other
			// kinds of exceptions that should be thrown.
			if (errorCode == SocketError.Success)
				sockares.CheckIfThrowDelayedException();

			return sockares.Total;
		}

		static unsafe int Receive_internal (SafeSocketHandle safeHandle, WSABUF* bufarray, int count, SocketFlags flags, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return Receive_array_icall (safeHandle.DangerousGetHandle (), bufarray, count, flags, out error, blocking);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}

		[MethodImplAttribute (MethodImplOptions.InternalCall)]
		extern static unsafe int Receive_array_icall (IntPtr sock, WSABUF* bufarray, int count, SocketFlags flags, out int error, bool blocking);

		static unsafe int Receive_internal (SafeSocketHandle safeHandle, byte* buffer, int count, SocketFlags flags, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return Receive_icall (safeHandle.DangerousGetHandle (), buffer, count, flags, out error, blocking);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static unsafe int Receive_icall (IntPtr sock, byte* buffer, int count, SocketFlags flags, out int error, bool blocking);

#endregion

#region ReceiveFrom

		public int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			if (remoteEP == null)
				throw new ArgumentNullException ("remoteEP");

			SocketError errorCode;
			int ret = ReceiveFrom (buffer, offset, size, socketFlags, ref remoteEP, out errorCode);

			if (errorCode != SocketError.Success)
				throw new SocketException (errorCode);

			return ret;
		}

		internal int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, out SocketError errorCode)
		{
			SocketAddress sockaddr = remoteEP.Serialize();

			int nativeError;
			int cnt;
			unsafe {
				fixed (byte* pbuffer = buffer) {
					cnt = ReceiveFrom_internal (m_Handle, &pbuffer[offset], size, socketFlags, ref sockaddr, out nativeError, is_blocking);
				}
			}

			errorCode = (SocketError) nativeError;
			if (errorCode != SocketError.Success) {
				if (errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
					is_connected = false;
				} else if (errorCode == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
					errorCode = SocketError.TimedOut;
				}

				return 0;
			}

			is_connected = true;
			is_bound = true;

			/* If sockaddr is null then we're a connection oriented protocol and should ignore the
			 * remoteEP parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
			if (sockaddr != null) {
				/* Stupidly, EndPoint.Create() is an instance method */
				remoteEP = remoteEP.Create (sockaddr);
			}

			seed_endpoint = remoteEP;

			return cnt;
		}

		int ReceiveFrom (Memory<byte> buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, out SocketError errorCode)
		{
			SocketAddress sockaddr = remoteEP.Serialize();

			int nativeError;
			int cnt;
			unsafe {
				using (var handle = buffer.Slice (offset, size).Pin ()) {
					cnt = ReceiveFrom_internal (m_Handle, (byte*)handle.Pointer, size, socketFlags, ref sockaddr, out nativeError, is_blocking);
				}
			}

			errorCode = (SocketError) nativeError;
			if (errorCode != SocketError.Success) {
				if (errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
					is_connected = false;
				} else if (errorCode == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
					errorCode = SocketError.TimedOut;
				}

				return 0;
			}

			is_connected = true;
			is_bound = true;

			/* If sockaddr is null then we're a connection oriented protocol and should ignore the
			 * remoteEP parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
			if (sockaddr != null) {
				/* Stupidly, EndPoint.Create() is an instance method */
				remoteEP = remoteEP.Create (sockaddr);
			}

			seed_endpoint = remoteEP;

			return cnt;
		}

		public bool ReceiveFromAsync (SocketAsyncEventArgs e)
		{
			ThrowIfDisposedAndClosed ();

			// We do not support recv into multiple buffers yet
			if (e.BufferList != null)
				throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
			if (e.RemoteEndPoint == null)
				throw new ArgumentNullException ("remoteEP", "Value cannot be null.");

			InitSocketAsyncEventArgs (e, ReceiveFromAsyncCallback, e, SocketOperation.ReceiveFrom);

			e.socket_async_result.Buffer = e.Buffer;
			e.socket_async_result.Offset = e.Offset;
			e.socket_async_result.Size = e.Count;
			e.socket_async_result.EndPoint = e.RemoteEndPoint;
			e.socket_async_result.SockFlags = e.SocketFlags;

			QueueIOSelectorJob (ReadSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, e.socket_async_result));

			return true;
		}

		static AsyncCallback ReceiveFromAsyncCallback = new AsyncCallback (ares => {
			SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;

			if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
				throw new InvalidOperationException ("No operation in progress");

			try {
				e.SetBytesTransferred (e.CurrentSocket.EndReceiveFrom_internal ((SocketAsyncResult)ares, e));
			} catch (SocketException ex) {
				e.SocketError = ex.SocketErrorCode;
			} catch (ObjectDisposedException) {
				e.SocketError = SocketError.OperationAborted;
			} finally {
				e.Complete_internal ();
			}
		});

		public IAsyncResult BeginReceiveFrom (byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			if (remoteEP == null)
				throw new ArgumentNullException ("remoteEP");

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveFrom) {
				Buffer = buffer,
				Offset = offset,
				Size = size,
				SockFlags = socketFlags,
				EndPoint = remoteEP,
			};

			QueueIOSelectorJob (ReadSem, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, sockares));

			return sockares;
		}

		static IOAsyncCallback BeginReceiveFromCallback = new IOAsyncCallback (ares => {
			SocketAsyncResult sockares = (SocketAsyncResult) ares;
			int total = 0;

			try {
				SocketError errorCode;
				total = sockares.socket.ReceiveFrom (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, ref sockares.EndPoint, out errorCode);

				if (errorCode != SocketError.Success) {
					sockares.Complete (new SocketException (errorCode));
					return;
				}
			} catch (Exception e) {
				sockares.Complete (e);
				return;
			}

			sockares.Complete (total);
		});

		public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint)
		{
			ThrowIfDisposedAndClosed ();

			if (endPoint == null)
				throw new ArgumentNullException ("endPoint");

			SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceiveFrom", "asyncResult");

			if (!sockares.IsCompleted)
				sockares.AsyncWaitHandle.WaitOne();

			sockares.CheckIfThrowDelayedException();

			endPoint = sockares.EndPoint;

			return sockares.Total;
		}

		int EndReceiveFrom_internal (SocketAsyncResult sockares, SocketAsyncEventArgs ares)
		{
			ThrowIfDisposedAndClosed ();

			if (Interlocked.CompareExchange (ref sockares.EndCalled, 1, 0) == 1)
				throw new InvalidOperationException ("EndReceiveFrom can only be called once per asynchronous operation");

			if (!sockares.IsCompleted)
				sockares.AsyncWaitHandle.WaitOne ();

			sockares.CheckIfThrowDelayedException ();
			ares.RemoteEndPoint = sockares.EndPoint;
			return sockares.Total;
		}

		static unsafe int ReceiveFrom_internal (SafeSocketHandle safeHandle, byte* buffer, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return ReceiveFrom_icall (safeHandle.DangerousGetHandle (), buffer, count, flags, ref sockaddr, out error, blocking);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static unsafe int ReceiveFrom_icall (IntPtr sock, byte* buffer, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error, bool blocking);

#endregion

#region ReceiveMessageFrom

		[MonoTODO ("Not implemented")]
		public int ReceiveMessageFrom (byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			if (remoteEP == null)
				throw new ArgumentNullException ("remoteEP");

			// FIXME: figure out how we get hold of the IPPacketInformation
			throw new NotImplementedException ();
		}

		[MonoTODO ("Not implemented")]
		public bool ReceiveMessageFromAsync (SocketAsyncEventArgs e)
		{
			// NO check is made whether e != null in MS.NET (NRE is thrown in such case)

			ThrowIfDisposedAndClosed ();

			throw new NotImplementedException ();
		}

		[MonoTODO]
		public IAsyncResult BeginReceiveMessageFrom (byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			if (remoteEP == null)
				throw new ArgumentNullException ("remoteEP");

			throw new NotImplementedException ();
		}

		[MonoTODO]
		public int EndReceiveMessageFrom (IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
		{
			ThrowIfDisposedAndClosed ();

			if (endPoint == null)
				throw new ArgumentNullException ("endPoint");

			/*SocketAsyncResult sockares =*/ ValidateEndIAsyncResult (asyncResult, "EndReceiveMessageFrom", "asyncResult");

			throw new NotImplementedException ();
		}

#endregion

#region Send

		public int Send (byte [] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			if (size == 0) {
				errorCode = SocketError.Success;
				return 0;
			}

			int nativeError;
			int sent = 0;
			do {
				unsafe {
					fixed (byte *pbuffer = buffer) {
						sent += Send_internal (m_Handle, &pbuffer[offset + sent], size - sent, socketFlags, out nativeError, is_blocking);
					}
				}

				errorCode = (SocketError)nativeError;
				if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
					is_connected = false;
					is_bound = false;
					break;
				} else {
					is_connected = true;
				}
			} while (sent < size);

			return sent;
		}

		[CLSCompliant (false)]
		public int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
		{
			ThrowIfDisposedAndClosed ();

			if (buffers == null)
				throw new ArgumentNullException ("buffers");
			if (buffers.Count == 0)
				throw new ArgumentException ("Buffer is empty", "buffers");

			int numsegments = buffers.Count;
			int nativeError;
			int ret;

			GCHandle[] gch = new GCHandle[numsegments];
			try {
				unsafe {
					fixed (WSABUF* bufarray = new WSABUF[numsegments]) {
						for(int i = 0; i < numsegments; i++) {
							ArraySegment<byte> segment = buffers[i];

							if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
								throw new ArgumentOutOfRangeException ("segment");

							try {} finally {
								gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
							}

							bufarray[i].len = segment.Count;
							bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
						}

						ret = Send_internal (m_Handle, bufarray, numsegments, socketFlags, out nativeError, is_blocking);
					}
				}
			} finally {
				for (int i = 0; i < numsegments; i++) {
					if (gch[i].IsAllocated)
						gch[i].Free();
				}
			}

			errorCode = (SocketError)nativeError;

			return ret;
		}

		public int Send (ReadOnlySpan<byte> buffer, SocketFlags socketFlags)
		{
			return Send (buffer.ToArray(), socketFlags);
		}

		public int Send (ReadOnlySpan<byte> buffer) => Send (buffer, SocketFlags.None);

		public bool SendAsync (SocketAsyncEventArgs e)
		{
			// NO check is made whether e != null in MS.NET (NRE is thrown in such case)

			ThrowIfDisposedAndClosed ();

			if (e.MemoryBuffer.Equals (default) && e.BufferList == null)
				throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");

			if (e.BufferList != null) {
				InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.SendGeneric);

				e.socket_async_result.Buffers = e.BufferList;

				QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, e.socket_async_result));
			} else {
				InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.Send);

				e.socket_async_result.Buffer = e.MemoryBuffer;
				e.socket_async_result.Offset = e.Offset;
				e.socket_async_result.Size = e.Count;

				QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
			}

			return true;
		}

		static AsyncCallback SendAsyncCallback = new AsyncCallback (ares => {
			SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;

			if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
				throw new InvalidOperationException ("No operation in progress");

			try {
				e.SetBytesTransferred (e.CurrentSocket.EndSend (ares));
			} catch (SocketException se){
				e.SocketError = se.SocketErrorCode;
			} catch (ObjectDisposedException) {
				e.SocketError = SocketError.OperationAborted;
			} finally {
				e.Complete_internal ();
			}
		});

		public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			if (!is_connected) {
				errorCode = SocketError.NotConnected;
				return null;
			}

			errorCode = SocketError.Success;

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Send) {
				Buffer = buffer,
				Offset = offset,
				Size = size,
				SockFlags = socketFlags,
			};

			QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), sockares));

			return sockares;
		}

		static void BeginSendCallback (SocketAsyncResult sockares, int sent_so_far)
		{
			int total = 0;

			try {
				unsafe {
					using (var pbuffer = sockares.Buffer.Slice (sockares.Offset, sockares.Size).Pin ()) {
						total = Socket.Send_internal (sockares.socket.m_Handle, (byte*)pbuffer.Pointer, sockares.Size, sockares.SockFlags, out sockares.error, false);
					}
				}
			} catch (Exception e) {
				sockares.Complete (e);
				return;
			}

			if (sockares.error == 0) {
				sent_so_far += total;
				sockares.Offset += total;
				sockares.Size -= total;

				if (sockares.socket.CleanedUp) {
					sockares.Complete (sent_so_far);
					return;
				}

				if (sockares.Size > 0) {
					IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, sent_so_far), sockares));
					return; // Have to finish writing everything. See bug #74475.
				}

				sockares.Total = sent_so_far;
			}

			sockares.Complete (sent_so_far);
		}

		[CLSCompliant (false)]
		public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (buffers == null)
				throw new ArgumentNullException ("buffers");

			if (!is_connected) {
				errorCode = SocketError.NotConnected;
				return null;
			}

			errorCode = SocketError.Success;

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendGeneric) {
				Buffers = buffers,
				SockFlags = socketFlags,
			};

			QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, sockares));

			return sockares;
		}

		static IOAsyncCallback BeginSendGenericCallback = new IOAsyncCallback (ares => {
			SocketAsyncResult sockares = (SocketAsyncResult) ares;
			int total = 0;

			try {
				total = sockares.socket.Send (sockares.Buffers, sockares.SockFlags);
			} catch (Exception e) {
				sockares.Complete (e);
				return;
			}

			sockares.Complete (total);
		});

		public int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
		{
			ThrowIfDisposedAndClosed ();

			SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndSend", "asyncResult");

			if (!sockares.IsCompleted)
				sockares.AsyncWaitHandle.WaitOne ();

			errorCode = sockares.ErrorCode;

			if (errorCode != SocketError.Success && errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress)
				is_connected = false;

			/* If no socket error occurred, call CheckIfThrowDelayedException in
			 * case there are other kinds of exceptions that should be thrown.*/
			if (errorCode == SocketError.Success)
				sockares.CheckIfThrowDelayedException ();

			return sockares.Total;
		}

		static unsafe int Send_internal (SafeSocketHandle safeHandle, WSABUF* bufarray, int count, SocketFlags flags, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return Send_array_icall (safeHandle.DangerousGetHandle (), bufarray, count, flags, out error, blocking);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}

		[MethodImplAttribute (MethodImplOptions.InternalCall)]
		extern static unsafe int Send_array_icall (IntPtr sock, WSABUF* bufarray, int count, SocketFlags flags, out int error, bool blocking);

		static unsafe int Send_internal (SafeSocketHandle safeHandle, byte* buffer, int count, SocketFlags flags, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return Send_icall (safeHandle.DangerousGetHandle (), buffer, count, flags, out error, blocking);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static unsafe int Send_icall (IntPtr sock, byte* buffer, int count, SocketFlags flags, out int error, bool blocking);

#endregion

#region SendTo

		public int SendTo (byte [] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			if (remoteEP == null)
				throw new ArgumentNullException("remoteEP");

			int error;
			int ret;
			unsafe {
				fixed (byte *pbuffer = buffer) {
					ret = SendTo_internal (m_Handle, &pbuffer[offset], size, socketFlags, remoteEP.Serialize (), out error, is_blocking);
				}
			}

			SocketError err = (SocketError) error;
			if (err != 0) {
				if (err != SocketError.WouldBlock && err != SocketError.InProgress)
					is_connected = false;
				throw new SocketException (error);
			}

			is_connected = true;
			is_bound = true;
			seed_endpoint = remoteEP;

			return ret;
		}

		int SendTo (Memory<byte> buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
		{
			ThrowIfDisposedAndClosed ();

			if (remoteEP == null)
				throw new ArgumentNullException("remoteEP");

			int error;
			int ret;
			unsafe {
				using (var pbuffer = buffer.Slice (offset, size).Pin ()) {
					ret = SendTo_internal (m_Handle, (byte*)pbuffer.Pointer, size, socketFlags, remoteEP.Serialize (), out error, is_blocking);
				}
			}

			SocketError err = (SocketError) error;
			if (err != 0) {
				if (err != SocketError.WouldBlock && err != SocketError.InProgress)
					is_connected = false;
				throw new SocketException (error);
			}

			is_connected = true;
			is_bound = true;
			seed_endpoint = remoteEP;

			return ret;
		}

		public bool SendToAsync (SocketAsyncEventArgs e)
		{
			// NO check is made whether e != null in MS.NET (NRE is thrown in such case)

			ThrowIfDisposedAndClosed ();

			if (e.BufferList != null)
				throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
			if (e.RemoteEndPoint == null)
				throw new ArgumentNullException ("remoteEP", "Value cannot be null.");

			InitSocketAsyncEventArgs (e, SendToAsyncCallback, e, SocketOperation.SendTo);

			e.socket_async_result.Buffer = e.Buffer;
			e.socket_async_result.Offset = e.Offset;
			e.socket_async_result.Size = e.Count;
			e.socket_async_result.SockFlags = e.SocketFlags;
			e.socket_async_result.EndPoint = e.RemoteEndPoint;

			QueueIOSelectorJob (WriteSem, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), e.socket_async_result));

			return true;
		}

		static AsyncCallback SendToAsyncCallback = new AsyncCallback (ares => {
			SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;

			if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
				throw new InvalidOperationException ("No operation in progress");

			try {
				e.SetBytesTransferred (e.CurrentSocket.EndSendTo (ares));
			} catch (SocketException ex) {
				e.SocketError = ex.SocketErrorCode;
			} catch (ObjectDisposedException) {
				e.SocketError = SocketError.OperationAborted;
			} finally {
				e.Complete_internal ();
			}
		});

		public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendTo) {
				Buffer = buffer,
				Offset = offset,
				Size = size,
				SockFlags = socketFlags,
				EndPoint = remoteEP,
			};

			QueueIOSelectorJob (WriteSem, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), sockares));

			return sockares;
		}

		static void BeginSendToCallback (SocketAsyncResult sockares, int sent_so_far)
		{
			int total = 0;
			try {
				total = sockares.socket.SendTo (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, sockares.EndPoint);

				if (sockares.error == 0) {
					sent_so_far += total;
					sockares.Offset += total;
					sockares.Size -= total;
				}

				if (sockares.Size > 0) {
					IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, sent_so_far), sockares));
					return; // Have to finish writing everything. See bug #74475.
				}

				sockares.Total = sent_so_far;
			} catch (Exception e) {
				sockares.Complete (e);
				return;
			}

			sockares.Complete ();
		}

		public int EndSendTo (IAsyncResult asyncResult)
		{
			ThrowIfDisposedAndClosed ();

			SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndSendTo", "result");

			if (!sockares.IsCompleted)
				sockares.AsyncWaitHandle.WaitOne();

			sockares.CheckIfThrowDelayedException();

			return sockares.Total;
		}

		static unsafe int SendTo_internal (SafeSocketHandle safeHandle, byte* buffer, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return SendTo_icall (safeHandle.DangerousGetHandle (), buffer, count, flags, sa, out error, blocking);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static unsafe int SendTo_icall (IntPtr sock, byte* buffer, int count, SocketFlags flags, SocketAddress sa, out int error, bool blocking);

#endregion

#region SendFile

		public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
		{
			ThrowIfDisposedAndClosed ();

			if (!is_connected)
				throw new NotSupportedException ();
			if (!is_blocking)
				throw new InvalidOperationException ();

			int error = 0;
			if (!SendFile_internal (m_Handle, fileName, preBuffer, postBuffer, flags, out error, is_blocking) || error != 0) {
				SocketException exc = new SocketException (error);
				if (exc.ErrorCode == 2 || exc.ErrorCode == 3)
					throw new FileNotFoundException ();
				throw exc;
			}
		}

		public IAsyncResult BeginSendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

			if (!is_connected)
				throw new NotSupportedException ();
			if (!File.Exists (fileName))
				throw new FileNotFoundException ();

			SendFileHandler handler = new SendFileHandler (SendFile);

			return new SendFileAsyncResult (handler, handler.BeginInvoke (fileName, preBuffer, postBuffer, flags, ar => callback (new SendFileAsyncResult (handler, ar)), state));
		}

		public void EndSendFile (IAsyncResult asyncResult)
		{
			ThrowIfDisposedAndClosed ();

			if (asyncResult == null)
				throw new ArgumentNullException ("asyncResult");

			SendFileAsyncResult ares = asyncResult as SendFileAsyncResult;
			if (ares == null)
				throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");

			ares.Delegate.EndInvoke (ares.Original);
		}

		static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking)
		{
			try {
				safeHandle.RegisterForBlockingSyscall ();
				return SendFile_icall (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags, out error, blocking);
			} finally {
				safeHandle.UnRegisterForBlockingSyscall ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static bool SendFile_icall (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags, out int error, bool blocking);

		delegate void SendFileHandler (string fileName, byte [] preBuffer, byte [] postBuffer, TransmitFileOptions flags);

		sealed class SendFileAsyncResult : IAsyncResult {
			IAsyncResult ares;
			SendFileHandler d;

			public SendFileAsyncResult (SendFileHandler d, IAsyncResult ares)
			{
				this.d = d;
				this.ares = ares;
			}

			public object AsyncState {
				get { return ares.AsyncState; }
			}

			public WaitHandle AsyncWaitHandle {
				get { return ares.AsyncWaitHandle; }
			}

			public bool CompletedSynchronously {
				get { return ares.CompletedSynchronously; }
			}

			public bool IsCompleted {
				get { return ares.IsCompleted; }
			}

			public SendFileHandler Delegate {
				get { return d; }
			}

			public IAsyncResult Original {
				get { return ares; }
			}
		}

#endregion

#region SendPackets

		[MonoTODO ("Not implemented")]
		public bool SendPacketsAsync (SocketAsyncEventArgs e)
		{
			// NO check is made whether e != null in MS.NET (NRE is thrown in such case)

			ThrowIfDisposedAndClosed ();

			throw new NotImplementedException ();
		}

#endregion

#region DuplicateAndClose

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		static extern bool Duplicate_icall (IntPtr handle, int targetProcessId, out IntPtr duplicateHandle, out MonoIOError error);

		[MonoLimitation ("We do not support passing sockets across processes, we merely allow this API to pass the socket across AppDomains")]
		public SocketInformation DuplicateAndClose (int targetProcessId)
		{
			var si = new SocketInformation ();
			si.Options =
				(is_listening      ? SocketInformationOptions.Listening : 0) |
				(is_connected      ? SocketInformationOptions.Connected : 0) |
				(is_blocking       ? 0 : SocketInformationOptions.NonBlocking) |
				(useOverlappedIO ? SocketInformationOptions.UseOnlyOverlappedIO : 0);

			IntPtr duplicateHandle;
			if (!Duplicate_icall (Handle, targetProcessId, out duplicateHandle, out MonoIOError error))
				throw MonoIO.GetException (error);

			si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)addressFamily, (int)socketType, (int)protocolType, is_bound ? 1 : 0, (long)duplicateHandle);
 			m_Handle = null;
 
 			return si;
		}

#endregion

#region GetSocketOption

		public void GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
		{
			ThrowIfDisposedAndClosed ();

			if (optionValue == null)
				throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");

			int error;
			GetSocketOption_arr_internal (m_Handle, optionLevel, optionName, ref optionValue, out error);

			if (error != 0)
				throw new SocketException (error);
		}

		public byte [] GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength)
		{
			ThrowIfDisposedAndClosed ();

			int error;
			byte[] byte_val = new byte [optionLength];
			GetSocketOption_arr_internal (m_Handle, optionLevel, optionName, ref byte_val, out error);

			if (error != 0)
				throw new SocketException (error);

			return byte_val;
		}

		public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
		{
			ThrowIfDisposedAndClosed ();

			int error;
			object obj_val;
			GetSocketOption_obj_internal (m_Handle, optionLevel, optionName, out obj_val, out error);

			if (error != 0)
				throw new SocketException (error);

			if (optionName == SocketOptionName.Linger)
				return (LingerOption) obj_val;
			else if (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)
				return (MulticastOption) obj_val;
			else if (obj_val is int)
				return (int) obj_val;
			else
				return obj_val;
		}

		static void GetSocketOption_arr_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				GetSocketOption_arr_icall (safeHandle.DangerousGetHandle (), level, name, ref byte_val, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void GetSocketOption_arr_icall (IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error);

		static void GetSocketOption_obj_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				GetSocketOption_obj_icall (safeHandle.DangerousGetHandle (), level, name, out obj_val, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void GetSocketOption_obj_icall (IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error);

#endregion

#region SetSocketOption

		public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
		{
			ThrowIfDisposedAndClosed ();

			// I'd throw an ArgumentNullException, but this is what MS does.
			if (optionValue == null)
				throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");

			int error;
			SetSocketOption_internal (m_Handle, optionLevel, optionName, null, optionValue, 0, out error);

			if (error != 0) {
				if (error == (int) SocketError.InvalidArgument)
					throw new ArgumentException ();
				throw new SocketException (error);
			}
		}

		public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
		{
			ThrowIfDisposedAndClosed ();

			// NOTE: if a null is passed, the byte[] overload is used instead...
			if (optionValue == null)
				throw new ArgumentNullException("optionValue");

			int error;

			if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger) {
				LingerOption linger = optionValue as LingerOption;
				if (linger == null)
					throw new ArgumentException ("A 'LingerOption' value must be specified.", "optionValue");
				SetSocketOption_internal (m_Handle, optionLevel, optionName, linger, null, 0, out error);
			} else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
				MulticastOption multicast = optionValue as MulticastOption;
				if (multicast == null)
					throw new ArgumentException ("A 'MulticastOption' value must be specified.", "optionValue");
				SetSocketOption_internal (m_Handle, optionLevel, optionName, multicast, null, 0, out error);
			} else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
				IPv6MulticastOption multicast = optionValue as IPv6MulticastOption;
				if (multicast == null)
					throw new ArgumentException ("A 'IPv6MulticastOption' value must be specified.", "optionValue");
				SetSocketOption_internal (m_Handle, optionLevel, optionName, multicast, null, 0, out error);
			} else {
				throw new ArgumentException ("Invalid value specified.", "optionValue");
			}

			if (error != 0) {
				if (error == (int) SocketError.InvalidArgument)
					throw new ArgumentException ();
				throw new SocketException (error);
			}
		}

		public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
		{
			int int_val = optionValue ? 1 : 0;

			SetSocketOption (optionLevel, optionName, int_val);
		}

		public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
		{
			ThrowIfDisposedAndClosed ();

			int error;
			SetSocketOption_internal (m_Handle, optionLevel, optionName, null, null, optionValue, out error);

			if (error != 0) {
				if (error == (int) SocketError.InvalidArgument)
					throw new ArgumentException ();
				throw new SocketException (error);
			}
		}

		static void SetSocketOption_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				SetSocketOption_icall (safeHandle.DangerousGetHandle (), level, name, obj_val, byte_val, int_val, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void SetSocketOption_icall (IntPtr socket, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error);

#endregion

#region IOControl

		public int IOControl (int ioControlCode, byte [] optionInValue, byte [] optionOutValue)
		{
			if (CleanedUp)
				throw new ObjectDisposedException (GetType ().ToString ());

			int error;
			int result = IOControl_internal (m_Handle, ioControlCode, optionInValue, optionOutValue, out error);

			if (error != 0)
				throw new SocketException (error);
			if (result == -1)
				throw new InvalidOperationException ("Must use Blocking property instead.");

			return result;
		}

		static int IOControl_internal (SafeSocketHandle safeHandle, int ioctl_code, byte [] input, byte [] output, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				return IOControl_icall (safeHandle.DangerousGetHandle (), ioctl_code, input, output, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		/* See Socket.IOControl, WSAIoctl documentation in MSDN. The common options between UNIX
		 * and Winsock are FIONREAD, FIONBIO and SIOCATMARK. Anything else will depend on the system
		 * except SIO_KEEPALIVE_VALS which is properly handled on both windows and linux. */
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static int IOControl_icall (IntPtr sock, int ioctl_code, byte [] input, byte [] output, out int error);

#endregion

#region Close

		public void Close ()
		{
			linger_timeout = 0;
			Dispose ();
		}

		public void Close (int timeout)
		{
			linger_timeout = timeout;
			Dispose ();
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		internal extern static void Close_icall (IntPtr socket, out int error);

#endregion

#region Shutdown

		public void Shutdown (SocketShutdown how)
		{
			const int enotconn = 10057;

			ThrowIfDisposedAndClosed ();

			if (!is_connected)
				throw new SocketException (enotconn); // Not connected

			int error;
			Shutdown_internal (m_Handle, how, out error);

			if (error == enotconn) {
				// POSIX requires this error to be returned from shutdown in some cases,
				//  even if the socket is actually connected.
				// We have already checked is_connected so it isn't meaningful or useful for
				//  us to throw if the OS says the socket was already closed when we tried to
				//  shut it down.
				// See https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=227259
				return;
			}

			if (error != 0)
				throw new SocketException (error);
		}

		static void Shutdown_internal (SafeSocketHandle safeHandle, SocketShutdown how, out int error)
		{
			bool release = false;
			try {
				safeHandle.DangerousAddRef (ref release);
				Shutdown_icall (safeHandle.DangerousGetHandle (), how, out error);
			} finally {
				if (release)
					safeHandle.DangerousRelease ();
			}
		}

		[MethodImplAttribute (MethodImplOptions.InternalCall)]
		internal extern static void Shutdown_icall (IntPtr socket, SocketShutdown how, out int error);

#endregion

#region Dispose

		protected virtual void Dispose (bool disposing)
		{
			if (CleanedUp)
				return;

			m_IntCleanedUp = 1;
			bool was_connected = is_connected;
			is_connected = false;

			if (m_Handle != null) {
				is_closed = true;
				IntPtr x = Handle;

				if (was_connected)
					Linger (x);

				m_Handle.Dispose ();
			}
		}

		void Linger (IntPtr handle)
		{
			if (!is_connected || linger_timeout <= 0)
				return;

			/* We don't want to receive any more data */
			int error;
			Shutdown_icall (handle, SocketShutdown.Receive, out error);

			if (error != 0)
				return;

			int seconds = linger_timeout / 1000;
			int ms = linger_timeout % 1000;
			if (ms > 0) {
				/* If the other end closes, this will return 'true' with 'Available' == 0 */
				Poll_icall (handle, SelectMode.SelectRead, ms * 1000, out error);
				if (error != 0)
					return;
			}

			if (seconds > 0) {
				LingerOption linger = new LingerOption (true, seconds);
				SetSocketOption_icall (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
				/* Not needed, we're closing upon return */
				//if (error != 0)
				//	return;
			}
		}

#endregion

		void ThrowIfDisposedAndClosed (Socket socket)
		{
			if (socket.CleanedUp && socket.is_closed)
				throw new ObjectDisposedException (socket.GetType ().ToString ());
		}

		void ThrowIfDisposedAndClosed ()
		{
			if (CleanedUp && is_closed)
				throw new ObjectDisposedException (GetType ().ToString ());
		}

		void ThrowIfBufferNull (byte[] buffer)
		{
			if (buffer == null)
				throw new ArgumentNullException ("buffer");
		}

		void ThrowIfBufferOutOfRange (byte[] buffer, int offset, int size)
		{
			if (offset < 0)
				throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
			if (offset > buffer.Length)
				throw new ArgumentOutOfRangeException ("offset", "offset must be <= buffer.Length");
			if (size < 0)
				throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
			if (size > buffer.Length - offset)
				throw new ArgumentOutOfRangeException ("size", "size must be <= buffer.Length - offset");
		}

		void ThrowIfUdp ()
		{
			if (protocolType == ProtocolType.Udp)
				throw new SocketException ((int)SocketError.ProtocolOption);
		}

		SocketAsyncResult ValidateEndIAsyncResult (IAsyncResult ares, string methodName, string argName)
		{
			if (ares == null)
				throw new ArgumentNullException (argName);

			SocketAsyncResult sockares = ares as SocketAsyncResult;
			if (sockares == null)
				throw new ArgumentException ("Invalid IAsyncResult", argName);
			if (Interlocked.CompareExchange (ref sockares.EndCalled, 1, 0) == 1)
				throw new InvalidOperationException (methodName + " can only be called once per asynchronous operation");

			return sockares;
		}

		void QueueIOSelectorJob (SemaphoreSlim sem, IntPtr handle, IOSelectorJob job)
		{
			var task = sem.WaitAsync();
			// fast path without Task<Action> allocation.
			if (task.IsCompleted) {
				if (CleanedUp) {
					job.MarkDisposed ();
					return;
				}
				IOSelector.Add (handle, job);
			}
			else
			{
				task.ContinueWith( t => {
					if (CleanedUp) {
						job.MarkDisposed ();
						return;
					}
					IOSelector.Add(handle, job);
				});
			}
		}

		void InitSocketAsyncEventArgs (SocketAsyncEventArgs e, AsyncCallback callback, object state, SocketOperation operation)
		{
			e.socket_async_result.Init (this, callback, state, operation);
			if (e.AcceptSocket != null) {
				e.socket_async_result.AcceptSocket = e.AcceptSocket;
			}
			e.SetCurrentSocket (this);
			e.SetLastOperation (SocketOperationToSocketAsyncOperation (operation));
			e.SocketError = SocketError.Success;
			e.SetBytesTransferred (0);
		}

		SocketAsyncOperation SocketOperationToSocketAsyncOperation (SocketOperation op)
		{
			switch (op) {
			case SocketOperation.Connect:
				return SocketAsyncOperation.Connect;
			case SocketOperation.Accept:
				return SocketAsyncOperation.Accept;
			case SocketOperation.Disconnect:
				return SocketAsyncOperation.Disconnect;
			case SocketOperation.Receive:
			case SocketOperation.ReceiveGeneric:
				return SocketAsyncOperation.Receive;
			case SocketOperation.ReceiveFrom:
				return SocketAsyncOperation.ReceiveFrom;
			case SocketOperation.Send:
			case SocketOperation.SendGeneric:
				return SocketAsyncOperation.Send;
			case SocketOperation.SendTo:
				return SocketAsyncOperation.SendTo;
			default:
				throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
			}
		}
		
		IPEndPoint RemapIPEndPoint (IPEndPoint input) {
			// If socket is DualMode ensure we automatically handle mapping IPv4 addresses to IPv6.
			if (IsDualMode && input.AddressFamily == AddressFamily.InterNetwork)
				return new IPEndPoint (input.Address.MapToIPv6 (), input.Port);
			
			return input;
		}
		
		[StructLayout (LayoutKind.Sequential)]
		struct WSABUF {
			public int len;
			public IntPtr buf;
		}

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		internal static extern void cancel_blocking_socket_operation (Thread thread);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		internal static extern bool SupportsPortReuse (ProtocolType proto);

		internal static int FamilyHint {
			get {
				// Returns one of
				//	MONO_HINT_UNSPECIFIED		= 0,
				//	MONO_HINT_IPV4				= 1,
				//	MONO_HINT_IPV6				= 2,

				int hint = 0;
				if (OSSupportsIPv4) {
					hint = 1;
				}

				if (OSSupportsIPv6) {
					hint = hint == 0 ? 2 : 0;
				}

				return hint;
			}
		}

		static bool IsProtocolSupported (NetworkInterfaceComponent networkInterface)
		{
#if MOBILE
			return true;
#else
			var nics = NetworkInterface.GetAllNetworkInterfaces ();
			foreach (var adapter in nics) {
				if (adapter.Supports (networkInterface))
					return true;
			}

			return false;
#endif
		}

		internal void ReplaceHandleIfNecessaryAfterFailedConnect ()
		{
			/*
			 * This is called from `DualSocketMultipleConnectAsync.GetNextAddress(out Socket)`
			 * and `SingleSocketMultipleConnectAsync.GetNextAddress(out Socket)` when using
			 * the CoreFX version of `MultipleConnectAsync`.
			 */
		}
	}
}