summaryrefslogtreecommitdiff
path: root/FreeRTOS-Plus/Source/FreeRTOS-Plus-TCP/FreeRTOS_Sockets.c
blob: bb68d2b38d14c51c190c875d2f0a442bc8868b9f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
/*
 * FreeRTOS+TCP V2.2.1
 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates.  All Rights Reserved.
 *
 * 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.
 *
 * http://aws.amazon.com/freertos
 * http://www.FreeRTOS.org
 */

/* Standard includes. */
#include <stdint.h>
#include <stdio.h>

/* FreeRTOS includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"

/* FreeRTOS+TCP includes. */
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"
#include "FreeRTOS_IP_Private.h"
#include "FreeRTOS_DNS.h"
#include "NetworkBufferManagement.h"

/* The ItemValue of the sockets xBoundSocketListItem member holds the socket's
port number. */
#define socketSET_SOCKET_PORT( pxSocket, usPort ) listSET_LIST_ITEM_VALUE( ( &( ( pxSocket )->xBoundSocketListItem ) ), ( usPort ) )
#define socketGET_SOCKET_PORT( pxSocket ) listGET_LIST_ITEM_VALUE( ( &( ( pxSocket )->xBoundSocketListItem ) ) )

/* Test if a socket it bound which means it is either included in
xBoundUDPSocketsList or xBoundTCPSocketsList */
#define socketSOCKET_IS_BOUND( pxSocket )	  ( listLIST_ITEM_CONTAINER( & ( pxSocket )->xBoundSocketListItem ) != NULL )

/* If FreeRTOS_sendto() is called on a socket that is not bound to a port
number then, depending on the FreeRTOSIPConfig.h settings, it might be that a
port number is automatically generated for the socket.  Automatically generated
port numbers will be between socketAUTO_PORT_ALLOCATION_START_NUMBER and
0xffff.

Per https://tools.ietf.org/html/rfc6056, "the dynamic ports consist of the range
49152-65535. However, ephemeral port selection algorithms should use the whole
range 1024-65535" excluding those already in use (inbound or outbound). */
#if !defined( socketAUTO_PORT_ALLOCATION_START_NUMBER )
	#define socketAUTO_PORT_ALLOCATION_START_NUMBER ( ( uint16_t ) 0x0400 )
#endif

#define socketAUTO_PORT_ALLOCATION_MAX_NUMBER   ( ( uint16_t ) 0xffff )

/* The number of octets that make up an IP address. */
#define socketMAX_IP_ADDRESS_OCTETS		4u

/* A block time of 0 simply means "don't block". */
#define socketDONT_BLOCK				( ( TickType_t ) 0 )

#if( ( ipconfigUSE_TCP == 1 ) && !defined( ipTCP_TIMER_PERIOD_MS ) )
	#define ipTCP_TIMER_PERIOD_MS	( 1000 )
#endif

/* The next private port number to use when binding a client socket is stored in
the usNextPortToUse[] array - which has either 1 or two indexes depending on
whether TCP is being supported. */
#if( ipconfigUSE_TCP == 1 )
	#define socketPROTOCOL_COUNT		2
#else
	#define socketPROTOCOL_COUNT		1
#endif

/* Indexes into the usNextPortToUse[] array for UDP and TCP sockets
respectively. */
#define socketNEXT_UDP_PORT_NUMBER_INDEX	0
#define socketNEXT_TCP_PORT_NUMBER_INDEX	1

/* Some helper macro's for defining the 20/80 % limits of uxLittleSpace / uxEnoughSpace. */
#define sock20_PERCENT						20
#define sock80_PERCENT						80
#define sock100_PERCENT						100


/*-----------------------------------------------------------*/

/*
 * Allocate the next port number from the private allocation range.
 * TCP and UDP each have their own series of port numbers
 * ulProtocol is either ipPROTOCOL_UDP or ipPROTOCOL_TCP
 */
static uint16_t prvGetPrivatePortNumber( BaseType_t xProtocol );

/*
 * Return the list item from within pxList that has an item value of
 * xWantedItemValue.  If there is no such list item return NULL.
 */
static const ListItem_t * pxListFindListItemWithValue( const List_t *pxList, TickType_t xWantedItemValue );

/*
 * Return pdTRUE only if pxSocket is valid and bound, as far as can be
 * determined.
 */
static BaseType_t prvValidSocket( FreeRTOS_Socket_t *pxSocket, BaseType_t xProtocol, BaseType_t xIsBound );

/*
 * Before creating a socket, check the validity of the parameters used
 * and find the size of the socket space, which is different for UDP and TCP
 */
static BaseType_t prvDetermineSocketSize( BaseType_t xDomain, BaseType_t xType, BaseType_t xProtocol, size_t *pxSocketSize );

#if( ipconfigUSE_TCP == 1 )
	/*
	 * Create a txStream or a rxStream, depending on the parameter 'xIsInputStream'
	 */
	static StreamBuffer_t *prvTCPCreateStream (FreeRTOS_Socket_t *pxSocket, BaseType_t xIsInputStream );
#endif /* ipconfigUSE_TCP == 1 */

#if( ipconfigUSE_TCP == 1 )
	/*
	 * Called from FreeRTOS_send(): some checks which will be done before
	 * sending a TCP packed.
	 */
	static int32_t prvTCPSendCheck( FreeRTOS_Socket_t *pxSocket, size_t xDataLength );
#endif /* ipconfigUSE_TCP */

#if( ipconfigUSE_TCP == 1 )
	/*
	 * When a child socket gets closed, make sure to update the child-count of the parent
	 */
	static void prvTCPSetSocketCount( FreeRTOS_Socket_t *pxSocketToDelete );
#endif  /* ipconfigUSE_TCP == 1 */

#if( ipconfigUSE_TCP == 1 )
	/*
	 * Called from FreeRTOS_connect(): make some checks and if allowed, send a
	 * message to the IP-task to start connecting to a remote socket
	 */
	static BaseType_t prvTCPConnectStart( FreeRTOS_Socket_t *pxSocket, struct freertos_sockaddr *pxAddress );
#endif /* ipconfigUSE_TCP */

#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )

	/* Executed by the IP-task, it will check all sockets belonging to a set */
	static FreeRTOS_Socket_t *prvFindSelectedSocket( SocketSelect_t *pxSocketSet );

#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/

/* The list that contains mappings between sockets and port numbers.  Accesses
to this list must be protected by critical sections of one kind or another. */
List_t xBoundUDPSocketsList;

#if ipconfigUSE_TCP == 1
	List_t xBoundTCPSocketsList;
#endif /* ipconfigUSE_TCP == 1 */

/*-----------------------------------------------------------*/

static BaseType_t prvValidSocket( FreeRTOS_Socket_t *pxSocket, BaseType_t xProtocol, BaseType_t xIsBound )
{
BaseType_t xReturn = pdTRUE;

	if( ( pxSocket == NULL ) || ( pxSocket == FREERTOS_INVALID_SOCKET ) )
	{
		xReturn = pdFALSE;
	}
	else if( ( xIsBound != pdFALSE ) && ( socketSOCKET_IS_BOUND( pxSocket ) == pdFALSE ) )
	{
		/* The caller expects the socket to be bound, but it isn't. */
		xReturn = pdFALSE;
	}
	else if( pxSocket->ucProtocol != ( uint8_t ) xProtocol )
	{
		/* Socket has a wrong type (UDP != TCP). */
		xReturn = pdFALSE;
	}

	return xReturn;
}
/*-----------------------------------------------------------*/

BaseType_t vNetworkSocketsInit( void )
{
	vListInitialise( &xBoundUDPSocketsList );

	#if( ipconfigUSE_TCP == 1 )
	{
		vListInitialise( &xBoundTCPSocketsList );
	}
	#endif  /* ipconfigUSE_TCP == 1 */

	return pdTRUE;
}
/*-----------------------------------------------------------*/

static BaseType_t prvDetermineSocketSize( BaseType_t xDomain, BaseType_t xType, BaseType_t xProtocol, size_t *pxSocketSize )
{
BaseType_t xReturn = pdPASS;
FreeRTOS_Socket_t *pxSocket;

	/* Asserts must not appear before it has been determined that the network
	task is ready - otherwise the asserts will fail. */
	if( xIPIsNetworkTaskReady() == pdFALSE )
	{
		xReturn = pdFAIL;
	}
	else
	{
		/* Only Ethernet is currently supported. */
		configASSERT( xDomain == FREERTOS_AF_INET );

		/* Check if the UDP socket-list has been initialised. */
		configASSERT( listLIST_IS_INITIALISED( &xBoundUDPSocketsList ) );
		#if( ipconfigUSE_TCP == 1 )
		{
			/* Check if the TCP socket-list has been initialised. */
			configASSERT( listLIST_IS_INITIALISED( &xBoundTCPSocketsList ) );
		}
		#endif  /* ipconfigUSE_TCP == 1 */

		if( xProtocol == FREERTOS_IPPROTO_UDP )
		{
			if( xType != FREERTOS_SOCK_DGRAM )
			{
				xReturn = pdFAIL;
				configASSERT( xReturn );
			}
			/* In case a UDP socket is created, do not allocate space for TCP data. */
			*pxSocketSize = ( sizeof( *pxSocket ) - sizeof( pxSocket->u ) ) + sizeof( pxSocket->u.xUDP );
		}
#if( ipconfigUSE_TCP == 1 )
		else if( xProtocol == FREERTOS_IPPROTO_TCP )
		{
			if( xType != FREERTOS_SOCK_STREAM )
			{
				xReturn = pdFAIL;
				configASSERT( xReturn );
			}

			*pxSocketSize = ( sizeof( *pxSocket ) - sizeof( pxSocket->u ) ) + sizeof( pxSocket->u.xTCP );
		}
#endif  /* ipconfigUSE_TCP == 1 */
		else
		{
			xReturn = pdFAIL;
			configASSERT( xReturn );
		}
	}
	/* In case configASSERT() is not used */
	( void )xDomain;
	return xReturn;
}
/*-----------------------------------------------------------*/

/* FreeRTOS_socket() allocates and initiates a socket */
Socket_t FreeRTOS_socket( BaseType_t xDomain, BaseType_t xType, BaseType_t xProtocol )
{
FreeRTOS_Socket_t *pxSocket;
size_t uxSocketSize;
EventGroupHandle_t xEventGroup;
Socket_t xReturn;

	if( prvDetermineSocketSize( xDomain, xType, xProtocol, &uxSocketSize ) == pdFAIL )
	{
		xReturn = FREERTOS_INVALID_SOCKET;
	}
	else
	{
		/* Allocate the structure that will hold the socket information.  The
		size depends on the type of socket: UDP sockets need less space.  A
		define 'pvPortMallocSocket' will used to allocate the necessary space.
		By default it points to the FreeRTOS function 'pvPortMalloc()'. */
		pxSocket = ( FreeRTOS_Socket_t * ) pvPortMallocSocket( uxSocketSize );

		if( pxSocket == NULL )
		{
			pxSocket = ( FreeRTOS_Socket_t * ) FREERTOS_INVALID_SOCKET;
			iptraceFAILED_TO_CREATE_SOCKET();
		}
		else if( ( xEventGroup = xEventGroupCreate() ) == NULL )
		{
			vPortFreeSocket( pxSocket );
			pxSocket = ( FreeRTOS_Socket_t * ) FREERTOS_INVALID_SOCKET;
			iptraceFAILED_TO_CREATE_EVENT_GROUP();
		}
		else
		{
			/* Clear the entire space to avoid nulling individual entries */
			memset( pxSocket, '\0', uxSocketSize );

			pxSocket->xEventGroup = xEventGroup;

			/* Initialise the socket's members.  The semaphore will be created
			if the socket is bound to an address, for now the pointer to the
			semaphore is just set to NULL to show it has not been created. */
			if( xProtocol == FREERTOS_IPPROTO_UDP )
			{
				vListInitialise( &( pxSocket->u.xUDP.xWaitingPacketsList ) );

				#if( ipconfigUDP_MAX_RX_PACKETS > 0 )
				{
					pxSocket->u.xUDP.uxMaxPackets = ( UBaseType_t ) ipconfigUDP_MAX_RX_PACKETS;
				}
				#endif /* ipconfigUDP_MAX_RX_PACKETS > 0 */
			}

			vListInitialiseItem( &( pxSocket->xBoundSocketListItem ) );
			listSET_LIST_ITEM_OWNER( &( pxSocket->xBoundSocketListItem ), ( void * ) pxSocket );

			pxSocket->xReceiveBlockTime = ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME;
			pxSocket->xSendBlockTime	= ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME;
			pxSocket->ucSocketOptions   = ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT;
			pxSocket->ucProtocol		= ( uint8_t ) xProtocol; /* protocol: UDP or TCP */

			#if( ipconfigUSE_TCP == 1 )
			{
				if( xProtocol == FREERTOS_IPPROTO_TCP )
				{
					/* StreamSize is expressed in number of bytes */
					/* Round up buffer sizes to nearest multiple of MSS */
					pxSocket->u.xTCP.usInitMSS	= pxSocket->u.xTCP.usCurMSS = ipconfigTCP_MSS;
					pxSocket->u.xTCP.uxRxStreamSize = ( size_t ) ipconfigTCP_RX_BUFFER_LENGTH;
					pxSocket->u.xTCP.uxTxStreamSize = ( size_t ) FreeRTOS_round_up( ipconfigTCP_TX_BUFFER_LENGTH, ipconfigTCP_MSS );
					/* Use half of the buffer size of the TCP windows */
					#if ( ipconfigUSE_TCP_WIN == 1 )
					{
						pxSocket->u.xTCP.uxRxWinSize  = FreeRTOS_max_uint32( 1UL, ( uint32_t ) ( pxSocket->u.xTCP.uxRxStreamSize / 2 ) / ipconfigTCP_MSS );
						pxSocket->u.xTCP.uxTxWinSize  = FreeRTOS_max_uint32( 1UL, ( uint32_t ) ( pxSocket->u.xTCP.uxTxStreamSize / 2 ) / ipconfigTCP_MSS );
					}
					#else
					{
						pxSocket->u.xTCP.uxRxWinSize  = 1u;
						pxSocket->u.xTCP.uxTxWinSize  = 1u;
					}
					#endif
					/* The above values are just defaults, and can be overridden by
					calling FreeRTOS_setsockopt().  No buffers will be allocated until a
					socket is connected and data is exchanged. */
				}
			}
			#endif  /* ipconfigUSE_TCP == 1 */
		}

		xReturn = ( Socket_t ) pxSocket;
	}

	/* Remove compiler warnings in the case the configASSERT() is not defined. */
	( void ) xDomain;

	return xReturn;
}
/*-----------------------------------------------------------*/

#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )

	SocketSet_t FreeRTOS_CreateSocketSet( void )
	{
	SocketSelect_t *pxSocketSet;

		pxSocketSet = ( SocketSelect_t * ) pvPortMalloc( sizeof( *pxSocketSet ) );

		if( pxSocketSet != NULL )
		{
			memset( pxSocketSet, '\0', sizeof( *pxSocketSet ) );
			pxSocketSet->xSelectGroup = xEventGroupCreate();

			if( pxSocketSet->xSelectGroup == NULL )
			{
				vPortFree( ( void* ) pxSocketSet );
				pxSocketSet = NULL;
			}
		}

		return ( SocketSet_t ) pxSocketSet;
	}

#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/

#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )

	void FreeRTOS_DeleteSocketSet( SocketSet_t xSocketSet )
	{
		SocketSelect_t *pxSocketSet = ( SocketSelect_t*) xSocketSet;

		vEventGroupDelete( pxSocketSet->xSelectGroup );
		vPortFree( ( void* ) pxSocketSet );
	}

#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/

#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )

	/* Add a socket to a set */
	void FreeRTOS_FD_SET( Socket_t xSocket, SocketSet_t xSocketSet, EventBits_t xSelectBits )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	SocketSelect_t *pxSocketSet = ( SocketSelect_t * ) xSocketSet;

		configASSERT( pxSocket != NULL );
		configASSERT( xSocketSet != NULL );

		/* Make sure we're not adding bits which are reserved for internal use,
		such as eSELECT_CALL_IP */
		pxSocket->xSelectBits |= ( xSelectBits & eSELECT_ALL );

		if( ( pxSocket->xSelectBits & eSELECT_ALL ) != 0 )
		{
			/* Adding a socket to a socket set. */
			pxSocket->pxSocketSet = ( SocketSelect_t * ) xSocketSet;

			/* Now have the IP-task call vSocketSelect() to see if the set contains
			any sockets which are 'ready' and set the proper bits.
			By setting 'bApiCalled = false', vSocketSelect() knows that it was
			not called from a user API */
			pxSocketSet->bApiCalled = pdFALSE;
			prvFindSelectedSocket( pxSocketSet );
		}
	}

#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/

#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
	/* Clear select bits for a socket
	If the mask becomes 0, remove the socket from the set */
	void FreeRTOS_FD_CLR( Socket_t xSocket, SocketSet_t xSocketSet, EventBits_t xSelectBits )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;

		configASSERT( pxSocket != NULL );
		configASSERT( xSocketSet != NULL );

		pxSocket->xSelectBits &= ~( xSelectBits & eSELECT_ALL );
		if( ( pxSocket->xSelectBits & eSELECT_ALL ) != 0 )
		{
			pxSocket->pxSocketSet = ( SocketSelect_t *)xSocketSet;
		}
		else
		{
			/* disconnect it from the socket set */
			pxSocket->pxSocketSet = ( SocketSelect_t *)NULL;
		}
	}

#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/


#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )

	/* Test if a socket belongs to a socket-set */
	EventBits_t FreeRTOS_FD_ISSET( Socket_t xSocket, SocketSet_t xSocketSet )
	{
	EventBits_t xReturn;
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;

		configASSERT( pxSocket != NULL );
		configASSERT( xSocketSet != NULL );

		if( xSocketSet == ( SocketSet_t ) pxSocket->pxSocketSet )
		{
			/* Make sure we're not adding bits which are reserved for internal
			use. */
			xReturn = pxSocket->xSocketBits & eSELECT_ALL;
		}
		else
		{
			xReturn = 0;
		}

		return xReturn;
	}

#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/

#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )

	/* The select() statement: wait for an event to occur on any of the sockets
	included in a socket set */
	BaseType_t FreeRTOS_select( SocketSet_t xSocketSet, TickType_t xBlockTimeTicks )
	{
	TimeOut_t xTimeOut;
	TickType_t xRemainingTime;
	SocketSelect_t *pxSocketSet = ( SocketSelect_t*) xSocketSet;
	BaseType_t xResult;

		configASSERT( xSocketSet != NULL );

		/* Only in the first round, check for non-blocking */
		xRemainingTime = xBlockTimeTicks;

		/* Fetch the current time */
		vTaskSetTimeOutState( &xTimeOut );

		for( ;; )
		{
			/* Find a socket which might have triggered the bit
			This function might return immediately or block for a limited time */
			xResult = ( BaseType_t ) xEventGroupWaitBits( pxSocketSet->xSelectGroup, eSELECT_ALL, pdFALSE, pdFALSE, xRemainingTime );

			#if( ipconfigSUPPORT_SIGNALS != 0 )
			{
				if( ( xResult & eSELECT_INTR ) != 0u )
				{
					xEventGroupClearBits( pxSocketSet->xSelectGroup, eSELECT_INTR );
					FreeRTOS_debug_printf( ( "FreeRTOS_select: interrupted\n" ) );
					break;
				}
			}
			#endif /* ipconfigSUPPORT_SIGNALS */

			/* Have the IP-task find the socket which had an event */
			pxSocketSet->bApiCalled = pdTRUE;
			prvFindSelectedSocket( pxSocketSet );

			xResult = ( BaseType_t ) xEventGroupGetBits( pxSocketSet->xSelectGroup );

			if( xResult != 0 )
			{
				break;
			}

			/* Has the timeout been reached? */
			if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE )
			{
				break;
			}
		}

		return xResult;
	}

#endif /* ipconfigSUPPORT_SELECT_FUNCTION */
/*-----------------------------------------------------------*/

#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )

	/* Send a message to the IP-task to have it check all sockets belonging to
	'pxSocketSet' */
	static FreeRTOS_Socket_t *prvFindSelectedSocket( SocketSelect_t *pxSocketSet )
	{
	IPStackEvent_t xSelectEvent;
	FreeRTOS_Socket_t *xReturn;

		xSelectEvent.eEventType = eSocketSelectEvent;
		xSelectEvent.pvData = ( void * ) pxSocketSet;

		/* while the IP-task works on the request, the API will block on
		'eSELECT_CALL_IP'.  So clear it first. */
		xEventGroupClearBits( pxSocketSet->xSelectGroup, eSELECT_CALL_IP );

		/* Now send the socket select event */
		if( xSendEventStructToIPTask( &xSelectEvent, ( TickType_t ) portMAX_DELAY ) == pdFAIL )
		{
			/* Oops, we failed to wake-up the IP task. No use to wait for it. */
			FreeRTOS_debug_printf( ( "prvFindSelectedSocket: failed\n" ) );
			xReturn = NULL;
		}
		else
		{
			/* As soon as the IP-task is ready, it will set 'eSELECT_CALL_IP' to
			wakeup the calling API */
			xEventGroupWaitBits( pxSocketSet->xSelectGroup, eSELECT_CALL_IP, pdTRUE, pdFALSE, portMAX_DELAY );

			/* Return 'pxSocket' which is set by the IP-task */
			xReturn = pxSocketSet->pxSocket;
		}

		return xReturn;
	}

#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/

/*
 * FreeRTOS_recvfrom: receive data from a bound socket
 * In this library, the function can only be used with connectionsless sockets
 * (UDP)
 */
int32_t FreeRTOS_recvfrom( Socket_t xSocket, void *pvBuffer, size_t xBufferLength, BaseType_t xFlags, struct freertos_sockaddr *pxSourceAddress, socklen_t *pxSourceAddressLength )
{
BaseType_t lPacketCount = 0;
NetworkBufferDescriptor_t *pxNetworkBuffer;
FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
TickType_t xRemainingTime = ( TickType_t ) 0; /* Obsolete assignment, but some compilers output a warning if its not done. */
BaseType_t xTimed = pdFALSE;
TimeOut_t xTimeOut;
int32_t lReturn;
EventBits_t xEventBits = ( EventBits_t ) 0;

	if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_UDP, pdTRUE ) == pdFALSE )
	{
		return -pdFREERTOS_ERRNO_EINVAL;
	}

	lPacketCount = ( BaseType_t ) listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) );

	/* The function prototype is designed to maintain the expected Berkeley
	sockets standard, but this implementation does not use all the parameters. */
	( void ) pxSourceAddressLength;

	while( lPacketCount == 0 )
	{
		if( xTimed == pdFALSE )
		{
			/* Check to see if the socket is non blocking on the first
			iteration.  */
			xRemainingTime = pxSocket->xReceiveBlockTime;

			if( xRemainingTime == ( TickType_t ) 0 )
			{
				#if( ipconfigSUPPORT_SIGNALS != 0 )
				{
					/* Just check for the interrupt flag. */
					xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup, eSOCKET_INTR,
						pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, socketDONT_BLOCK );
				}
				#endif /* ipconfigSUPPORT_SIGNALS */
				break;
			}

			if( ( xFlags & FREERTOS_MSG_DONTWAIT ) != 0 )
			{
				break;
			}

			/* To ensure this part only executes once. */
			xTimed = pdTRUE;

			/* Fetch the current time. */
			vTaskSetTimeOutState( &xTimeOut );
		}

		/* Wait for arrival of data.  While waiting, the IP-task may set the
		'eSOCKET_RECEIVE' bit in 'xEventGroup', if it receives data for this
		socket, thus unblocking this API call. */
		xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup, eSOCKET_RECEIVE | eSOCKET_INTR,
			pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime );

		#if( ipconfigSUPPORT_SIGNALS != 0 )
		{
			if( ( xEventBits & eSOCKET_INTR ) != 0 )
			{
				if( ( xEventBits & eSOCKET_RECEIVE ) != 0 )
				{
					/* Shouldn't have cleared the eSOCKET_RECEIVE flag. */
					xEventGroupSetBits( pxSocket->xEventGroup, eSOCKET_RECEIVE );
				}
				break;
			}
		}
		#else
		{
			( void ) xEventBits;
		}
		#endif /* ipconfigSUPPORT_SIGNALS */

		lPacketCount = ( BaseType_t ) listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) );

		if( lPacketCount != 0 )
		{
			break;
		}

		/* Has the timeout been reached ? */
		if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) )
		{
			break;
		}
	} /* while( lPacketCount == 0 ) */

	if( lPacketCount != 0 )
	{
		taskENTER_CRITICAL();
		{
			/* The owner of the list item is the network buffer. */
			pxNetworkBuffer = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &( pxSocket->u.xUDP.xWaitingPacketsList ) );

			if( ( xFlags & FREERTOS_MSG_PEEK ) == 0 )
			{
				/* Remove the network buffer from the list of buffers waiting to
				be processed by the socket. */
				uxListRemove( &( pxNetworkBuffer->xBufferListItem ) );
			}
		}
		taskEXIT_CRITICAL();

		/* The returned value is the length of the payload data, which is
		calculated at the total packet size minus the headers.
		The validity of `xDataLength` prvProcessIPPacket has been confirmed
		in 'prvProcessIPPacket()'. */
		lReturn = ( int32_t ) ( pxNetworkBuffer->xDataLength - sizeof( UDPPacket_t ) );

		if( pxSourceAddress != NULL )
		{
			pxSourceAddress->sin_port = pxNetworkBuffer->usPort;
			pxSourceAddress->sin_addr = pxNetworkBuffer->ulIPAddress;
		}

		if( ( xFlags & FREERTOS_ZERO_COPY ) == 0 )
		{
			/* The zero copy flag is not set.  Truncate the length if it won't
			fit in the provided buffer. */
			if( lReturn > ( int32_t ) xBufferLength )
			{
				iptraceRECVFROM_DISCARDING_BYTES( ( xBufferLength - lReturn ) );
				lReturn = ( int32_t )xBufferLength;
			}

			/* Copy the received data into the provided buffer, then release the
			network buffer. */
			memcpy( pvBuffer, ( void * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] ), ( size_t )lReturn );

			if( ( xFlags & FREERTOS_MSG_PEEK ) == 0 )
			{
				vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
			}
		}
		else
		{
			/* The zero copy flag was set.  pvBuffer is not a buffer into which
			the received data can be copied, but a pointer that must be set to
			point to the buffer in which the received data has already been
			placed. */
			*( ( void** ) pvBuffer ) = ( void * ) ( &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] ) );
		}

	}
#if( ipconfigSUPPORT_SIGNALS != 0 )
	else if( ( xEventBits & eSOCKET_INTR ) != 0 )
	{
		lReturn = -pdFREERTOS_ERRNO_EINTR;
		iptraceRECVFROM_INTERRUPTED();
	}
#endif /* ipconfigSUPPORT_SIGNALS */
	else
	{
		lReturn = -pdFREERTOS_ERRNO_EWOULDBLOCK;
		iptraceRECVFROM_TIMEOUT();
	}

	return lReturn;
}
/*-----------------------------------------------------------*/

int32_t FreeRTOS_sendto( Socket_t xSocket, const void *pvBuffer, size_t xTotalDataLength, BaseType_t xFlags, const struct freertos_sockaddr *pxDestinationAddress, socklen_t xDestinationAddressLength )
{
NetworkBufferDescriptor_t *pxNetworkBuffer;
IPStackEvent_t xStackTxEvent = { eStackTxEvent, NULL };
TimeOut_t xTimeOut;
TickType_t xTicksToWait;
int32_t lReturn = 0;
FreeRTOS_Socket_t *pxSocket;

	pxSocket = ( FreeRTOS_Socket_t * ) xSocket;

	/* The function prototype is designed to maintain the expected Berkeley
	sockets standard, but this implementation does not use all the
	parameters. */
	( void ) xDestinationAddressLength;
	configASSERT( pvBuffer );

	if( xTotalDataLength <= ( size_t ) ipMAX_UDP_PAYLOAD_LENGTH )
	{
		/* If the socket is not already bound to an address, bind it now.
		Passing NULL as the address parameter tells FreeRTOS_bind() to select
		the address to bind to. */
		if( ( socketSOCKET_IS_BOUND( pxSocket ) != pdFALSE ) ||
			( FreeRTOS_bind( xSocket, NULL, 0u ) == 0 ) )
		{
			xTicksToWait = pxSocket->xSendBlockTime;

			#if( ipconfigUSE_CALLBACKS != 0 )
			{
				if( xIsCallingFromIPTask() != pdFALSE )
				{
					/* If this send function is called from within a call-back
					handler it may not block, otherwise chances would be big to
					get a deadlock: the IP-task waiting for itself. */
					xTicksToWait = ( TickType_t )0;
				}
			}
			#endif /* ipconfigUSE_CALLBACKS */

			if( ( xFlags & FREERTOS_MSG_DONTWAIT ) != 0 )
			{
				xTicksToWait = ( TickType_t ) 0;
			}

			if( ( xFlags & FREERTOS_ZERO_COPY ) == 0 )
			{
				/* Zero copy is not set, so obtain a network buffer into
				which the payload will be copied. */
				vTaskSetTimeOutState( &xTimeOut );

				/* Block until a buffer becomes available, or until a
				timeout has been reached */
				pxNetworkBuffer = pxGetNetworkBufferWithDescriptor( xTotalDataLength + sizeof( UDPPacket_t ), xTicksToWait );

				if( pxNetworkBuffer != NULL )
				{
					memcpy( ( void * ) &( pxNetworkBuffer->pucEthernetBuffer[ ipUDP_PAYLOAD_OFFSET_IPv4 ] ), ( void * ) pvBuffer, xTotalDataLength );

					if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdTRUE )
					{
						/* The entire block time has been used up. */
						xTicksToWait = ( TickType_t ) 0;
					}
				}
			}
			else
			{
				/* When zero copy is used, pvBuffer is a pointer to the
				payload of a buffer that has already been obtained from the
				stack.  Obtain the network buffer pointer from the buffer. */
				pxNetworkBuffer = pxUDPPayloadBuffer_to_NetworkBuffer( (void*)pvBuffer );
			}

			if( pxNetworkBuffer != NULL )
			{
				/* xDataLength is the size of the total packet, including the Ethernet header. */
				pxNetworkBuffer->xDataLength = xTotalDataLength + sizeof( UDPPacket_t );
				pxNetworkBuffer->usPort = pxDestinationAddress->sin_port;
				pxNetworkBuffer->usBoundPort = ( uint16_t ) socketGET_SOCKET_PORT( pxSocket );
				pxNetworkBuffer->ulIPAddress = pxDestinationAddress->sin_addr;

				/* The socket options are passed to the IP layer in the
				space that will eventually get used by the Ethernet header. */
				pxNetworkBuffer->pucEthernetBuffer[ ipSOCKET_OPTIONS_OFFSET ] = pxSocket->ucSocketOptions;

				/* Tell the networking task that the packet needs sending. */
				xStackTxEvent.pvData = pxNetworkBuffer;

				/* Ask the IP-task to send this packet */
				if( xSendEventStructToIPTask( &xStackTxEvent, xTicksToWait ) == pdPASS )
				{
					/* The packet was successfully sent to the IP task. */
					lReturn = ( int32_t ) xTotalDataLength;
					#if( ipconfigUSE_CALLBACKS == 1 )
					{
						if( ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xUDP.pxHandleSent ) )
						{
							pxSocket->u.xUDP.pxHandleSent( ( Socket_t )pxSocket, xTotalDataLength );
						}
					}
					#endif /* ipconfigUSE_CALLBACKS */
				}
				else
				{
					/* If the buffer was allocated in this function, release
					it. */
					if( ( xFlags & FREERTOS_ZERO_COPY ) == 0 )
					{
						vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
					}
					iptraceSTACK_TX_EVENT_LOST( ipSTACK_TX_EVENT );
				}
			}
			else
			{
				/* If errno was available, errno would be set to
				FREERTOS_ENOPKTS.  As it is, the function must return the
				number of transmitted bytes, so the calling function knows
				how	much data was actually sent. */
				iptraceNO_BUFFER_FOR_SENDTO();
			}
		}
		else
		{
			iptraceSENDTO_SOCKET_NOT_BOUND();
		}
	}
	else
	{
		/* The data is longer than the available buffer space. */
		iptraceSENDTO_DATA_TOO_LONG();
	}

	return lReturn;
} /* Tested */
/*-----------------------------------------------------------*/

/*
 * FreeRTOS_bind() : binds a sockt to a local port number.  If port 0 is
 * provided, a system provided port number will be assigned.  This function can
 * be used for both UDP and TCP sockets.  The actual binding will be performed
 * by the IP-task to avoid mutual access to the bound-socket-lists
 * (xBoundUDPSocketsList or xBoundTCPSocketsList).
 */
BaseType_t FreeRTOS_bind( Socket_t xSocket, struct freertos_sockaddr * pxAddress, socklen_t xAddressLength )
{
IPStackEvent_t xBindEvent;
FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
BaseType_t xReturn = 0;

	( void ) xAddressLength;

	if( ( pxSocket == NULL ) || ( pxSocket == FREERTOS_INVALID_SOCKET ) )
	{
		xReturn = -pdFREERTOS_ERRNO_EINVAL;
	}
	/* Once a socket is bound to a port, it can not be bound to a different
	port number */
	else if( socketSOCKET_IS_BOUND( pxSocket) != pdFALSE )
	{
		/* The socket is already bound. */
		FreeRTOS_debug_printf( ( "vSocketBind: Socket already bound to %d\n", pxSocket->usLocalPort ) );
		xReturn = -pdFREERTOS_ERRNO_EINVAL;
	}
	else
	{
		/* Prepare a messages to the IP-task in order to perform the binding.
		The desired port number will be passed in usLocalPort. */
		xBindEvent.eEventType = eSocketBindEvent;
		xBindEvent.pvData = ( void * ) xSocket;
		if( pxAddress != NULL )
		{
			pxSocket->usLocalPort = FreeRTOS_ntohs( pxAddress->sin_port );
		}
		else
		{
			/* Caller wants to bind to a random port number. */
			pxSocket->usLocalPort = 0u;
		}

		/* portMAX_DELAY is used as a the time-out parameter, as binding *must*
		succeed before the socket can be used.  _RB_ The use of an infinite
		block time needs be changed as it could result in the task hanging. */
		if( xSendEventStructToIPTask( &xBindEvent, ( TickType_t ) portMAX_DELAY ) == pdFAIL )
		{
			/* Failed to wake-up the IP-task, no use to wait for it */
			FreeRTOS_debug_printf( ( "FreeRTOS_bind: send event failed\n" ) );
			xReturn = -pdFREERTOS_ERRNO_ECANCELED;
		}
		else
		{
			/* The IP-task will set the 'eSOCKET_BOUND' bit when it has done its
			job. */
			xEventGroupWaitBits( pxSocket->xEventGroup, eSOCKET_BOUND, pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, portMAX_DELAY );
			if( socketSOCKET_IS_BOUND( pxSocket ) == pdFALSE )
			{
				xReturn = -pdFREERTOS_ERRNO_EINVAL;
			}
		}
	}

	return xReturn;
}

/*
 * vSocketBind(): internal version of bind() that should not be called directly.
 * 'xInternal' is used for TCP sockets only: it allows to have several
 * (connected) child sockets bound to the same server port.
 */
BaseType_t vSocketBind( FreeRTOS_Socket_t *pxSocket, struct freertos_sockaddr * pxAddress, size_t uxAddressLength, BaseType_t xInternal )
{
BaseType_t xReturn = 0; /* In Berkeley sockets, 0 means pass for bind(). */
List_t *pxSocketList;
#if( ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1 )
	struct freertos_sockaddr xAddress;
#endif /* ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND */

#if( ipconfigUSE_TCP == 1 )
	if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP )
	{
		pxSocketList = &xBoundTCPSocketsList;
	}
	else
#endif  /* ipconfigUSE_TCP == 1 */
	{
		pxSocketList = &xBoundUDPSocketsList;
	}

	/* The function prototype is designed to maintain the expected Berkeley
	sockets standard, but this implementation does not use all the parameters. */
	( void ) uxAddressLength;

	configASSERT( pxSocket );
	configASSERT( pxSocket != FREERTOS_INVALID_SOCKET );

	#if( ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1 )
	{
		/* pxAddress will be NULL if sendto() was called on a socket without the
		socket being bound to an address. In this case, automatically allocate
		an address and port to the socket. */
		if( pxAddress == NULL )
		{
			pxAddress = &xAddress;
			/* Put the port to zero to be assigned later. */
			pxAddress->sin_port = 0u;
		}
	}
	#endif /* ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND == 1 */

	/* Sockets must be bound before calling FreeRTOS_sendto() if
	ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is not set to 1. */
	configASSERT( pxAddress );

	if( pxAddress != NULL )
	{
		if( pxAddress->sin_port == 0u )
		{
			pxAddress->sin_port = prvGetPrivatePortNumber( ( BaseType_t )pxSocket->ucProtocol );
			if( 0 == pxAddress->sin_port )
			{
				return -pdFREERTOS_ERRNO_EADDRNOTAVAIL;
			}
		}

		/* If vSocketBind() is called from the API FreeRTOS_bind() it has been
		confirmed that the socket was not yet bound to a port.  If it is called
		from the IP-task, no such check is necessary. */

		/* Check to ensure the port is not already in use.  If the bind is
		called internally, a port MAY be used by more than one socket. */
		if( ( ( xInternal == pdFALSE ) || ( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP ) ) &&
			( pxListFindListItemWithValue( pxSocketList, ( TickType_t ) pxAddress->sin_port ) != NULL ) )
		{
			FreeRTOS_debug_printf( ( "vSocketBind: %sP port %d in use\n",
				pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP ? "TC" : "UD",
				FreeRTOS_ntohs( pxAddress->sin_port ) ) );
			xReturn = -pdFREERTOS_ERRNO_EADDRINUSE;
		}
		else
		{
			/* Allocate the port number to the socket.
			This macro will set 'xBoundSocketListItem->xItemValue' */
			socketSET_SOCKET_PORT( pxSocket, pxAddress->sin_port );

			/* And also store it in a socket field 'usLocalPort' in host-byte-order,
			mostly used for logging and debugging purposes */
			pxSocket->usLocalPort = FreeRTOS_ntohs( pxAddress->sin_port );

			/* Add the socket to the list of bound ports. */
			{
				/* If the network driver can iterate through 'xBoundUDPSocketsList',
				by calling xPortHasUDPSocket() then the IP-task must temporarily
				suspend the scheduler to keep the list in a consistent state. */
				#if( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 )
				{
					vTaskSuspendAll();
				}
				#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */

				/* Add the socket to 'xBoundUDPSocketsList' or 'xBoundTCPSocketsList' */
				vListInsertEnd( pxSocketList, &( pxSocket->xBoundSocketListItem ) );

				#if( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 )
				{
					xTaskResumeAll();
				}
				#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */
			}
		}
	}
	else
	{
		xReturn = -pdFREERTOS_ERRNO_EADDRNOTAVAIL;
		FreeRTOS_debug_printf( ( "vSocketBind: Socket no addr\n" ) );
	}

	if( xReturn != 0 )
	{
		iptraceBIND_FAILED( xSocket, ( FreeRTOS_ntohs( pxAddress->sin_port ) ) );
	}

	return xReturn;
} /* Tested */
/*-----------------------------------------------------------*/

/*
 * Close a socket and free the allocated space
 * In case of a TCP socket: the connection will not be closed automatically
 * Subsequent messages for the closed socket will be responded to with a RST
 * The IP-task will actually close the socket, after receiving a 'eSocketCloseEvent' message
 */
BaseType_t FreeRTOS_closesocket( Socket_t xSocket )
{
BaseType_t xResult;
#if( ipconfigUSE_TCP == 1 ) && ( ipconfigUSE_CALLBACKS == 1 )
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * )xSocket;
#endif
IPStackEvent_t xCloseEvent;
xCloseEvent.eEventType = eSocketCloseEvent;
xCloseEvent.pvData = ( void * ) xSocket;

	if( ( xSocket == NULL ) || ( xSocket == FREERTOS_INVALID_SOCKET ) )
	{
		xResult = 0;
	}
	else
	{
		#if( ( ipconfigUSE_TCP == 1 ) && ( ipconfigUSE_CALLBACKS == 1 ) )
		{
			if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP )
			{
				/* Make sure that IP-task won't call the user callback's anymore */
				pxSocket->u.xTCP.pxHandleConnected = NULL;
				pxSocket->u.xTCP.pxHandleReceive = NULL;
				pxSocket->u.xTCP.pxHandleSent = NULL;
			}
		}
		#endif  /* ( ( ipconfigUSE_TCP == 1 ) && ( ipconfigUSE_CALLBACKS == 1 ) ) */

		/* Let the IP task close the socket to keep it synchronised	with the
		packet handling. */

		/* Note when changing the time-out value below, it must be checked who is calling
		this function. If it is called by the IP-task, a deadlock could occur.
		The IP-task would only call it in case of a user call-back */
		if( xSendEventStructToIPTask( &xCloseEvent, ( TickType_t ) 0 ) == pdFAIL )
		{
			FreeRTOS_debug_printf( ( "FreeRTOS_closesocket: failed\n" ) );
			xResult = -1;
		}
		else
		{
			xResult = 1;
		}
	}

	return xResult;
}

/* This is the internal version of FreeRTOS_closesocket()
 * It will be called by the IPtask only to avoid problems with synchronicity
 */
void *vSocketClose( FreeRTOS_Socket_t *pxSocket )
{
NetworkBufferDescriptor_t *pxNetworkBuffer;

	#if( ipconfigUSE_TCP == 1 )
	{
		/* For TCP: clean up a little more. */
		if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			#if( ipconfigUSE_TCP_WIN == 1 )
			{
				if( pxSocket->u.xTCP.pxAckMessage != NULL )
				{
					vReleaseNetworkBufferAndDescriptor( pxSocket->u.xTCP.pxAckMessage );
				}
				/* Free the resources which were claimed by the tcpWin member */
				vTCPWindowDestroy( &pxSocket->u.xTCP.xTCPWindow );
			}
			#endif /* ipconfigUSE_TCP_WIN */

			/* Free the input and output streams */
			if( pxSocket->u.xTCP.rxStream != NULL )
			{
				vPortFreeLarge( pxSocket->u.xTCP.rxStream );
			}

			if( pxSocket->u.xTCP.txStream != NULL )
			{
				vPortFreeLarge( pxSocket->u.xTCP.txStream );
			}

			/* In case this is a child socket, make sure the child-count of the
			parent socket is decreased. */
			prvTCPSetSocketCount( pxSocket );
		}
	}
	#endif  /* ipconfigUSE_TCP == 1 */

	/* Socket must be unbound first, to ensure no more packets are queued on
	it. */
	if( socketSOCKET_IS_BOUND( pxSocket ) != pdFALSE )
	{
		/* If the network driver can iterate through 'xBoundUDPSocketsList',
		by calling xPortHasUDPSocket(), then the IP-task must temporarily
		suspend the scheduler to keep the list in a consistent state. */
		#if( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 )
		{
			vTaskSuspendAll();
		}
		#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */

		uxListRemove( &( pxSocket->xBoundSocketListItem ) );

		#if( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 )
		{
			xTaskResumeAll();
		}
		#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */
	}

	/* Now the socket is not bound the list of waiting packets can be
	drained. */
	if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_UDP )
	{
		while( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) > 0U )
		{
			pxNetworkBuffer = ( NetworkBufferDescriptor_t * ) listGET_OWNER_OF_HEAD_ENTRY( &( pxSocket->u.xUDP.xWaitingPacketsList ) );
			uxListRemove( &( pxNetworkBuffer->xBufferListItem ) );
			vReleaseNetworkBufferAndDescriptor( pxNetworkBuffer );
		}
	}

	if( pxSocket->xEventGroup )
	{
		vEventGroupDelete( pxSocket->xEventGroup );
	}

	#if( ipconfigUSE_TCP == 1 ) && ( ipconfigHAS_DEBUG_PRINTF != 0 )
	{
		if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			FreeRTOS_debug_printf( ( "FreeRTOS_closesocket[%u to %lxip:%u]: buffers %lu socks %lu\n",
				pxSocket->usLocalPort,
				pxSocket->u.xTCP.ulRemoteIP,
				pxSocket->u.xTCP.usRemotePort,
				uxGetNumberOfFreeNetworkBuffers(),
				listCURRENT_LIST_LENGTH( &xBoundTCPSocketsList ) ) );
		}
	}
	#endif /* ( ipconfigUSE_TCP == 1 ) && ( ipconfigHAS_DEBUG_PRINTF != 0 ) */

	/* Anf finally, after all resources have been freed, free the socket space */
	vPortFreeSocket( pxSocket );

	return 0;
} /* Tested */

/*-----------------------------------------------------------*/

#if ipconfigUSE_TCP == 1

	/*
	 * When a child socket gets closed, make sure to update the child-count of the
	 * parent.  When a listening parent socket is closed, make sure no child-sockets
	 * keep a pointer to it.
	 */
	static void prvTCPSetSocketCount( FreeRTOS_Socket_t *pxSocketToDelete )
	{
	const ListItem_t *pxIterator;
	const MiniListItem_t *pxEnd = ( const MiniListItem_t* )listGET_END_MARKER( &xBoundTCPSocketsList );
	FreeRTOS_Socket_t *pxOtherSocket;
	uint16_t usLocalPort = pxSocketToDelete->usLocalPort;

		for( pxIterator  = ( const ListItem_t * ) listGET_NEXT( pxEnd );
			 pxIterator != ( const ListItem_t * ) pxEnd;
			 pxIterator  = ( const ListItem_t * ) listGET_NEXT( pxIterator ) )
		{
			pxOtherSocket = ( FreeRTOS_Socket_t * ) listGET_LIST_ITEM_OWNER( pxIterator );
			if( ( pxOtherSocket->u.xTCP.ucTCPState == eTCP_LISTEN ) &&
				( pxOtherSocket->usLocalPort == usLocalPort ) &&
				( pxOtherSocket->u.xTCP.usChildCount ) )
			{
				pxOtherSocket->u.xTCP.usChildCount--;
				FreeRTOS_debug_printf( ( "Lost: Socket %u now has %u / %u child%s\n",
					pxOtherSocket->usLocalPort,
					pxOtherSocket->u.xTCP.usChildCount,
					pxOtherSocket->u.xTCP.usBacklog,
					pxOtherSocket->u.xTCP.usChildCount == 1u ? "" : "ren" ) );
				break;
			}
		}
	}

#endif /* ipconfigUSE_TCP == 1 */

/*-----------------------------------------------------------*/

BaseType_t FreeRTOS_setsockopt( Socket_t xSocket, int32_t lLevel, int32_t lOptionName, const void *pvOptionValue, size_t xOptionLength )
{
/* The standard Berkeley function returns 0 for success. */
BaseType_t xReturn = -pdFREERTOS_ERRNO_EINVAL;
BaseType_t lOptionValue;
FreeRTOS_Socket_t *pxSocket;

	pxSocket = ( FreeRTOS_Socket_t * ) xSocket;

	/* The function prototype is designed to maintain the expected Berkeley
	sockets standard, but this implementation does not use all the parameters. */
	( void ) lLevel;
	( void ) xOptionLength;

	configASSERT( xSocket );

	switch( lOptionName )
	{
		case FREERTOS_SO_RCVTIMEO	:
			/* Receive time out. */
			pxSocket->xReceiveBlockTime = *( ( TickType_t * ) pvOptionValue );
			xReturn = 0;
			break;

		case FREERTOS_SO_SNDTIMEO	:
			pxSocket->xSendBlockTime = *( ( TickType_t * ) pvOptionValue );
			if( pxSocket->ucProtocol == ( uint8_t ) FREERTOS_IPPROTO_UDP )
			{
				/* The send time out is capped for the reason stated in the
				comments where ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS is defined
				in FreeRTOSIPConfig.h (assuming an official configuration file
				is being used. */
				if( pxSocket->xSendBlockTime > ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS )
				{
					pxSocket->xSendBlockTime = ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS;
				}
			}
			else
			{
				/* For TCP socket, it isn't necessary to limit the blocking time
				because	the FreeRTOS_send() function does not wait for a network
				buffer to become available. */
			}
			xReturn = 0;
			break;
		#if( ipconfigUDP_MAX_RX_PACKETS > 0 )
			case FREERTOS_SO_UDP_MAX_RX_PACKETS:
				if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_UDP )
				{
					break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
				}
				pxSocket->u.xUDP.uxMaxPackets = *( ( UBaseType_t * ) pvOptionValue );
				xReturn = 0;
				break;
		#endif /* ipconfigUDP_MAX_RX_PACKETS */

		case FREERTOS_SO_UDPCKSUM_OUT :
			/* Turn calculating of the UDP checksum on/off for this socket. */
			lOptionValue = ( BaseType_t ) pvOptionValue;

			if( lOptionValue == 0 )
			{
				pxSocket->ucSocketOptions &= ( uint8_t ) ~FREERTOS_SO_UDPCKSUM_OUT;
			}
			else
			{
				pxSocket->ucSocketOptions |= ( uint8_t ) FREERTOS_SO_UDPCKSUM_OUT;
			}
			xReturn = 0;
			break;

		#if( ipconfigUSE_CALLBACKS == 1 )
			#if( ipconfigUSE_TCP == 1 )
				case FREERTOS_SO_TCP_CONN_HANDLER:	/* Set a callback for (dis)connection events */
				case FREERTOS_SO_TCP_RECV_HANDLER:	/* Install a callback for receiving TCP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */
				case FREERTOS_SO_TCP_SENT_HANDLER:	/* Install a callback for sending TCP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */
			#endif /* ipconfigUSE_TCP */
				case FREERTOS_SO_UDP_RECV_HANDLER:	/* Install a callback for receiving UDP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */
				case FREERTOS_SO_UDP_SENT_HANDLER:	/* Install a callback for sending UDP data. Supply pointer to 'F_TCP_UDP_Handler_t' (see below) */
					{
						#if( ipconfigUSE_TCP == 1 )
						{
							UBaseType_t uxProtocol;
							if( ( lOptionName == FREERTOS_SO_UDP_RECV_HANDLER ) ||
								( lOptionName == FREERTOS_SO_UDP_SENT_HANDLER ) )
							{
								uxProtocol = ( UBaseType_t ) FREERTOS_IPPROTO_UDP;
							}
							else
							{
								uxProtocol = ( UBaseType_t ) FREERTOS_IPPROTO_TCP;
							}

							if( pxSocket->ucProtocol != ( uint8_t ) uxProtocol )
							{
								break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
							}
						}
						#else
						{
							/* No need to check if the socket has the right
							protocol, because only UDP socket can be created. */
						}
						#endif /* ipconfigUSE_TCP */

						switch( lOptionName )
						{
						#if ipconfigUSE_TCP == 1
							case FREERTOS_SO_TCP_CONN_HANDLER:
								pxSocket->u.xTCP.pxHandleConnected = ((F_TCP_UDP_Handler_t *)pvOptionValue)->pxOnTCPConnected;
								break;
							case FREERTOS_SO_TCP_RECV_HANDLER:
								pxSocket->u.xTCP.pxHandleReceive = ((F_TCP_UDP_Handler_t *)pvOptionValue)->pxOnTCPReceive;
								break;
							case FREERTOS_SO_TCP_SENT_HANDLER:
								pxSocket->u.xTCP.pxHandleSent = ((F_TCP_UDP_Handler_t *)pvOptionValue)->pxOnTCPSent;
								break;
						#endif /* ipconfigUSE_TCP */
						case FREERTOS_SO_UDP_RECV_HANDLER:
							pxSocket->u.xUDP.pxHandleReceive = ((F_TCP_UDP_Handler_t *)pvOptionValue)->pxOnUDPReceive;
							break;
						case FREERTOS_SO_UDP_SENT_HANDLER:
							pxSocket->u.xUDP.pxHandleSent = ((F_TCP_UDP_Handler_t *)pvOptionValue)->pxOnUDPSent;
							break;
						default:
							break;
						}
					}

					xReturn = 0;
					break;
		#endif /* ipconfigUSE_CALLBACKS */

		#if( ipconfigUSE_TCP != 0 )
			#if( ipconfigSOCKET_HAS_USER_SEMAPHORE != 0 )
				/* Each socket has a semaphore on which the using task normally
				sleeps. */
				case FREERTOS_SO_SET_SEMAPHORE:
					{
						pxSocket->pxUserSemaphore = *( ( SemaphoreHandle_t * ) pvOptionValue );
						xReturn = 0;
					}
					break;
			#endif /* ipconfigSOCKET_HAS_USER_SEMAPHORE */

			#if( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK != 0 )
				case FREERTOS_SO_WAKEUP_CALLBACK:
				{
					/* Each socket can have a callback function that is executed
					when there is an event the socket's owner might want to
					process. */
					pxSocket->pxUserWakeCallback = ( SocketWakeupCallback_t ) pvOptionValue;
					xReturn = 0;
				}
				break;
			#endif /* ipconfigSOCKET_HAS_USER_WAKE_CALLBACK */

			case FREERTOS_SO_SET_LOW_HIGH_WATER:
				{
				LowHighWater_t *pxLowHighWater = ( LowHighWater_t * ) pvOptionValue;

					if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
					{
						/* It is not allowed to access 'pxSocket->u.xTCP'. */
						FreeRTOS_debug_printf( ( "FREERTOS_SO_SET_LOW_HIGH_WATER: wrong socket type\n" ) );
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}
					if( ( pxLowHighWater->uxLittleSpace >= pxLowHighWater->uxEnoughSpace ) ||
						( pxLowHighWater->uxEnoughSpace > pxSocket->u.xTCP.uxRxStreamSize ) )
					{
						/* Impossible values. */
						FreeRTOS_debug_printf( ( "FREERTOS_SO_SET_LOW_HIGH_WATER: bad values\n" ) );
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}
					/* Send a STOP when buffer space drops below 'uxLittleSpace' bytes. */
					pxSocket->u.xTCP.uxLittleSpace = pxLowHighWater->uxLittleSpace;
					/* Send a GO when buffer space grows above 'uxEnoughSpace' bytes. */
					pxSocket->u.xTCP.uxEnoughSpace = pxLowHighWater->uxEnoughSpace;
					xReturn = 0;
				}
				break;

			case FREERTOS_SO_SNDBUF:	/* Set the size of the send buffer, in units of MSS (TCP only) */
			case FREERTOS_SO_RCVBUF:	/* Set the size of the receive buffer, in units of MSS (TCP only) */
				{
					uint32_t ulNewValue;

					if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
					{
						FreeRTOS_debug_printf( ( "Set SO_%sBUF: wrong socket type\n",
							( lOptionName == FREERTOS_SO_SNDBUF ) ? "SND" : "RCV" ) );
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}

					if( ( ( lOptionName == FREERTOS_SO_SNDBUF ) && ( pxSocket->u.xTCP.txStream != NULL ) ) ||
						( ( lOptionName == FREERTOS_SO_RCVBUF ) && ( pxSocket->u.xTCP.rxStream != NULL ) ) )
					{
						FreeRTOS_debug_printf( ( "Set SO_%sBUF: buffer already created\n",
							( lOptionName == FREERTOS_SO_SNDBUF ) ? "SND" : "RCV" ) );
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}

					ulNewValue = *( ( uint32_t * ) pvOptionValue );

					if( lOptionName == FREERTOS_SO_SNDBUF )
					{
						/* Round up to nearest MSS size */
						ulNewValue = FreeRTOS_round_up( ulNewValue, ( uint32_t ) pxSocket->u.xTCP.usInitMSS );
						pxSocket->u.xTCP.uxTxStreamSize = ulNewValue;
					}
					else
					{
						pxSocket->u.xTCP.uxRxStreamSize = ulNewValue;
					}
				}
				xReturn = 0;
				break;

			case FREERTOS_SO_WIN_PROPERTIES:	/* Set all buffer and window properties in one call, parameter is pointer to WinProperties_t */
				{
					WinProperties_t* pxProps;

					if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
					{
						FreeRTOS_debug_printf( ( "Set SO_WIN_PROP: wrong socket type\n" ) );
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}

					if( ( pxSocket->u.xTCP.txStream != NULL ) || ( pxSocket->u.xTCP.rxStream != NULL ) )
					{
						FreeRTOS_debug_printf( ( "Set SO_WIN_PROP: buffer already created\n" ) );
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}

					pxProps = ( ( WinProperties_t * ) pvOptionValue );

					if ( FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_SNDBUF, &( pxProps->lTxBufSize ), sizeof( pxProps->lTxBufSize ) ) != 0 )
					{
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}

					if ( FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVBUF, &( pxProps->lRxBufSize ), sizeof( pxProps->lRxBufSize ) ) != 0 )
					{
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}

					#if( ipconfigUSE_TCP_WIN == 1 )
					{
						pxSocket->u.xTCP.uxRxWinSize = ( uint32_t )pxProps->lRxWinSize;	/* Fixed value: size of the TCP reception window */
						pxSocket->u.xTCP.uxTxWinSize = ( uint32_t )pxProps->lTxWinSize;	/* Fixed value: size of the TCP transmit window */
					}
					#else
					{
						pxSocket->u.xTCP.uxRxWinSize = 1u;
						pxSocket->u.xTCP.uxTxWinSize = 1u;
					}
					#endif

					/* In case the socket has already initialised its tcpWin,
					adapt the window size parameters */
					if( pxSocket->u.xTCP.xTCPWindow.u.bits.bHasInit != pdFALSE_UNSIGNED )
					{
						pxSocket->u.xTCP.xTCPWindow.xSize.ulRxWindowLength = pxSocket->u.xTCP.uxRxWinSize * pxSocket->u.xTCP.usInitMSS;
						pxSocket->u.xTCP.xTCPWindow.xSize.ulTxWindowLength = pxSocket->u.xTCP.uxTxWinSize * pxSocket->u.xTCP.usInitMSS;
					}
				}

				xReturn = 0;
				break;

			case FREERTOS_SO_REUSE_LISTEN_SOCKET:	/* If true, the server-socket will turn into a connected socket */
				{
					if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
					{
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}
					if( *( ( BaseType_t * ) pvOptionValue ) != 0 )
					{
						pxSocket->u.xTCP.bits.bReuseSocket = pdTRUE_UNSIGNED;
					}
					else
					{
						pxSocket->u.xTCP.bits.bReuseSocket = pdFALSE_UNSIGNED;
					}
				}
				xReturn = 0;
				break;

			case FREERTOS_SO_CLOSE_AFTER_SEND:		/* As soon as the last byte has been transmitted, finalise the connection */
				{
					if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
					{
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}

					if( *( ( BaseType_t * ) pvOptionValue ) != 0 )
					{
						pxSocket->u.xTCP.bits.bCloseAfterSend = pdTRUE_UNSIGNED;
					}
					else
					{
						pxSocket->u.xTCP.bits.bCloseAfterSend = pdFALSE_UNSIGNED;
					}
				}
				xReturn = 0;
				break;

			case FREERTOS_SO_SET_FULL_SIZE:		/* Refuse to send packets smaller than MSS  */
				{
					if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
					{
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}

					if( *( ( BaseType_t * ) pvOptionValue ) != 0 )
					{
						pxSocket->u.xTCP.xTCPWindow.u.bits.bSendFullSize = pdTRUE_UNSIGNED;
					}
					else
					{
						pxSocket->u.xTCP.xTCPWindow.u.bits.bSendFullSize = pdFALSE_UNSIGNED;
					}

					if( ( pxSocket->u.xTCP.xTCPWindow.u.bits.bSendFullSize == pdFALSE_UNSIGNED ) &&
						( pxSocket->u.xTCP.ucTCPState >= eESTABLISHED ) &&
						( FreeRTOS_outstanding( pxSocket ) != 0 ) )
					{
						pxSocket->u.xTCP.usTimeout = 1u; /* to set/clear bSendFullSize */
						xSendEventToIPTask( eTCPTimerEvent );
					}
				}
				xReturn = 0;
				break;

			case FREERTOS_SO_STOP_RX:		/* Refuse to receive more packts */
				{
					if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
					{
						break;	/* will return -pdFREERTOS_ERRNO_EINVAL */
					}

					if( *( ( BaseType_t * ) pvOptionValue ) != 0 )
					{
						pxSocket->u.xTCP.bits.bRxStopped = pdTRUE_UNSIGNED;
					}
					else
					{
						pxSocket->u.xTCP.bits.bRxStopped = pdFALSE_UNSIGNED;
					}

					pxSocket->u.xTCP.bits.bWinChange = pdTRUE_UNSIGNED;
					pxSocket->u.xTCP.usTimeout = 1u; /* to set/clear bRxStopped */
					xSendEventToIPTask( eTCPTimerEvent );
				}
				xReturn = 0;
				break;

		#endif  /* ipconfigUSE_TCP == 1 */

		default :
			/* No other options are handled. */
			xReturn = -pdFREERTOS_ERRNO_ENOPROTOOPT;
			break;
	}

	return xReturn;
} /* Tested */

/*-----------------------------------------------------------*/

/* Find an available port number per https://tools.ietf.org/html/rfc6056. */
static uint16_t prvGetPrivatePortNumber( BaseType_t xProtocol )
{
const uint16_t usEphemeralPortCount =
	socketAUTO_PORT_ALLOCATION_MAX_NUMBER - socketAUTO_PORT_ALLOCATION_START_NUMBER + 1;
uint16_t usIterations = usEphemeralPortCount;
uint32_t ulRandomSeed = 0;
uint16_t usResult = 0;
const List_t *pxList;

#if ipconfigUSE_TCP == 1
	if( xProtocol == ( BaseType_t ) FREERTOS_IPPROTO_TCP )
	{
		pxList = &xBoundTCPSocketsList;
	}
	else
#endif
	{
		pxList = &xBoundUDPSocketsList;
	}

	/* Avoid compiler warnings if ipconfigUSE_TCP is not defined. */
	( void ) xProtocol;

	/* Find the next available port using the random seed as a starting
	point. */
	do
	{
		/* Only proceed if the random number generator succeeded. */
		if( xApplicationGetRandomNumber( &( ulRandomSeed ) ) == pdFALSE )
		{
			break;
		}

		/* Map the random to a candidate port. */
		usResult =
			socketAUTO_PORT_ALLOCATION_START_NUMBER +
			( ( ( uint16_t )ulRandomSeed ) % usEphemeralPortCount );

		/* Check if there's already an open socket with the same protocol
		and port. */
		if( NULL == pxListFindListItemWithValue(
			pxList,
			( TickType_t )FreeRTOS_htons( usResult ) ) )
		{
			usResult = FreeRTOS_htons( usResult );
			break;
		}
		else
		{
			usResult = 0;
		}

		usIterations--;
	}
	while( usIterations > 0 );

	return usResult;
}
/*-----------------------------------------------------------*/

/* pxListFindListItemWithValue: find a list item in a bound socket list
'xWantedItemValue' refers to a port number */
static const ListItem_t * pxListFindListItemWithValue( const List_t *pxList, TickType_t xWantedItemValue )
{
const ListItem_t * pxResult = NULL;

	if( ( xIPIsNetworkTaskReady() != pdFALSE ) && ( pxList != NULL ) )
	{
		const ListItem_t *pxIterator;
		const MiniListItem_t *pxEnd = ( const MiniListItem_t* )listGET_END_MARKER( pxList );
		for( pxIterator  = ( const ListItem_t * ) listGET_NEXT( pxEnd );
			 pxIterator != ( const ListItem_t * ) pxEnd;
			 pxIterator  = ( const ListItem_t * ) listGET_NEXT( pxIterator ) )
		{
			if( listGET_LIST_ITEM_VALUE( pxIterator ) == xWantedItemValue )
			{
				pxResult = pxIterator;
				break;
			}
		}
	}

	return pxResult;
} /* Tested */

/*-----------------------------------------------------------*/

FreeRTOS_Socket_t *pxUDPSocketLookup( UBaseType_t uxLocalPort )
{
const ListItem_t *pxListItem;
FreeRTOS_Socket_t *pxSocket = NULL;

	/* Looking up a socket is quite simple, find a match with the local port.

	See if there is a list item associated with the port number on the
	list of bound sockets. */
	pxListItem = pxListFindListItemWithValue( &xBoundUDPSocketsList, ( TickType_t ) uxLocalPort );

	if( pxListItem != NULL )
	{
		/* The owner of the list item is the socket itself. */
		pxSocket = ( FreeRTOS_Socket_t * ) listGET_LIST_ITEM_OWNER( pxListItem );
		configASSERT( pxSocket != NULL );
	}
	return pxSocket;
}

/*-----------------------------------------------------------*/

#if ipconfigINCLUDE_FULL_INET_ADDR == 1

	uint32_t FreeRTOS_inet_addr( const char * pcIPAddress )
	{
	const uint32_t ulDecimalBase = 10u;
	uint8_t ucOctet[ socketMAX_IP_ADDRESS_OCTETS ];
	const char *pcPointerOnEntering;
	uint32_t ulReturn = 0UL, ulValue;
	UBaseType_t uxOctetNumber;
	BaseType_t xResult = pdPASS;

		for( uxOctetNumber = 0u; uxOctetNumber < socketMAX_IP_ADDRESS_OCTETS; uxOctetNumber++ )
		{
			ulValue = 0ul;
			pcPointerOnEntering = pcIPAddress;

			while( ( *pcIPAddress >= '0' ) && ( *pcIPAddress <= '9' ) )
			{
				/* Move previous read characters into the next decimal
				position. */
				ulValue *= ulDecimalBase;

				/* Add the binary value of the ascii character. */
				ulValue += ( ( uint32_t ) ( *pcIPAddress ) - ( uint32_t ) '0' );

				/* Move to next character in the string. */
				pcIPAddress++;
			}

			/* Check characters were read. */
			if( pcIPAddress == pcPointerOnEntering )
			{
				xResult = pdFAIL;
			}

			/* Check the value fits in an 8-bit number. */
			if( ulValue > 0xffUL )
			{
				xResult = pdFAIL;
			}
			else
			{
				ucOctet[ uxOctetNumber ] = ( uint8_t ) ulValue;

				/* Check the next character is as expected. */
				if( uxOctetNumber < ( socketMAX_IP_ADDRESS_OCTETS - 1u ) )
				{
					if( *pcIPAddress != '.' )
					{
						xResult = pdFAIL;
					}
					else
					{
						/* Move past the dot. */
						pcIPAddress++;
					}
				}
			}

			if( xResult == pdFAIL )
			{
				/* No point going on. */
				break;
			}
		}

		if( *pcIPAddress != ( char ) 0 )
		{
			/* Expected the end of the string. */
			xResult = pdFAIL;
		}

		if( uxOctetNumber != socketMAX_IP_ADDRESS_OCTETS )
		{
			/* Didn't read enough octets. */
			xResult = pdFAIL;
		}

		if( xResult == pdPASS )
		{
			ulReturn = FreeRTOS_inet_addr_quick( ucOctet[ 0 ], ucOctet[ 1 ], ucOctet[ 2 ], ucOctet[ 3 ] );
		}

		return ulReturn;
	}

#endif /* ipconfigINCLUDE_FULL_INET_ADDR */

/*-----------------------------------------------------------*/

/* Function to get the local address and IP port */
size_t FreeRTOS_GetLocalAddress( Socket_t xSocket, struct freertos_sockaddr *pxAddress )
{
FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;

	/* IP address of local machine. */
	pxAddress->sin_addr = *ipLOCAL_IP_ADDRESS_POINTER;

	/* Local port on this machine. */
	pxAddress->sin_port = FreeRTOS_htons( pxSocket->usLocalPort );

	return sizeof( *pxAddress );
}

/*-----------------------------------------------------------*/

void vSocketWakeUpUser( FreeRTOS_Socket_t *pxSocket )
{
/* _HT_ must work this out, now vSocketWakeUpUser will be called for any important
 * event or transition */
	#if( ipconfigSOCKET_HAS_USER_SEMAPHORE == 1 )
	{
		if( pxSocket->pxUserSemaphore != NULL )
		{
			xSemaphoreGive( pxSocket->pxUserSemaphore );
		}
	}
	#endif /* ipconfigSOCKET_HAS_USER_SEMAPHORE */

	#if( ipconfigSOCKET_HAS_USER_WAKE_CALLBACK == 1 )
	{
		if( pxSocket->pxUserWakeCallback != NULL )
		{
			pxSocket->pxUserWakeCallback( pxSocket );
		}
	}
	#endif /* ipconfigSOCKET_HAS_USER_SEMAPHORE */

	#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
	{
		if( pxSocket->pxSocketSet != NULL )
		{
			EventBits_t xSelectBits = ( pxSocket->xEventBits >> SOCKET_EVENT_BIT_COUNT ) & eSELECT_ALL;
			if( xSelectBits != 0ul )
			{
				pxSocket->xSocketBits |= xSelectBits;
				xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, xSelectBits );
			}
		}

		pxSocket->xEventBits &= eSOCKET_ALL;
	}
	#endif /* ipconfigSUPPORT_SELECT_FUNCTION */

	if( ( pxSocket->xEventGroup != NULL ) && ( pxSocket->xEventBits != 0u ) )
	{
		xEventGroupSetBits( pxSocket->xEventGroup, pxSocket->xEventBits );
	}

	pxSocket->xEventBits = 0ul;
}

/*-----------------------------------------------------------*/

#if( ipconfigETHERNET_DRIVER_FILTERS_PACKETS == 1 )

	/* This define makes it possible for network-card drivers to inspect
	 * UDP message and see if there is any UDP socket bound to a given port
	 * number.
	 * This is probably only usefull in systems with a minimum of RAM and
	 * when lots of anonymous broadcast messages come in
	 */
	BaseType_t xPortHasUDPSocket( uint16_t usPortNr )
	{
	BaseType_t xFound = pdFALSE;

		vTaskSuspendAll();
		{
			if( ( pxListFindListItemWithValue( &xBoundUDPSocketsList, ( TickType_t ) usPortNr ) != NULL ) )
			{
				xFound = pdTRUE;
			}
		}
		xTaskResumeAll();

		return xFound;
	}

#endif /* ipconfigETHERNET_DRIVER_FILTERS_PACKETS */

/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	static BaseType_t bMayConnect( FreeRTOS_Socket_t *pxSocket );
	static BaseType_t bMayConnect( FreeRTOS_Socket_t *pxSocket )
	{
		switch( pxSocket->u.xTCP.ucTCPState )
		{
			case eCLOSED:
			case eCLOSE_WAIT:	return 0;
			case eCONNECT_SYN:	return -pdFREERTOS_ERRNO_EINPROGRESS;
			default:			return -pdFREERTOS_ERRNO_EAGAIN;
		}
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	static BaseType_t prvTCPConnectStart( FreeRTOS_Socket_t *pxSocket, struct freertos_sockaddr *pxAddress )
	{
	BaseType_t xResult = 0;

		if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdFALSE )
		{
			/* Not a valid socket or wrong type */
			xResult = -pdFREERTOS_ERRNO_EBADF;
		}
		else if( FreeRTOS_issocketconnected( pxSocket ) > 0 )
		{
			/* The socket is already connected. */
			xResult = -pdFREERTOS_ERRNO_EISCONN;
		}
		else if( socketSOCKET_IS_BOUND( pxSocket ) == pdFALSE )
		{
			/* Bind the socket to the port that the client task will send from.
			Non-standard, so the error returned is that returned by bind(). */
			xResult = FreeRTOS_bind( ( Socket_t ) pxSocket, NULL, 0u );
		}

		if( xResult == 0 )
		{
			/* Check if it makes any sense to wait for a connect event, this condition
			might change while sleeping, so it must be checked within each loop */
			xResult = bMayConnect( pxSocket ); /* -EINPROGRESS, -EAGAIN, or 0 for OK */

			/* Start the connect procedure, kernel will start working on it */
			if( xResult == 0 )
			{
				pxSocket->u.xTCP.bits.bConnPrepared = pdFALSE_UNSIGNED;
				pxSocket->u.xTCP.ucRepCount = 0u;

				FreeRTOS_debug_printf( ( "FreeRTOS_connect: %u to %lxip:%u\n",
					pxSocket->usLocalPort, FreeRTOS_ntohl( pxAddress->sin_addr ), FreeRTOS_ntohs( pxAddress->sin_port ) ) );

				/* Port on remote machine. */
				pxSocket->u.xTCP.usRemotePort = FreeRTOS_ntohs( pxAddress->sin_port );

				/* IP address of remote machine. */
				pxSocket->u.xTCP.ulRemoteIP = FreeRTOS_ntohl( pxAddress->sin_addr );

				/* (client) internal state: socket wants to send a connect. */
				vTCPStateChange( pxSocket, eCONNECT_SYN );

				/* To start an active connect. */
				pxSocket->u.xTCP.usTimeout = 1u;

				if( xSendEventToIPTask( eTCPTimerEvent ) != pdPASS )
				{
					xResult = -pdFREERTOS_ERRNO_ECANCELED;
				}
			}
		}

		return xResult;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/*
	 * FreeRTOS_connect: socket wants to connect to a remote port
	 */
	BaseType_t FreeRTOS_connect( Socket_t xClientSocket, struct freertos_sockaddr *pxAddress, socklen_t xAddressLength )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t* ) xClientSocket;
	TickType_t xRemainingTime;
	BaseType_t xTimed = pdFALSE;
	BaseType_t xResult;
	TimeOut_t xTimeOut;

		( void ) xAddressLength;

		xResult = prvTCPConnectStart( pxSocket, pxAddress );

		if( xResult == 0 )
		{
			/* And wait for the result */
			for( ;; )
			{
				if( xTimed == pdFALSE )
				{
					/* Only in the first round, check for non-blocking */
					xRemainingTime = pxSocket->xReceiveBlockTime;
					if( xRemainingTime == ( TickType_t )0 )
					{
						/* Not yet connected, correct state, non-blocking. */
						xResult = -pdFREERTOS_ERRNO_EWOULDBLOCK;
						break;
					}

					/* Don't get here a second time. */
					xTimed = pdTRUE;

					/* Fetch the current time */
					vTaskSetTimeOutState( &xTimeOut );
				}

				/* Did it get connected while sleeping ? */
				xResult = FreeRTOS_issocketconnected( pxSocket );

				/* Returns positive when connected, negative means an error */
				if( xResult < 0 )
				{
					/* Return the error */
					break;
				}

				if( xResult > 0 )
				{
					/* Socket now connected, return a zero */
					xResult = 0;
					break;
				}

				/* Is it allowed to sleep more? */
				if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) )
				{
					xResult = -pdFREERTOS_ERRNO_ETIMEDOUT;
					break;
				}

				/* Go sleeping until we get any down-stream event */
				xEventGroupWaitBits( pxSocket->xEventGroup, eSOCKET_CONNECT, pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime );
			}
		}

		return xResult;
	}
#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/*
	 * FreeRTOS_accept: can return a new connected socket
	 * if the server socket is in listen mode and receives a connection request
	 * The new socket will be bound already to the same port number as the listing
	 * socket.
	 */
	Socket_t FreeRTOS_accept( Socket_t xServerSocket, struct freertos_sockaddr *pxAddress, socklen_t *pxAddressLength )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xServerSocket;
	FreeRTOS_Socket_t *pxClientSocket = NULL;
	TickType_t xRemainingTime;
	BaseType_t xTimed = pdFALSE, xAsk = pdFALSE;
	TimeOut_t xTimeOut;
	IPStackEvent_t xAskEvent;

		if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE )
		{
			/* Not a valid socket or wrong type */
			pxClientSocket = ( FreeRTOS_Socket_t * ) FREERTOS_INVALID_SOCKET;
		}
		else if( ( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED ) &&
				 ( pxSocket->u.xTCP.ucTCPState != eTCP_LISTEN ) )
		{
			/* Parent socket is not in listening mode */
			pxClientSocket = ( FreeRTOS_Socket_t * ) FREERTOS_INVALID_SOCKET;
		}
		else
		{
			/* Loop will stop with breaks. */
			for( ; ; )
			{
				/* Is there a new client? */
				vTaskSuspendAll();
				{
					if( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED )
					{
						pxClientSocket = pxSocket->u.xTCP.pxPeerSocket;
					}
					else
					{
						pxClientSocket = pxSocket;
					}
					if( pxClientSocket != NULL )
					{
						pxSocket->u.xTCP.pxPeerSocket = NULL;

						/* Is it still not taken ? */
						if( pxClientSocket->u.xTCP.bits.bPassAccept != pdFALSE_UNSIGNED )
						{
							pxClientSocket->u.xTCP.bits.bPassAccept = pdFALSE_UNSIGNED;
						}
						else
						{
							pxClientSocket = NULL;
						}
					}
				}
				xTaskResumeAll();

				if( pxClientSocket != NULL )
				{
					if( pxAddress != NULL )
					{
						/* IP address of remote machine. */
						pxAddress->sin_addr = FreeRTOS_ntohl( pxClientSocket->u.xTCP.ulRemoteIP );

						/* Port on remote machine. */
						pxAddress->sin_port = FreeRTOS_ntohs( pxClientSocket->u.xTCP.usRemotePort );
					}
					if( pxAddressLength != NULL )
					{
						*pxAddressLength = sizeof( *pxAddress );
					}

					if( pxSocket->u.xTCP.bits.bReuseSocket == pdFALSE_UNSIGNED )
					{
						xAsk = pdTRUE;
					}
				}

				if( xAsk != pdFALSE )
				{
					/* Ask to set an event in 'xEventGroup' as soon as a new
					client gets connected for this listening socket. */
					xAskEvent.eEventType = eTCPAcceptEvent;
					xAskEvent.pvData = ( void * ) pxSocket;
					xSendEventStructToIPTask( &xAskEvent, portMAX_DELAY );
				}

				if( pxClientSocket != NULL )
				{
					break;
				}

				if( xTimed == pdFALSE )
				{
					/* Only in the first round, check for non-blocking */
					xRemainingTime = pxSocket->xReceiveBlockTime;
					if( xRemainingTime == ( TickType_t ) 0 )
					{
						break;
					}

					/* Don't get here a second time */
					xTimed = pdTRUE;

					/* Fetch the current time */
					vTaskSetTimeOutState( &xTimeOut );
				}

				/* Has the timeout been reached? */
				if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE )
				{
					break;
				}

				/* Go sleeping until we get any down-stream event */
				xEventGroupWaitBits( pxSocket->xEventGroup, eSOCKET_ACCEPT, pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime );
			}
		}

		return ( Socket_t ) pxClientSocket;
	}
#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/*
	 * Read incoming data from a TCP socket
	 * Only after the last byte has been read, a close error might be returned
	 */
	BaseType_t FreeRTOS_recv( Socket_t xSocket, void *pvBuffer, size_t xBufferLength, BaseType_t xFlags )
	{
	BaseType_t xByteCount;
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	TickType_t xRemainingTime;
	BaseType_t xTimed = pdFALSE;
	TimeOut_t xTimeOut;
	EventBits_t xEventBits = ( EventBits_t ) 0;

		/* Check if the socket is valid, has type TCP and if it is bound to a
		port. */
		if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE )
		{
			xByteCount = -pdFREERTOS_ERRNO_EINVAL;
		}
		else
		{
			if( pxSocket->u.xTCP.rxStream != NULL )
			{
				xByteCount = ( BaseType_t )uxStreamBufferGetSize ( pxSocket->u.xTCP.rxStream );
			}
			else
			{
				xByteCount = 0;
			}

			while( xByteCount == 0 )
			{
				switch( pxSocket->u.xTCP.ucTCPState )
				{
				case eCLOSED:
				case eCLOSE_WAIT:	/* (server + client) waiting for a connection termination request from the local user. */
				case eCLOSING:		/* (server + client) waiting for a connection termination request acknowledgement from the remote TCP. */
					if( pxSocket->u.xTCP.bits.bMallocError != pdFALSE_UNSIGNED )
					{
						/* The no-memory error has priority above the non-connected error.
						Both are fatal and will elad to closing the socket. */
						xByteCount = -pdFREERTOS_ERRNO_ENOMEM;
					}
					else
					{
						xByteCount = -pdFREERTOS_ERRNO_ENOTCONN;
					}
					/* Call continue to break out of the switch and also the while
					loop. */
					continue;
				default:
					break;
				}

				if( xTimed == pdFALSE )
				{
					/* Only in the first round, check for non-blocking. */
					xRemainingTime = pxSocket->xReceiveBlockTime;

					if( xRemainingTime == ( TickType_t ) 0 )
					{
						#if( ipconfigSUPPORT_SIGNALS != 0 )
						{
							/* Just check for the interrupt flag. */
							xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup, eSOCKET_INTR,
								pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, socketDONT_BLOCK );
						}
						#endif /* ipconfigSUPPORT_SIGNALS */
						break;
					}

					if( ( xFlags & FREERTOS_MSG_DONTWAIT ) != 0 )
					{
						break;
					}

					/* Don't get here a second time. */
					xTimed = pdTRUE;

					/* Fetch the current time. */
					vTaskSetTimeOutState( &xTimeOut );
				}

				/* Has the timeout been reached? */
				if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE )
				{
					break;
				}

				/* Block until there is a down-stream event. */
				xEventBits = xEventGroupWaitBits( pxSocket->xEventGroup,
					eSOCKET_RECEIVE | eSOCKET_CLOSED | eSOCKET_INTR,
					pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime );
				#if( ipconfigSUPPORT_SIGNALS != 0 )
				{
					if( ( xEventBits & eSOCKET_INTR ) != 0u )
					{
						break;
					}
				}
				#else
				{
					( void ) xEventBits;
				}
				#endif /* ipconfigSUPPORT_SIGNALS */

				if( pxSocket->u.xTCP.rxStream != NULL )
				{
					xByteCount = ( BaseType_t ) uxStreamBufferGetSize ( pxSocket->u.xTCP.rxStream );
				}
				else
				{
					xByteCount = 0;
				}
			}

		#if( ipconfigSUPPORT_SIGNALS != 0 )
			if( ( xEventBits & eSOCKET_INTR ) != 0 )
			{
				if( ( xEventBits & ( eSOCKET_RECEIVE | eSOCKET_CLOSED ) ) != 0 )
				{
					/* Shouldn't have cleared other flags. */
					xEventBits &= ~eSOCKET_INTR;
					xEventGroupSetBits( pxSocket->xEventGroup, xEventBits );
				}
				xByteCount = -pdFREERTOS_ERRNO_EINTR;
			}
			else
		#endif /* ipconfigSUPPORT_SIGNALS */
			if( xByteCount > 0 )
			{
				if( ( xFlags & FREERTOS_ZERO_COPY ) == 0 )
				{
					xByteCount = ( BaseType_t ) uxStreamBufferGet( pxSocket->u.xTCP.rxStream, 0ul, ( uint8_t * ) pvBuffer, ( size_t ) xBufferLength, ( xFlags & FREERTOS_MSG_PEEK ) != 0 );
					if( pxSocket->u.xTCP.bits.bLowWater != pdFALSE_UNSIGNED )
					{
						/* We had reached the low-water mark, now see if the flag
						can be cleared */
						size_t uxFrontSpace = uxStreamBufferFrontSpace( pxSocket->u.xTCP.rxStream );

						if( uxFrontSpace >= pxSocket->u.xTCP.uxEnoughSpace )
						{
							pxSocket->u.xTCP.bits.bLowWater = pdFALSE_UNSIGNED;
							pxSocket->u.xTCP.bits.bWinChange = pdTRUE_UNSIGNED;
							pxSocket->u.xTCP.usTimeout = 1u; /* because bLowWater is cleared. */
							xSendEventToIPTask( eTCPTimerEvent );
						}
					}
				}
				else
				{
					/* Zero-copy reception of data: pvBuffer is a pointer to a pointer. */
					xByteCount = ( BaseType_t ) uxStreamBufferGetPtr( pxSocket->u.xTCP.rxStream, (uint8_t **)pvBuffer );
				}
			}
		} /* prvValidSocket() */

		return xByteCount;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	static int32_t prvTCPSendCheck( FreeRTOS_Socket_t *pxSocket, size_t xDataLength )
	{
	int32_t xResult = 1;

		/* Is this a socket of type TCP and is it already bound to a port number ? */
		if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE )
		{
			xResult = -pdFREERTOS_ERRNO_EINVAL;
		}
		else if( pxSocket->u.xTCP.bits.bMallocError != pdFALSE_UNSIGNED )
		{
			xResult = -pdFREERTOS_ERRNO_ENOMEM;
		}
		else if( pxSocket->u.xTCP.ucTCPState == eCLOSED ||
                 pxSocket->u.xTCP.ucTCPState == eCLOSE_WAIT ||
                 pxSocket->u.xTCP.ucTCPState == eCLOSING )
		{
			xResult = -pdFREERTOS_ERRNO_ENOTCONN;
		}
		else if( pxSocket->u.xTCP.bits.bFinSent != pdFALSE_UNSIGNED )
		{
			/* This TCP connection is closing already, the FIN flag has been sent.
			Maybe it is still delivering or receiving data.
			Return OK in order not to get closed/deleted too quickly */
			xResult = 0;
		}
		else if( xDataLength == 0ul )
		{
			/* send() is being called to send zero bytes */
			xResult = 0;
		}
		else if( pxSocket->u.xTCP.txStream == NULL )
		{
			/* Create the outgoing stream only when it is needed */
			prvTCPCreateStream( pxSocket, pdFALSE );

			if( pxSocket->u.xTCP.txStream == NULL )
			{
				xResult = -pdFREERTOS_ERRNO_ENOMEM;
			}
		}

		return xResult;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/* Get a direct pointer to the circular transmit buffer.
	'*pxLength' will contain the number of bytes that may be written. */
	uint8_t *FreeRTOS_get_tx_head( Socket_t xSocket, BaseType_t *pxLength )
	{
    uint8_t *pucReturn = NULL;
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	StreamBuffer_t *pxBuffer = NULL;

        *pxLength = 0;

        /* Confirm that this is a TCP socket before dereferencing structure
        member pointers. */
        if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdTRUE )
        {
            pxBuffer = pxSocket->u.xTCP.txStream;
            if( pxBuffer != NULL )
            {
            BaseType_t xSpace = ( BaseType_t )uxStreamBufferGetSpace( pxBuffer );
            BaseType_t xRemain = ( BaseType_t )( pxBuffer->LENGTH - pxBuffer->uxHead );

                *pxLength = FreeRTOS_min_BaseType( xSpace, xRemain );
                pucReturn = pxBuffer->ucArray + pxBuffer->uxHead;
            }
		}

		return pucReturn;
	}
#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )
	/*
	 * Send data using a TCP socket.  It is not necessary to have the socket
	 * connected already.  Outgoing data will be stored and delivered as soon as
	 * the socket gets connected.
	 */
	BaseType_t FreeRTOS_send( Socket_t xSocket, const void *pvBuffer, size_t uxDataLength, BaseType_t xFlags )
	{
	BaseType_t xByteCount;
	BaseType_t xBytesLeft;
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	TickType_t xRemainingTime;
	BaseType_t xTimed = pdFALSE;
	TimeOut_t xTimeOut;
	BaseType_t xCloseAfterSend;

		/* Prevent compiler warnings about unused parameters.  The parameter
		may be used in future versions. */
		( void ) xFlags;

		xByteCount = ( BaseType_t ) prvTCPSendCheck( pxSocket, uxDataLength );

		if( xByteCount > 0 )
		{
			/* xBytesLeft is number of bytes to send, will count to zero. */
			xBytesLeft = ( BaseType_t ) uxDataLength;

			/* xByteCount is number of bytes that can be sent now. */
			xByteCount = ( BaseType_t ) uxStreamBufferGetSpace( pxSocket->u.xTCP.txStream );

			/* While there are still bytes to be sent. */
			while( xBytesLeft > 0 )
			{
				/* If txStream has space. */
				if( xByteCount > 0 )
				{
					/* Don't send more than necessary. */
					if( xByteCount > xBytesLeft )
					{
						xByteCount = xBytesLeft;
					}

					/* Is the close-after-send flag set and is this really the
					last transmission? */
					if( ( pxSocket->u.xTCP.bits.bCloseAfterSend != pdFALSE_UNSIGNED ) && ( xByteCount == xBytesLeft ) )
					{
						xCloseAfterSend = pdTRUE;
					}
					else
					{
						xCloseAfterSend = pdFALSE;
					}

					/* The flag 'bCloseAfterSend' can be set before sending data
					using setsockopt()

					When the last data packet is being sent out, a FIN flag will
					be included to let the peer know that no more data is to be
					expected.  The use of 'bCloseAfterSend' is not mandatory, it
					is just a faster way of transferring files (e.g. when using
					FTP). */
					if( xCloseAfterSend != pdFALSE )
					{
						/* Now suspend the scheduler: sending the last data	and
						setting bCloseRequested must be done together */
						vTaskSuspendAll();
						pxSocket->u.xTCP.bits.bCloseRequested = pdTRUE_UNSIGNED;
					}

					xByteCount = ( BaseType_t ) uxStreamBufferAdd( pxSocket->u.xTCP.txStream, 0ul, ( const uint8_t * ) pvBuffer, ( size_t ) xByteCount );

					if( xCloseAfterSend != pdFALSE )
					{
						/* Now when the IP-task transmits the data, it will also
						see	that bCloseRequested is true and include the FIN
						flag to start closure of the connection. */
						xTaskResumeAll();
					}

					/* Send a message to the IP-task so it can work on this
					socket.  Data is sent, let the IP-task work on it. */
					pxSocket->u.xTCP.usTimeout = 1u;

					if( xIsCallingFromIPTask() == pdFALSE )
					{
						/* Only send a TCP timer event when not called from the
						IP-task. */
						xSendEventToIPTask( eTCPTimerEvent );
					}

					xBytesLeft -= xByteCount;

					if( xBytesLeft == 0 )
					{
						break;
					}

					/* As there are still bytes left to be sent, increase the
					data pointer. */
					pvBuffer = ( void * ) ( ( ( const uint8_t * ) pvBuffer) + xByteCount );
				}

				/* Not all bytes have been sent. In case the socket is marked as
				blocking sleep for a while. */
				if( xTimed == pdFALSE )
				{
					/* Only in the first round, check for non-blocking. */
					xRemainingTime = pxSocket->xSendBlockTime;

					#if( ipconfigUSE_CALLBACKS != 0 )
					{
						if( xIsCallingFromIPTask() != pdFALSE )
						{
							/* If this send function is called from within a
							call-back handler it may not block, otherwise
							chances would be big to get a deadlock: the IP-task
							waiting for	itself. */
							xRemainingTime = ( TickType_t ) 0;
						}
					}
					#endif /* ipconfigUSE_CALLBACKS */

					if( xRemainingTime == ( TickType_t ) 0 )
					{
						break;
					}

					if( ( xFlags & FREERTOS_MSG_DONTWAIT ) != 0 )
					{
						break;
					}

					/* Don't get here a second time. */
					xTimed = pdTRUE;

					/* Fetch the current time. */
					vTaskSetTimeOutState( &xTimeOut );
				}
				else
				{
					/* Has the timeout been reached? */
					if( xTaskCheckForTimeOut( &xTimeOut, &xRemainingTime ) != pdFALSE )
					{
						break;
					}
				}

				/* Go sleeping until down-stream events are received. */
				xEventGroupWaitBits( pxSocket->xEventGroup, eSOCKET_SEND | eSOCKET_CLOSED,
					pdTRUE /*xClearOnExit*/, pdFALSE /*xWaitAllBits*/, xRemainingTime );

				xByteCount = ( BaseType_t ) uxStreamBufferGetSpace( pxSocket->u.xTCP.txStream );
			}

			/* How much was actually sent? */
			xByteCount = ( ( BaseType_t ) uxDataLength ) - xBytesLeft;

			if( xByteCount == 0 )
			{
				if( pxSocket->u.xTCP.ucTCPState > eESTABLISHED )
				{
					xByteCount = ( BaseType_t ) -pdFREERTOS_ERRNO_ENOTCONN;
				}
				else
				{
					if( ipconfigTCP_MAY_LOG_PORT( pxSocket->usLocalPort ) != pdFALSE )
					{
						FreeRTOS_debug_printf( ( "FreeRTOS_send: %u -> %lxip:%d: no space\n",
							pxSocket->usLocalPort,
							pxSocket->u.xTCP.ulRemoteIP,
							pxSocket->u.xTCP.usRemotePort ) );
					}

					xByteCount = ( BaseType_t ) -pdFREERTOS_ERRNO_ENOSPC;
				}
			}
		}

		return xByteCount;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/*
	 * Request to put a socket in listen mode
	 */
	BaseType_t FreeRTOS_listen( Socket_t xSocket, BaseType_t xBacklog )
	{
	FreeRTOS_Socket_t *pxSocket;
	BaseType_t xResult = 0;

		pxSocket = ( FreeRTOS_Socket_t * ) xSocket;

		/* listen() is allowed for a valid TCP socket in Closed state and already
		bound. */
		if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE )
		{
			xResult = -pdFREERTOS_ERRNO_EOPNOTSUPP;
		}
		else if( ( pxSocket->u.xTCP.ucTCPState != eCLOSED ) && ( pxSocket->u.xTCP.ucTCPState != eCLOSE_WAIT ) )
		{
			/* Socket is in a wrong state. */
			xResult = -pdFREERTOS_ERRNO_EOPNOTSUPP;
		}
		else
		{
			/* Backlog is interpreted here as "the maximum number of child
			sockets. */
			pxSocket->u.xTCP.usBacklog = ( uint16_t )FreeRTOS_min_int32( ( int32_t ) 0xffff, ( int32_t ) xBacklog );

			/* This cleaning is necessary only if a listening socket is being
			reused as it might have had a previous connection. */
			if( pxSocket->u.xTCP.bits.bReuseSocket )
			{
				if( pxSocket->u.xTCP.rxStream != NULL )
				{
					vStreamBufferClear( pxSocket->u.xTCP.rxStream );
				}

				if( pxSocket->u.xTCP.txStream != NULL )
				{
					vStreamBufferClear( pxSocket->u.xTCP.txStream );
				}

				memset( pxSocket->u.xTCP.xPacket.u.ucLastPacket, '\0', sizeof( pxSocket->u.xTCP.xPacket.u.ucLastPacket ) );
				memset( &pxSocket->u.xTCP.xTCPWindow, '\0', sizeof( pxSocket->u.xTCP.xTCPWindow ) );
				memset( &pxSocket->u.xTCP.bits, '\0', sizeof( pxSocket->u.xTCP.bits ) );

				/* Now set the bReuseSocket flag again, because the bits have
				just been cleared. */
				pxSocket->u.xTCP.bits.bReuseSocket = pdTRUE_UNSIGNED;
			}

			vTCPStateChange( pxSocket, eTCP_LISTEN );
		}

		return xResult;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/* shutdown - shut down part of a full-duplex connection */
	BaseType_t FreeRTOS_shutdown( Socket_t xSocket, BaseType_t xHow )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xResult;

		if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdTRUE ) == pdFALSE )
		{
			/*_RB_ Is this comment correct?  The socket is not of a type that
			supports the listen() operation. */
			xResult = -pdFREERTOS_ERRNO_EOPNOTSUPP;
		}
		else if ( pxSocket->u.xTCP.ucTCPState != eESTABLISHED )
		{
			/*_RB_ Is this comment correct?  The socket is not of a type that
			supports the listen() operation. */
			xResult = -pdFREERTOS_ERRNO_EOPNOTSUPP;
		}
		else
		{
			pxSocket->u.xTCP.bits.bUserShutdown = pdTRUE_UNSIGNED;

			/* Let the IP-task perform the shutdown of the connection. */
			pxSocket->u.xTCP.usTimeout = 1u;
			xSendEventToIPTask( eTCPTimerEvent );
			xResult = 0;
		}
		(void) xHow;

		return xResult;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/*
	 * A TCP timer has expired, now check all TCP sockets for:
	 * - Active connect
	 * - Send a delayed ACK
	 * - Send new data
	 * - Send a keep-alive packet
	 * - Check for timeout (in non-connected states only)
	 */
	TickType_t xTCPTimerCheck( BaseType_t xWillSleep )
	{
	FreeRTOS_Socket_t *pxSocket;
	TickType_t xShortest = pdMS_TO_TICKS( ( TickType_t ) ipTCP_TIMER_PERIOD_MS );
	TickType_t xNow = xTaskGetTickCount();
	static TickType_t xLastTime = 0u;
	TickType_t xDelta = xNow - xLastTime;
	ListItem_t* pxEnd = ( ListItem_t * ) listGET_END_MARKER( &xBoundTCPSocketsList );
	ListItem_t *pxIterator = ( ListItem_t * ) listGET_HEAD_ENTRY( &xBoundTCPSocketsList );

		xLastTime = xNow;

		if( xDelta == 0u )
		{
			xDelta = 1u;
		}

		while( pxIterator != pxEnd )
		{
			pxSocket = ( FreeRTOS_Socket_t * )listGET_LIST_ITEM_OWNER( pxIterator );
			pxIterator = ( ListItem_t * ) listGET_NEXT( pxIterator );

			/* Sockets with 'tmout == 0' do not need any regular attention. */
			if( pxSocket->u.xTCP.usTimeout == 0u )
			{
				continue;
			}

			if( xDelta < ( TickType_t ) pxSocket->u.xTCP.usTimeout )
			{
				pxSocket->u.xTCP.usTimeout = ( uint16_t ) ( ( ( TickType_t ) pxSocket->u.xTCP.usTimeout ) - xDelta );
			}
			else
			{
			int rc ;
				pxSocket->u.xTCP.usTimeout = 0u;
				rc = xTCPSocketCheck( pxSocket );

				/* Within this function, the socket might want to send a delayed
				ack or send out data or whatever it needs to do. */
				if( rc < 0 )
				{
					/* Continue because the socket was deleted. */
					continue;
				}
			}

			/* In xEventBits the driver may indicate that the socket has
			important events for the user.  These are only done just before the
			IP-task goes to sleep. */
			if( pxSocket->xEventBits != 0u )
			{
				if( xWillSleep != pdFALSE )
				{
					/* The IP-task is about to go to sleep, so messages can be
					sent to the socket owners. */
					vSocketWakeUpUser( pxSocket );
				}
				else
				{
					/* Or else make sure this will be called again to wake-up
					the sockets' owner. */
					xShortest = ( TickType_t ) 0;
				}
			}

			if( ( pxSocket->u.xTCP.usTimeout != 0u ) && ( xShortest > ( TickType_t ) pxSocket->u.xTCP.usTimeout ) )
			{
				xShortest = ( TickType_t ) pxSocket->u.xTCP.usTimeout;
			}
		}

		return xShortest;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/*
	 * TCP: as multiple sockets may be bound to the same local port number
	 * looking up a socket is a little more complex:
	 * Both a local port, and a remote port and IP address are being used
	 * For a socket in listening mode, the remote port and IP address are both 0
	 */
	FreeRTOS_Socket_t *pxTCPSocketLookup( uint32_t ulLocalIP, UBaseType_t uxLocalPort, uint32_t ulRemoteIP, UBaseType_t uxRemotePort )
	{
	ListItem_t *pxIterator;
	FreeRTOS_Socket_t *pxResult = NULL, *pxListenSocket = NULL;
	MiniListItem_t *pxEnd = ( MiniListItem_t* )listGET_END_MARKER( &xBoundTCPSocketsList );

		/* Parameter not yet supported. */
		( void ) ulLocalIP;

		for( pxIterator  = ( ListItem_t * ) listGET_NEXT( pxEnd );
			 pxIterator != ( ListItem_t * ) pxEnd;
			 pxIterator  = ( ListItem_t * ) listGET_NEXT( pxIterator ) )
		{
			FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) listGET_LIST_ITEM_OWNER( pxIterator );

			if( pxSocket->usLocalPort == ( uint16_t ) uxLocalPort )
			{
				if( pxSocket->u.xTCP.ucTCPState == eTCP_LISTEN )
				{
					/* If this is a socket listening to uxLocalPort, remember it
					in case there is no perfect match. */
					pxListenSocket = pxSocket;
				}
				else if( ( pxSocket->u.xTCP.usRemotePort == ( uint16_t ) uxRemotePort ) && ( pxSocket->u.xTCP.ulRemoteIP == ulRemoteIP ) )
				{
					/* For sockets not in listening mode, find a match with
					xLocalPort, ulRemoteIP AND xRemotePort. */
					pxResult = pxSocket;
					break;
				}
			}
		}
		if( pxResult == NULL )
		{
			/* An exact match was not found, maybe a listening socket was
			found. */
			pxResult = pxListenSocket;
		}

		return pxResult;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

    const struct xSTREAM_BUFFER *FreeRTOS_get_rx_buf( Socket_t xSocket )
    {
    FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * )xSocket;
    struct xSTREAM_BUFFER *pxReturn = NULL;

        /* Confirm that this is a TCP socket before dereferencing structure
        member pointers. */
        if( prvValidSocket( pxSocket, FREERTOS_IPPROTO_TCP, pdFALSE ) == pdTRUE )
        {
            pxReturn = pxSocket->u.xTCP.rxStream;
        }

        return pxReturn;
    }

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	static StreamBuffer_t *prvTCPCreateStream ( FreeRTOS_Socket_t *pxSocket, BaseType_t xIsInputStream )
	{
	StreamBuffer_t *pxBuffer;
	size_t uxLength;
	size_t uxSize;

		/* Now that a stream is created, the maximum size is fixed before
		creation, it could still be changed with setsockopt(). */
		if( xIsInputStream != pdFALSE )
		{
			uxLength = pxSocket->u.xTCP.uxRxStreamSize;

			if( pxSocket->u.xTCP.uxLittleSpace == 0ul )
			{
				pxSocket->u.xTCP.uxLittleSpace  = ( sock20_PERCENT * pxSocket->u.xTCP.uxRxStreamSize ) / sock100_PERCENT;
			}

			if( pxSocket->u.xTCP.uxEnoughSpace == 0ul )
			{
				pxSocket->u.xTCP.uxEnoughSpace = ( sock80_PERCENT * pxSocket->u.xTCP.uxRxStreamSize ) / sock100_PERCENT;
			}
		}
		else
		{
			uxLength = pxSocket->u.xTCP.uxTxStreamSize;
		}

		/* Add an extra 4 (or 8) bytes. */
		uxLength += sizeof( size_t );

		/* And make the length a multiple of sizeof( size_t ). */
		uxLength &= ~( sizeof( size_t ) - 1u );

		uxSize = sizeof( *pxBuffer ) - sizeof( pxBuffer->ucArray ) + uxLength;

		pxBuffer = ( StreamBuffer_t * )pvPortMallocLarge( uxSize );

		if( pxBuffer == NULL )
		{
			FreeRTOS_debug_printf( ( "prvTCPCreateStream: malloc failed\n" ) );
			pxSocket->u.xTCP.bits.bMallocError = pdTRUE_UNSIGNED;
			vTCPStateChange( pxSocket, eCLOSE_WAIT );
		}
		else
		{
			/* Clear the markers of the stream */
			memset( pxBuffer, '\0', sizeof( *pxBuffer ) - sizeof( pxBuffer->ucArray ) );
			pxBuffer->LENGTH = ( size_t ) uxLength ;

			if( xTCPWindowLoggingLevel != 0 )
			{
				FreeRTOS_debug_printf( ( "prvTCPCreateStream: %cxStream created %lu bytes (total %lu)\n", xIsInputStream ? 'R' : 'T', uxLength, uxSize ) );
			}

			if( xIsInputStream != 0 )
			{
				pxSocket->u.xTCP.rxStream = pxBuffer;
			}
			else
			{
				pxSocket->u.xTCP.txStream = pxBuffer;
			}
		}

		return pxBuffer;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/*
	 * Add data to the RxStream.  When uxOffset > 0, data has come in out-of-order
	 * and will be put in front of the head so it can not be popped by the user.
	 */
	int32_t lTCPAddRxdata( FreeRTOS_Socket_t *pxSocket, size_t uxOffset, const uint8_t *pcData, uint32_t ulByteCount )
	{
	StreamBuffer_t *pxStream = pxSocket->u.xTCP.rxStream;
	int32_t xResult;
	#if( ipconfigUSE_CALLBACKS == 1 )
		BaseType_t bHasHandler = ipconfigIS_VALID_PROG_ADDRESS( pxSocket->u.xTCP.pxHandleReceive );
		const uint8_t *pucBuffer = NULL;
	#endif /* ipconfigUSE_CALLBACKS */

		/* int32_t uxStreamBufferAdd( pxBuffer, uxOffset, pucData, aCount )
		if( pucData != NULL ) copy data the the buffer
		if( pucData == NULL ) no copying, just advance rxHead
		if( uxOffset != 0 ) Just store data which has come out-of-order
		if( uxOffset == 0 ) Also advance rxHead */
		if( pxStream == NULL )
		{
			pxStream = prvTCPCreateStream( pxSocket, pdTRUE );
			if( pxStream == NULL )
			{
				return -1;
			}
		}

		#if( ipconfigUSE_CALLBACKS == 1 )
		{
			if( ( bHasHandler != pdFALSE ) && ( uxStreamBufferGetSize( pxStream ) == 0u ) && ( uxOffset == 0ul ) && ( pcData != NULL ) )
			{
				/* Data can be passed directly to the user */
				pucBuffer = pcData;

				/* Zero-copy for call-back: no need to add the bytes to the
				stream, only the pointer will be advanced by uxStreamBufferAdd(). */
				pcData = NULL;
			}
		}
		#endif /* ipconfigUSE_CALLBACKS */

		xResult = ( int32_t ) uxStreamBufferAdd( pxStream, uxOffset, pcData, ( size_t ) ulByteCount );

		#if( ipconfigHAS_DEBUG_PRINTF != 0 )
		{
			if( xResult != ( int32_t ) ulByteCount )
			{
				FreeRTOS_debug_printf( ( "lTCPAddRxdata: at %ld: %ld/%lu bytes (tail %lu head %lu space %lu front %lu)\n",
					uxOffset, xResult, ulByteCount,
					pxStream->uxTail,
					pxStream->uxHead,
					uxStreamBufferFrontSpace( pxStream ),
					pxStream->uxFront ) );
			}
		}
		#endif /* ipconfigHAS_DEBUG_PRINTF */

		if( uxOffset == 0u )
		{
			/* Data is being added to rxStream at the head (offs = 0) */
			#if( ipconfigUSE_CALLBACKS == 1 )
				if( bHasHandler != pdFALSE )
				{
					/* The socket owner has installed an OnReceive handler. Pass the
					Rx data, without copying from the rxStream, to the user. */
					for (;;)
					{
						uint8_t *ucReadPtr = NULL;
						uint32_t ulCount;
						if( pucBuffer != NULL )
						{
							ucReadPtr = ( uint8_t * )pucBuffer;
							ulCount = ulByteCount;
							pucBuffer = NULL;
						}
						else
						{
							ulCount = ( uint32_t ) uxStreamBufferGetPtr( pxStream, &( ucReadPtr ) );
						}

						if( ulCount == 0ul )
						{
							break;
						}

						pxSocket->u.xTCP.pxHandleReceive( ( Socket_t )pxSocket, ( void* )ucReadPtr, ( size_t ) ulCount );
						uxStreamBufferGet( pxStream, 0ul, NULL, ( size_t ) ulCount, pdFALSE );
					}
				} else
			#endif /* ipconfigUSE_CALLBACKS */
			{
				/* See if running out of space. */
				if( pxSocket->u.xTCP.bits.bLowWater == pdFALSE_UNSIGNED )
				{
					size_t uxFrontSpace = uxStreamBufferFrontSpace( pxSocket->u.xTCP.rxStream );
					if( uxFrontSpace <= pxSocket->u.xTCP.uxLittleSpace  )
					{
						pxSocket->u.xTCP.bits.bLowWater = pdTRUE_UNSIGNED;
						pxSocket->u.xTCP.bits.bWinChange = pdTRUE_UNSIGNED;

						/* bLowWater was reached, send the changed window size. */
						pxSocket->u.xTCP.usTimeout = 1u;
						xSendEventToIPTask( eTCPTimerEvent );
					}
				}

				/* New incoming data is available, wake up the user.   User's
				semaphores will be set just before the IP-task goes asleep. */
				pxSocket->xEventBits |= eSOCKET_RECEIVE;

				#if ipconfigSUPPORT_SELECT_FUNCTION == 1
				{
					if( ( pxSocket->xSelectBits & eSELECT_READ ) != 0 )
					{
						pxSocket->xEventBits |= ( eSELECT_READ << SOCKET_EVENT_BIT_COUNT );
					}
				}
				#endif
			}
		}

		return xResult;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/* Function to get the remote address and IP port */
	BaseType_t FreeRTOS_GetRemoteAddress( Socket_t xSocket, struct freertos_sockaddr *pxAddress )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xResult;

		if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			xResult = -pdFREERTOS_ERRNO_EINVAL;
		}
		else
		{
			/* BSD style sockets communicate IP and port addresses in network
			byte order.

			IP address of remote machine. */
			pxAddress->sin_addr = FreeRTOS_htonl ( pxSocket->u.xTCP.ulRemoteIP );

			/* Port on remote machine. */
			pxAddress->sin_port = FreeRTOS_htons ( pxSocket->u.xTCP.usRemotePort );

			xResult = ( BaseType_t ) sizeof( ( *pxAddress ) );
		}

		return xResult;
	}

#endif /* ipconfigUSE_TCP */

/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/* Returns the number of bytes that may be added to txStream */
	BaseType_t FreeRTOS_maywrite( Socket_t xSocket )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xResult;

		if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			xResult = -pdFREERTOS_ERRNO_EINVAL;
		}
		else if( pxSocket->u.xTCP.ucTCPState != eESTABLISHED )
		{
			if( ( pxSocket->u.xTCP.ucTCPState < eCONNECT_SYN ) || ( pxSocket->u.xTCP.ucTCPState > eESTABLISHED ) )
			{
				xResult = -1;
			}
			else
			{
				xResult = 0;
			}
		}
		else if( pxSocket->u.xTCP.txStream == NULL )
		{
			xResult = ( BaseType_t ) pxSocket->u.xTCP.uxTxStreamSize;
		}
		else
		{
			xResult = ( BaseType_t ) uxStreamBufferGetSpace( pxSocket->u.xTCP.txStream );
		}

		return xResult;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP ==1 )

	BaseType_t FreeRTOS_tx_space( Socket_t xSocket )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xReturn;

		if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			xReturn = -pdFREERTOS_ERRNO_EINVAL;
		}
		else
		{
			if( pxSocket->u.xTCP.txStream != NULL )
			{
				xReturn = ( BaseType_t ) uxStreamBufferGetSpace ( pxSocket->u.xTCP.txStream );
			}
			else
			{
				xReturn = ( BaseType_t ) pxSocket->u.xTCP.uxTxStreamSize;
			}
		}

		return xReturn;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	BaseType_t FreeRTOS_tx_size( Socket_t xSocket )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xReturn;

		if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			xReturn = -pdFREERTOS_ERRNO_EINVAL;
		}
		else
		{
			if( pxSocket->u.xTCP.txStream != NULL )
			{
				xReturn = ( BaseType_t ) uxStreamBufferGetSize ( pxSocket->u.xTCP.txStream );
			}
			else
			{
				xReturn = 0;
			}
		}

		return xReturn;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/* Returns pdTRUE if TCP socket is connected. */
	BaseType_t FreeRTOS_issocketconnected( Socket_t xSocket )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xReturn = pdFALSE;

		if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			xReturn = -pdFREERTOS_ERRNO_EINVAL;
		}
		else
		{
			if( pxSocket->u.xTCP.ucTCPState >= eESTABLISHED )
			{
				if( pxSocket->u.xTCP.ucTCPState < eCLOSE_WAIT )
				{
					xReturn = pdTRUE;
				}
			}
		}

		return xReturn;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/* returns the actual size of MSS being used */
	BaseType_t FreeRTOS_mss( Socket_t xSocket )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xReturn;

		if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			xReturn = -pdFREERTOS_ERRNO_EINVAL;
		}
		else
		{
			/* usCurMSS is declared as uint16_t to save space.  FreeRTOS_mss()
			will often be used in signed native-size expressions cast it to
			BaseType_t. */
			xReturn = ( BaseType_t ) ( pxSocket->u.xTCP.usCurMSS );
		}

		return xReturn;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/* HT: for internal use only: return the connection status */
	BaseType_t FreeRTOS_connstatus( Socket_t xSocket )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xReturn;

		if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			xReturn = -pdFREERTOS_ERRNO_EINVAL;
		}
		else
		{
			/* Cast it to BaseType_t */
			xReturn = ( BaseType_t ) ( pxSocket->u.xTCP.ucTCPState );
		}

		return xReturn;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	/*
	 * Returns the number of bytes which can be read.
	 */
	BaseType_t FreeRTOS_rx_size( Socket_t xSocket )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xReturn;

		if( pxSocket->ucProtocol != ( uint8_t ) FREERTOS_IPPROTO_TCP )
		{
			xReturn = -pdFREERTOS_ERRNO_EINVAL;
		}
		else if( pxSocket->u.xTCP.rxStream != NULL )
		{
			xReturn = ( BaseType_t ) uxStreamBufferGetSize( pxSocket->u.xTCP.rxStream );
		}
		else
		{
			xReturn = 0;
		}

		return xReturn;
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ipconfigUSE_TCP == 1 )

	void FreeRTOS_netstat( void )
	{
	IPStackEvent_t xAskEvent;

		/* Ask the IP-task to call vTCPNetStat()
		 * to avoid accessing xBoundTCPSocketsList
		 */
		xAskEvent.eEventType = eTCPNetStat;
		xAskEvent.pvData = ( void * ) NULL;
		xSendEventStructToIPTask( &xAskEvent, 1000u );
	}

#endif /* ipconfigUSE_TCP */
/*-----------------------------------------------------------*/

#if( ( ipconfigHAS_PRINTF != 0 ) && ( ipconfigUSE_TCP == 1 ) )

	void vTCPNetStat( void )
	{
	/* Show a simple listing of all created sockets and their connections */
	ListItem_t *pxIterator;
	BaseType_t count = 0;

		if( listLIST_IS_INITIALISED( &xBoundTCPSocketsList ) == pdFALSE )
		{
			FreeRTOS_printf( ( "PLUS-TCP not initialized\n" ) );
		}
		else
		{
			FreeRTOS_printf( ( "Prot Port IP-Remote	   : Port  R/T Status	   Alive  tmout Child\n" ) );
			for( pxIterator  = ( ListItem_t * ) listGET_HEAD_ENTRY( &xBoundTCPSocketsList );
				 pxIterator != ( ListItem_t * ) listGET_END_MARKER( &xBoundTCPSocketsList );
				 pxIterator  = ( ListItem_t * ) listGET_NEXT( pxIterator ) )
			{
				FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) listGET_LIST_ITEM_OWNER( pxIterator );
				#if( ipconfigTCP_KEEP_ALIVE == 1 )
					TickType_t age = xTaskGetTickCount() - pxSocket->u.xTCP.xLastAliveTime;
				#else
					TickType_t age = 0u;
				#endif
				#if( ipconfigUSE_CALLBACKS == 1 )
					void *pxHandleReceive = (void*)pxSocket->u.xTCP.pxHandleReceive;
				#else
					void *pxHandleReceive = (void*)NULL;
				#endif
				char ucChildText[16] = "";
				if (pxSocket->u.xTCP.ucTCPState == eTCP_LISTEN)
				{
					const int32_t copied_len = snprintf( ucChildText, sizeof( ucChildText ), " %d/%d",
						( int ) pxSocket->u.xTCP.usChildCount,
						( int ) pxSocket->u.xTCP.usBacklog);
					/* These should never evaluate to false since the buffers are both shorter than 5-6 characters (<=65535) */
					configASSERT( copied_len >= 0 );
					configASSERT( copied_len < sizeof( ucChildText ) );
				}
				FreeRTOS_printf( ( "TCP %5d %-16lxip:%5d %d/%d %-13.13s %6lu %6u%s\n",
					pxSocket->usLocalPort,		/* Local port on this machine */
					pxSocket->u.xTCP.ulRemoteIP,	/* IP address of remote machine */
					pxSocket->u.xTCP.usRemotePort,	/* Port on remote machine */
					pxSocket->u.xTCP.rxStream != NULL,
					pxSocket->u.xTCP.txStream != NULL,
					FreeRTOS_GetTCPStateName( pxSocket->u.xTCP.ucTCPState ),
					(age > 999999 ? 999999 : age), /* Format 'age' for printing */
					pxSocket->u.xTCP.usTimeout,
					ucChildText ) );
					/* Remove compiler warnings if FreeRTOS_debug_printf() is not defined. */
					( void ) pxHandleReceive;
				count++;
			}

			for( pxIterator  = ( ListItem_t * ) listGET_HEAD_ENTRY( &xBoundUDPSocketsList );
				 pxIterator != ( ListItem_t * ) listGET_END_MARKER( &xBoundUDPSocketsList );
				 pxIterator  = ( ListItem_t * ) listGET_NEXT( pxIterator ) )
			{
				/* Local port on this machine */
				FreeRTOS_printf( ( "UDP Port %5u\n",
					FreeRTOS_ntohs( listGET_LIST_ITEM_VALUE( pxIterator ) ) ) );
				count++;
			}

			FreeRTOS_printf( ( "FreeRTOS_netstat: %lu sockets %lu < %lu < %d buffers free\n",
				count,
				uxGetMinimumFreeNetworkBuffers( ),
				uxGetNumberOfFreeNetworkBuffers( ),
				ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS ) );
		}
	}

#endif /* ( ( ipconfigHAS_PRINTF != 0 ) && ( ipconfigUSE_TCP == 1 ) ) */
/*-----------------------------------------------------------*/

#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )

	void vSocketSelect( SocketSelect_t *pxSocketSet )
	{
	BaseType_t xRound;
	EventBits_t xSocketBits, xBitsToClear;
	#if ipconfigUSE_TCP == 1
		BaseType_t xLastRound = 1;
	#else
		BaseType_t xLastRound = 0;
	#endif

		/* These flags will be switched on after checking the socket status. */
		EventBits_t xGroupBits = 0;
		pxSocketSet->pxSocket = NULL;

		for( xRound = 0; xRound <= xLastRound; xRound++ )
		{
			const ListItem_t *pxIterator;
			const MiniListItem_t *pxEnd;
			if( xRound == 0 )
			{
				pxEnd = ( const MiniListItem_t* )listGET_END_MARKER( &xBoundUDPSocketsList );
			}
		#if ipconfigUSE_TCP == 1
			else
			{
				pxEnd = ( const MiniListItem_t* )listGET_END_MARKER( &xBoundTCPSocketsList );
			}
		#endif /* ipconfigUSE_TCP == 1 */
			for( pxIterator = ( const ListItem_t * ) ( listGET_NEXT( pxEnd ) );
				 pxIterator != ( const ListItem_t * ) pxEnd;
				 pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) )
			{
				FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) listGET_LIST_ITEM_OWNER( pxIterator );
				if( pxSocket->pxSocketSet != pxSocketSet )
				{
					/* Socket does not belong to this select group. */
					continue;
				}
				xSocketBits = 0;

				#if( ipconfigUSE_TCP == 1 )
					if( pxSocket->ucProtocol == FREERTOS_IPPROTO_TCP )
					{
						/* Check if the socket has already been accepted by the
						owner.  If not, it is useless to return it from a
						select(). */
						BaseType_t bAccepted = pdFALSE;

						if( pxSocket->u.xTCP.bits.bPassQueued == pdFALSE_UNSIGNED )
						{
							if( pxSocket->u.xTCP.bits.bPassAccept == pdFALSE_UNSIGNED )
							{
								bAccepted = pdTRUE;
							}
						}

						/* Is the set owner interested in READ events? */
						if( ( pxSocket->xSelectBits & eSELECT_READ ) != 0 )
						{
							if( pxSocket->u.xTCP.ucTCPState == eTCP_LISTEN )
							{
								if( ( pxSocket->u.xTCP.pxPeerSocket != NULL ) && ( pxSocket->u.xTCP.pxPeerSocket->u.xTCP.bits.bPassAccept != 0 ) )
								{
									xSocketBits |= eSELECT_READ;
								}
							}
							else if( ( pxSocket->u.xTCP.bits.bReuseSocket != pdFALSE_UNSIGNED ) && ( pxSocket->u.xTCP.bits.bPassAccept != pdFALSE_UNSIGNED ) )
							{
								/* This socket has the re-use flag. After connecting it turns into
								aconnected socket. Set the READ event, so that accept() will be called. */
								xSocketBits |= eSELECT_READ;
							}
							else if( ( bAccepted != 0 ) && ( FreeRTOS_recvcount( pxSocket ) > 0 ) )
							{
								xSocketBits |= eSELECT_READ;
							}
						}
						/* Is the set owner interested in EXCEPTION events? */
						if( ( pxSocket->xSelectBits & eSELECT_EXCEPT ) != 0 )
						{
							if( ( pxSocket->u.xTCP.ucTCPState == eCLOSE_WAIT ) || ( pxSocket->u.xTCP.ucTCPState == eCLOSED ) )
							{
								xSocketBits |= eSELECT_EXCEPT;
							}
						}

						/* Is the set owner interested in WRITE events? */
						if( ( pxSocket->xSelectBits & eSELECT_WRITE ) != 0 )
						{
							BaseType_t bMatch = pdFALSE;

							if( bAccepted != 0 )
							{
								if( FreeRTOS_tx_space( pxSocket ) > 0 )
								{
									bMatch = pdTRUE;
								}
							}

							if( bMatch == pdFALSE )
							{
								if( ( pxSocket->u.xTCP.bits.bConnPrepared != pdFALSE_UNSIGNED ) &&
									( pxSocket->u.xTCP.ucTCPState >= eESTABLISHED ) &&
									( pxSocket->u.xTCP.bits.bConnPassed == pdFALSE_UNSIGNED ) )
								{
									pxSocket->u.xTCP.bits.bConnPassed = pdTRUE_UNSIGNED;
									bMatch = pdTRUE;
								}
							}

							if( bMatch != pdFALSE )
							{
								xSocketBits |= eSELECT_WRITE;
							}
						}
					}
					else
				#endif /* ipconfigUSE_TCP == 1 */
				{
					/* Select events for UDP are simpler. */
					if( ( ( pxSocket->xSelectBits & eSELECT_READ ) != 0 ) &&
						( listCURRENT_LIST_LENGTH( &( pxSocket->u.xUDP.xWaitingPacketsList ) ) > 0U ) )
					{
						xSocketBits |= eSELECT_READ;
					}
					/* The WRITE and EXCEPT bits are not used for UDP */
				}	/* if( pxSocket->ucProtocol == FREERTOS_IPPROTO_TCP ) */

				/* Each socket keeps its own event flags, which are looked-up
				by FreeRTOS_FD_ISSSET() */
				pxSocket->xSocketBits = xSocketBits;

				/* The ORed value will be used to set the bits in the event
				group. */
				xGroupBits |= xSocketBits;

			}	/* for( pxIterator ... ) */
		}	/* for( xRound = 0; xRound <= xLastRound; xRound++ ) */

		xBitsToClear = xEventGroupGetBits( pxSocketSet->xSelectGroup );

		/* Now set the necessary bits. */
		xBitsToClear = ( xBitsToClear & ~xGroupBits ) & eSELECT_ALL;

		#if( ipconfigSUPPORT_SIGNALS != 0 )
		{
			/* Maybe the socketset was signalled, but don't
			clear the 'eSELECT_INTR' bit here, as it will be used
			and cleared in FreeRTOS_select(). */
			xBitsToClear &= ( EventBits_t ) ~eSELECT_INTR;
		}
		#endif /* ipconfigSUPPORT_SIGNALS */

		if( xBitsToClear != 0 )
		{
			xEventGroupClearBits( pxSocketSet->xSelectGroup, xBitsToClear );
		}

		/* Now include eSELECT_CALL_IP to wakeup the caller. */
		xEventGroupSetBits( pxSocketSet->xSelectGroup, xGroupBits | eSELECT_CALL_IP );
	}

#endif /* ipconfigSUPPORT_SELECT_FUNCTION == 1 */
/*-----------------------------------------------------------*/

#if( ipconfigSUPPORT_SIGNALS != 0 )

	/* Send a signal to the task which reads from this socket. */
	BaseType_t FreeRTOS_SignalSocket( Socket_t xSocket )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xReturn;

		if( pxSocket == NULL )
		{
			xReturn = -pdFREERTOS_ERRNO_EINVAL;
		}
		else
	#if( ipconfigSUPPORT_SELECT_FUNCTION == 1 )
		if( ( pxSocket->pxSocketSet != NULL ) && ( pxSocket->pxSocketSet->xSelectGroup != NULL ) )
		{
			xEventGroupSetBits( pxSocket->pxSocketSet->xSelectGroup, eSELECT_INTR );
			xReturn = 0;
		}
		else
	#endif /* ipconfigSUPPORT_SELECT_FUNCTION */
		if( pxSocket->xEventGroup != NULL )
		{
			xEventGroupSetBits( pxSocket->xEventGroup, eSOCKET_INTR );
			xReturn = 0;
		}
		else
		{
			xReturn = -pdFREERTOS_ERRNO_EINVAL;
		}

		return xReturn;
	}

#endif /* ipconfigSUPPORT_SIGNALS */
/*-----------------------------------------------------------*/

#if( ipconfigSUPPORT_SIGNALS != 0 )

	/* Send a signal to the task which reads from this socket (FromISR version). */
	BaseType_t FreeRTOS_SignalSocketFromISR( Socket_t xSocket, BaseType_t *pxHigherPriorityTaskWoken )
	{
	FreeRTOS_Socket_t *pxSocket = ( FreeRTOS_Socket_t * ) xSocket;
	BaseType_t xReturn;
	IPStackEvent_t xEvent;
	extern QueueHandle_t xNetworkEventQueue;

		configASSERT( pxSocket != NULL );
		configASSERT( pxSocket->ucProtocol == FREERTOS_IPPROTO_TCP );
		configASSERT( pxSocket->xEventGroup );

		xEvent.eEventType = eSocketSignalEvent;
		xEvent.pvData = ( void * )pxSocket;

		/* The IP-task will call FreeRTOS_SignalSocket for this socket. */
		xReturn = xQueueSendToBackFromISR( xNetworkEventQueue, &xEvent, pxHigherPriorityTaskWoken );

		return xReturn;
	}

#endif /* ipconfigSUPPORT_SIGNALS */
/*-----------------------------------------------------------*/