arzmq-sys 0.6.3

Low-level bindings to the zeromq library
Documentation
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

/**
* @file protoSocket.cpp
* 
* @brief Network socket container class that provides consistent interface for 
* use of operating system (or simulation environment) transport sockets.
*/

#ifdef UNIX

#include <unistd.h>
#include <stdlib.h>  // for atoi()
#ifdef HAVE_IPV6
#ifdef MACOSX
#define __APPLE_USE_RFC_3542 1  // needed to invoke IPV6_PKTINFO
#endif // MACOSX
#include <netinet/in.h>
#endif  // HAVE_IPV6
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <errno.h>
#include <fcntl.h>

#ifndef SIOCGIFHWADDR
#if defined(SOLARIS) || defined(IRIX)
#include <sys/sockio.h> // for SIOCGIFADDR ioctl
#include <netdb.h>      // for res_init()
#include <sys/dlpi.h>
#include <stropts.h>
#else
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#include <ifaddrs.h> 
#endif  // if/else (SOLARIS || IRIX)
#endif  // !SIOCGIFHWADDR

#endif  // UNIX

#ifdef WIN32
#include <Winsock2.h>
#include <Ws2def.h>
#include <WS2tcpip.h>  // for extra socket options
#include <Mswsock.h>   // for even more
#include <Windows.h>
#include <Iphlpapi.h>
#include <Iptypes.h>
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
typedef UINT32 in_addr_t;
#endif  // WIN32

// NOTE: This value should be confirmed.  It's the apparently Linux-only approach we currently
//       use to set the IPv6 flow info header fields.  Other approaches are under investigation
//       (We seem to be only able to affect the "traffic class" bits at this time)
#ifndef IPV6_FLOWINFO_SEND
#define IPV6_FLOWINFO_SEND 33 // from linux/in6.h
#endif // !IPV6_FLOWINFO_SEND

#include <stdio.h>
#include <string.h>

#include "protoSocket.h"
#include "protoNet.h"
#include "protoDebug.h"

// Hack for using with NRL IPSEC implementation
#ifdef HAVE_NETSEC
#include <net/security.h>
extern void* netsec_request;
extern int netsec_requestlen;
#endif // HAVE_NETSEC

// Use this macro (-DSOCKLEN_T=X) in your system's Makefile if the type socklen_t is 
// not defined for your system (use "man getsockname" to see what type is required).

#ifdef SOCKLEN_T
#define socklen_t SOCKLEN_T
#else
#ifdef WIN32
//#define socklen_t int
#endif // WIN32
#endif // if/else SOCKLEN_T

#include "protoDispatcher.h"

#ifdef WIN32
const ProtoSocket::Handle ProtoSocket::INVALID_HANDLE = INVALID_SOCKET;
LPFN_WSARECVMSG ProtoSocket::WSARecvMsg = NULL;
#else
const ProtoSocket::Handle ProtoSocket::INVALID_HANDLE = -1;
#endif  // if/else WIN32

ProtoSocket::IPv6SupportStatus ProtoSocket::ipv6_support_status = IPV6_UNKNOWN;

ProtoSocket::ProtoSocket(ProtoSocket::Protocol theProtocol)
    : domain(IPv4), protocol(theProtocol), raw_protocol(RAW), state(CLOSED), 
      handle(INVALID_HANDLE), port(-1), tos(0), ecn_capable(false), ip_recvdstaddr(false),
#ifdef HAVE_IPV6
      flow_label(0),
#endif // HAVE_IPV6
      notifier(NULL), notify_output(false), notify_input(true), notify_exception(false),
#ifdef WIN32
      input_event_handle(NULL), output_event_handle(NULL), 
      input_ready(false), output_ready(false), closing(false),
#endif // WIN32
      listener(NULL), user_data(NULL)
{
   
}

ProtoSocket::~ProtoSocket()
{
    Close();
    if (NULL != listener)
    {
        delete listener;
        listener = NULL; 
    }
}

bool ProtoSocket::SetBlocking(bool blocking)
{
#ifdef UNIX
    if (blocking)
    {
        if(-1 == fcntl(handle, F_SETFL, fcntl(handle, F_GETFL, 0) & ~O_NONBLOCK))
        {
            PLOG(PL_ERROR, "ProtoSocket::SetBlocking() fcntl(F_SETFL(~O_NONBLOCK)) error: %s\n", GetErrorString());
            return false;
        }
    }
    else
    {
        if(-1 == fcntl(handle, F_SETFL, fcntl(handle, F_GETFL, 0) | O_NONBLOCK))
        {
            PLOG(PL_ERROR, "ProtoSocket::SetBlocking() fcntl(F_SETFL(O_NONBLOCK)) error: %s\n", GetErrorString());
            return false;
        }
    }
#endif // UNIX
    return true;  //Note: taken care automatically under Win32 by WSAAsyncSelect(), etc
}  // end ProtoSocket::SetBlocking(bool blocking)

bool ProtoSocket::StartInputNotification()
{
    if (!notify_input)
    {
	    notify_input = true;
	    notify_input = UpdateNotification();
    }
	return notify_input;
}  // end ProtoSocket::StartInputNotification()

void ProtoSocket::StopInputNotification()
{
	if (notify_input)
    {
	    notify_input = false;
	    UpdateNotification();
    }
}  // end ProtoSocket::StopInputNotification()

bool ProtoSocket::StartOutputNotification()
{
	if (!notify_output)
    {
	    notify_output = true;
	    notify_output = UpdateNotification();
    }
	return notify_output;
}  // end ProtoSocket::StartOutputNotification()

void ProtoSocket::StopOutputNotification()
{
	 if (notify_output)
    {
	    notify_output = false;
	    UpdateNotification();
    }
}  // end ProtoSocket::StopOutputNotification()

bool ProtoSocket::StartExceptionNotification()
{
    notify_exception = true;
    notify_exception = UpdateNotification();
    return notify_exception;
}  // end ProtoSocket::StartExceptionNotification()

void ProtoSocket::StopExceptionNotification()
{   
    notify_exception = false;
    UpdateNotification();
}  // ProtoSocket::StopExceptionNotification()

bool ProtoSocket::SetNotifier(ProtoSocket::Notifier* theNotifier)
{
    if (notifier != theNotifier)
    {
        if (IsOpen())
        {
            // 1) Detach old notifier, if any
            if (NULL != notifier)
            {
                notifier->UpdateSocketNotification(*this, 0);
                if (NULL == theNotifier)
                {
                    // Reset socket to "blocking"
                    if(!SetBlocking(true))
                        PLOG(PL_ERROR, "ProtoSocket::SetNotifier() SetBlocking(true) error\n", GetErrorString());
                }
            }
            else
            {
                // Set socket to "non-blocking"
				if(!SetBlocking(false))
                {
                    PLOG(PL_ERROR, "ProtoSocket::SetNotifier() SetBlocking(false) error\n", GetErrorString());
                    return false;
                }
#ifdef WIN32
                // Reset input/output ready to initial state?
                input_ready = false;
                output_ready = true;
#endif // WIN32
            }   
            // 2) Set and update new notifier (if applicable)
            notifier = theNotifier;
            if (!UpdateNotification())
            {
                notifier = NULL;  
                return false;
            } 
        }
        else
        {
            notifier = theNotifier;
        }
    }
    return true;
}  // end ProtoSocket::SetNotifier()

ProtoAddress::Type ProtoSocket::GetAddressType()
{
    switch (domain)
    {
        case LOCAL:
            return ProtoAddress::INVALID;  
        case IPv4:
            return ProtoAddress::IPv4;
#ifdef HAVE_IPV6
        case IPv6:
            return ProtoAddress::IPv6; 
#endif // HAVE_IPV6
#ifdef SIMULATE
        case SIM:
            return ProtoAddress::SIM;
#endif // SIMULATE
        default:
            return ProtoAddress::INVALID; 
    }  
}  // end ProtoSocket::GetAddressType()

/**
 * WIN32 needs the address type determine IPv6 _or_ IPv4 socket domain
 * @note WIN32 can't do IPv4 on an IPV6 socket!
 * Vista and above support dual stack sockets
 */
bool ProtoSocket::Open(UINT16               thePort, 
                       ProtoAddress::Type   addrType,
                       bool                 bindOnOpen)
{
    if (IsOpen()) Close();
#ifdef HAVE_IPV6
    if(addrType == ProtoAddress::IPv6)
    {
        if (!HostIsIPv6Capable())
        {
            PLOG(PL_ERROR,"ProtoSocket::Open() system not IPv6 capable?\n");
            return false;
        }
        domain = IPv6;
    }
    else
#endif // HAVE_IPV6
    {
        domain = IPv4;
    }    
    
    int socketType = 0;
    switch (protocol)
    {
        case UDP:
            socketType = SOCK_DGRAM;
            break;
        case TCP:
            socketType = SOCK_STREAM;
            break;
        case RAW:  
            socketType = SOCK_RAW;
            break;
        default:
	        PLOG(PL_ERROR,"ProtoSocket::Open() error: Unsupported protocol\n");
	        return false;
    }
    
#ifdef WIN32
#ifdef HAVE_IPV6
    int family = (IPv6 == domain) ? AF_INET6: AF_INET;
#else
    int family = AF_INET;
#endif // if/else HAVE_IPV6
    // Startup WinSock
	if (!ProtoAddress::Win32Startup())
    {
        PLOG(PL_ERROR, "ProtoSocket::Open() WSAStartup() error: %s\n", GetErrorString());
        return false;
    }
    // Since we're might want QoS, we need find a QoS-capable UDP service provider
    WSAPROTOCOL_INFO* infoPtr = NULL;
    WSAPROTOCOL_INFO* protocolInfo = NULL;
    DWORD buflen = 0;
    // Query to properly size protocolInfo buffer
    WSAEnumProtocols(NULL, protocolInfo, &buflen);
    if (buflen)
    {
        int protocolType;
        switch (protocol)
        {
            case UDP:
                protocolType = IPPROTO_UDP;
                break;
            case TCP:
                protocolType = IPPROTO_TCP;
                break;
            case RAW:  
                switch (raw_protocol)
                {
                    case RAW:
                        protocolType = IPPROTO_RAW;
                        break;
                    case UDP:
                        protocolType = IPPROTO_UDP;
                        break;
                    case TCP:
                        protocolType = IPPROTO_TCP;
                        break;
                    default:
                        protocolType = IPPROTO_RAW;
                }
                break; 
        }
        
        // Enumerate, try to find multipoint _AND_ QOS-capable UDP, and create a socket
        if ((protocolInfo = (WSAPROTOCOL_INFO*) new char[buflen]))
        {
            int count = WSAEnumProtocols(NULL, protocolInfo, &buflen);
            if (SOCKET_ERROR != count)
            {
                for (int i = 0; i < count; i++)
                {
                    switch (protocol)
                    {
                        // This code tries to find a multicast-capable UDP/TCP socket
                        // providers _without_ QoS support, if possible (but note will 
                        // use one with QoS support if this is not possible.  The reason
                        // for this is that, ironically, it appears that a socket _without_ 
                        // QoS support allows for more flexible control of IP TOS setting 
                        // by the app?!  (Note that this may be revisited if we someday 
                        // again dabble with Win32 RSVP support (if it still exists) in future
                        // Protolib apps)
                        case UDP:
                            if ((IPPROTO_UDP == protocolInfo[i].iProtocol) &&
                                (0 != (XP1_SUPPORT_MULTIPOINT & protocolInfo[i].dwServiceFlags1)))
                            {
                                
                                if ((NULL == infoPtr) ||
                                    (0 == (XP1_QOS_SUPPORTED & protocolInfo[i].dwServiceFlags1)))
                                {
                                    infoPtr = protocolInfo + i;
                                }
                            }
                            break;
                        case TCP:
                            if (IPPROTO_TCP == protocolInfo[i].iProtocol)
                            {
                                if ((NULL == infoPtr) ||
                                    (0 == (XP1_QOS_SUPPORTED & protocolInfo[i].dwServiceFlags1)))
                                {
                                    infoPtr = protocolInfo + i;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }  // end for (i=0..count)
            }
            else
            {
                PLOG(PL_ERROR, "ProtoSocket: WSAEnumProtocols() error2!\n");
                delete[] protocolInfo;
				ProtoAddress::Win32Cleanup();
                return false;
            }
        }
        else
        {
            PLOG(PL_ERROR, "ProtoSocket: Error allocating memory!\n");
			ProtoAddress::Win32Cleanup();
            return false;
        }        
    }
    else
    {
        PLOG(PL_WARN, "ProtoSocket::Open() WSAEnumProtocols() error1!\n");            
    }

    // Use WSASocket() to open right kind of socket
    // (Just a regular socket if infoPtr == NULL
    DWORD flags = WSA_FLAG_OVERLAPPED;
#ifndef _WIN32_WCE
    if (UDP == protocol) flags |= (WSA_FLAG_MULTIPOINT_C_LEAF | WSA_FLAG_MULTIPOINT_D_LEAF);
#endif // !_WIN32_WCE
    handle = WSASocket(family, socketType, 0, infoPtr, 0, flags);
    if (NULL != protocolInfo) delete[] protocolInfo;
    if (INVALID_HANDLE == handle)
    {
        PLOG(PL_ERROR, "ProtoSocket::Open() WSASocket() error: %s\n", GetErrorString());
	    ProtoAddress::Win32Cleanup();	
        return false;
    }
    if (NULL == (input_event_handle = WSACreateEvent()))
    {
        PLOG(PL_ERROR, "ProtoSocket::Open() WSACreateEvent() error: %s\n", GetErrorString());
        Close();
        return false;
    } 
	input_ready = false;
	output_ready = true;
#else 
#ifdef HAVE_IPV6
    int family = (IPv6 == domain) ? AF_INET6: AF_INET;
#else
    int family = AF_INET;
#endif // if/else HAVE_IPV6
    
    /*if (AF_INET6 == family)
        TRACE("opening an IPV6 socket\n");
    else
        TRACE("opening an IPV4 socket\n");*/
    int socketProtocol = 0;  // use default socket protocol type if not RAW
    if (SOCK_RAW == socketType)
    {
        switch (raw_protocol)
        {
            case RAW:
                socketProtocol = IPPROTO_RAW;
                break;
            case UDP:
                socketProtocol = IPPROTO_UDP;
                break;
            case TCP:
                socketProtocol = IPPROTO_TCP;
                break;
            default:
                socketProtocol = IPPROTO_RAW;
        }
    }
    if (INVALID_HANDLE == (handle = socket(family, socketType, socketProtocol)))
    {
       PLOG(PL_ERROR, "ProtoSocket::Open() socket() error: %s\n", GetErrorString());
       return false;
    }
    // (TBD) set IP_HDRINCL option for raw socket
#endif // if/else WIN32
    state = IDLE;
#ifdef NETSEC
    if (net_security_setrequest(handle, 0, netsec_request, netsec_requestlen))
    {
        PLOG(PL_ERROR, "ProtoSocket::Open() net_security_setrequest() error: %s\n", 
                GetErrorString());
        Close();
        return false;
    }
#endif // NETSEC

#ifdef UNIX
    // Don't pass descriptor to child processes
    if(-1 == fcntl(handle, F_SETFD, FD_CLOEXEC))
        PLOG(PL_ERROR, "ProtoSocket::Open() fcntl(FD_CLOEXEC) warning: %s\n", GetErrorString());
    // Make the socket non-blocking
    if (notifier)
    {
        if(-1 == fcntl(handle, F_SETFL, fcntl(handle, F_GETFL, 0) | O_NONBLOCK))
        {
            PLOG(PL_ERROR, "ProtoSocket::Open() fcntl(F_SETFL(O_NONBLOCK)) error: %s\n",
                    GetErrorString());
            Close();
            return false;
        }
    }
#endif // UNIX
    if (bindOnOpen)
    {
        if (!Bind(thePort))
		{
			Close();
			return false;
		}
    }
    else
    {
        port = -1;
		// TBD - the UpdateNotification() call here may be unnecessary???
		//       (newly opened, unbound socket needs no notification?)
		if (!UpdateNotification())
		{
			PLOG(PL_ERROR, "ProtoSocket::Open() error installing async notification\n");
			Close();
			return false;
		}
    } 
    // Do the following in case TOS or "ecn_capable" was set _before_ 
    // ProtoSocket::Open() was called.  Note that the "IPv6" flow label
    // "traffic class" is also updated as needed for IPv6 sockets
    if ((0 != tos) || (ecn_capable)) SetTOS(tos);
#ifdef WIN32
    closing = false;
#endif //WIN32
    ip_recvdstaddr = false;  // make sure this is reset
    return true;
}  // end ProtoSocket::Open()

bool ProtoSocket::SetRawProtocol(Protocol theProtocol)
{
    bool wasOpen = false;
    UINT16 portSave = 0;
    if (IsOpen())
    {
        portSave = GetPort();
        Close();
        wasOpen = true;
    }
    protocol = RAW;
    raw_protocol = theProtocol;
    if (wasOpen)
        return Open(portSave);
    else
        return true;
}  // end ProtoSocket::SetRawProtocol()

bool ProtoSocket::UpdateNotification()
{    
	if (NULL != notifier)
    {
        if (IsOpen() && !SetBlocking(false))
        {
            PLOG(PL_ERROR, "ProtoSocket::UpdateNotification() SetBlocking() error\n");
            return false;   
        }
        int notifyFlags = NOTIFY_NONE;
        if (NULL != listener)
        {
            switch (protocol)
            {
                case UDP:
                case RAW:
                    switch (state)
                    {
                        case CLOSED:
                            break;
                        default:
                            if (notify_input && IsBound())
                                notifyFlags = NOTIFY_INPUT;
                            else
                                notifyFlags = NOTIFY_NONE;
                            if (notify_output) 
                                notifyFlags |= NOTIFY_OUTPUT;
                            if (IsOpen() && notify_exception)
                                notifyFlags |= NOTIFY_EXCEPTION;
                        break;
                    }
                  break;
                  
                case TCP:
                    switch(state)
                    {
                        case CLOSED:
                        case IDLE:
                            break;
                        case CONNECTING:
                            notifyFlags = NOTIFY_OUTPUT;
                            break;
                        case LISTENING:
                            notifyFlags = NOTIFY_INPUT;
                            break;
                        case CONNECTED:
			  	            if (notify_input)
                                notifyFlags = NOTIFY_INPUT;
                            if (notify_output) 
                                notifyFlags |= NOTIFY_OUTPUT;
                            break;  
                    }  // end switch(state)
                    break; 
                case ZMQ:
                    switch (state)
                    {
                        case CONNECTED:
                            if (notify_input)
                                notifyFlags = NOTIFY_INPUT;
                            break;
                        default:
                            break;        
                    }
                    break;
	            default:
                    PLOG(PL_ERROR,"ProtoSocket::UpdateNotification Error: Unsupported protocol: %d.\n", protocol);
	                break;
            }  // end switch(protocol)
        }  // end if(listener)
        return notifier->UpdateSocketNotification(*this, notifyFlags);
    }  
    else
    {
        return true;   
    }
}  // end ProtoSocket::UpdateNotification()

void ProtoSocket::OnNotify(NotifyFlag theFlag)
{
    ProtoSocket::Event event = INVALID_EVENT;
    if (NOTIFY_INPUT == theFlag)
    {
        switch (state)
        {
            case CLOSED:
                break;
            case IDLE:
                event = RECV;
                break;
            case CONNECTING:
                break;
            case LISTENING:
                // (TBD) check for error
                event = ACCEPT;
                break; 
            case CONNECTED:
                event = RECV;
                break;
        }        
    }
    else if (NOTIFY_OUTPUT == theFlag)
    {
        switch (state)
        {
            case CLOSED:
                break;
            case IDLE:
                event = SEND;
                break;
            case CONNECTING:
            {
#ifdef WIN32
                event = CONNECT;
                state = CONNECTED;
                UpdateNotification();
#else
                int err;
                socklen_t errsize = sizeof(err);
                if (getsockopt(handle, SOL_SOCKET, SO_ERROR, (char*)&err, &errsize))
                {
                    PLOG(PL_ERROR, "ProtoSocket::OnNotify() getsockopt() error: %s\n", GetErrorString());
                    
                } 
                else if (0 != err)
                {
		            PLOG(PL_DEBUG, "ProtoSocket::OnNotify() getsockopt() error: %s\n", GetErrorString()); 
                    Disconnect();
		            event = ERROR_;  // TBD - should this be DISCONNECT instead?
                }
                else
                {
                    event = CONNECT;
                    state = CONNECTED;
                    UpdateNotification();
                }
#endif  // if/else WIN32
                break;
            }
            case LISTENING: 
                break;
            case CONNECTED:
                event = SEND;
                break;
        }    
    }
    else if (NOTIFY_EXCEPTION == theFlag)
    {
        event = EXCEPTION;
    }
    else if (NOTIFY_ERROR == theFlag)
    {
		//TRACE("ProtoSocket NOTIFY_ERROR notification\n");
        switch(state)
    	{
	        case CONNECTING:
	        case CONNECTED:
	            Disconnect();
            default:
                event = ProtoSocket::ERROR_;
	            break;
	    }
    }
    else  // NOTIFY_NONE  (connection was purposefully ended)
    {
        switch(state)
        {
            case CONNECTING:
                //PLOG(PL_ERROR, "ProtoSocket::OnNotify() Connect() error: %s\n", GetErrorString());
            case CONNECTED:
                Disconnect();
                event = DISCONNECT;
                break;
            default:
                break;
        }
    }
    ASSERT(INVALID_EVENT != event);
    if (listener) listener->on_event(*this, event);
}  // end ProtoSocket::OnNotify()

bool ProtoSocket::Bind(UINT16 thePort, const ProtoAddress* localAddress)
{
    if (IsBound()) Close();
    if (IsOpen() && (NULL != localAddress) && (GetAddressType() != localAddress->GetType()))
    {
        Close();  // requires a different address family, so close for reopen
    }
    if (!IsOpen()) 
    {
        ProtoAddress::Type addrType = localAddress ? localAddress->GetType() : ProtoAddress::IPv4;
		if(!Open(thePort, addrType, false))
        {
			PLOG(PL_ERROR,"ProtoSocket::Bind() error opening socket on port %d\n",thePort);
			return false;
		}
	}
#ifdef HAVE_IPV6
    struct sockaddr_storage socketAddr;
    socklen_t addrSize;
    if (IPv6 == domain)
    {
	    addrSize = sizeof(struct sockaddr_in6);
        memset((char*)&socketAddr, 0, sizeof(struct sockaddr_in6));    
        ((struct sockaddr_in6*)&socketAddr)->sin6_family = AF_INET6;
        ((struct sockaddr_in6*)&socketAddr)->sin6_port = htons(thePort);
        ((struct sockaddr_in6*)&socketAddr)->sin6_flowinfo = 0;
        if (NULL != localAddress)
        {
            ((struct sockaddr_in6*)&socketAddr)->sin6_addr = 
                ((const struct sockaddr_in6*)(&localAddress->GetSockAddrStorage()))->sin6_addr;
        }
        else
        {
            ((struct sockaddr_in6*)&socketAddr)->sin6_addr = in6addr_any;
        }
    }
    else
    {
        addrSize = sizeof(struct sockaddr_in);
        memset((char*)&socketAddr, 0, sizeof(struct sockaddr_in));    
        ((struct sockaddr_in*)&socketAddr)->sin_family = AF_INET;
        ((struct sockaddr_in*)&socketAddr)->sin_port = htons(thePort);
        if (NULL != localAddress)
        {
            ((struct sockaddr_in*)&socketAddr)->sin_addr = 
                ((const struct sockaddr_in*)(&localAddress->GetSockAddrStorage()))->sin_addr;
        }
	    else
        {
            struct in_addr inAddr;
            inAddr.s_addr = htonl(INADDR_ANY);
            ((struct sockaddr_in*)&socketAddr)->sin_addr = inAddr;
        }
    }
#else
    struct sockaddr socketAddr;
    socklen_t addrSize = sizeof(struct sockaddr_in);
    memset((char*)&socketAddr, 0, sizeof(struct sockaddr_in));    
    ((struct sockaddr_in*)&socketAddr)->sin_family = AF_INET;
    ((struct sockaddr_in*)&socketAddr)->sin_port = htons(thePort);
    if (NULL != localAddress)
    {
        ((struct sockaddr_in*)&socketAddr)->sin_addr = 
            ((struct sockaddr_in*)(&localAddress->GetSockAddr()))->sin_addr;
    }
	else
    {
        struct in_addr inAddr;
        inAddr.s_addr = htonl(INADDR_ANY);
        ((struct sockaddr_in*)&socketAddr)->sin_addr = inAddr;
    }
#endif  //  if/else HAVE_IPV6
    
#ifdef UNIX
#ifdef HAVE_IPV6
    if ((IPv6 == domain) && (0 != flow_label))
        ((struct sockaddr_in6*)&socketAddr)->sin6_flowinfo = flow_label;
#endif // HAVE_IPV6
#endif // UNIX

#ifdef HAVE_IPV6
#ifdef WIN32
	OSVERSIONINFO osvi;
	BOOL osVistaOrLater;
	ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	GetVersionEx(&osvi);
	osVistaOrLater = osvi.dwMajorVersion > 5;
	if (osVistaOrLater)
	{
		// On Windows Vista & above dual stack sockets are supported so
		// disable ipv6_v6only so we can listen to both ipv4 & ipv6 connections
		// simultaneously
		int ipv6only = 0;
		if (setsockopt(handle, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&ipv6only, sizeof(ipv6only)) < 0)
		{
			PLOG(PL_ERROR, "ProtoSocket::Bind() setsockopt(!IPV6_V6ONLY) error: %s\n", GetErrorString());
			return false;
		}
	}
#endif  // WIN32
#endif // HAVE_IPV6
    // Bind the socket to the given port     
    if (bind(handle, (struct sockaddr*)&socketAddr, addrSize) < 0)
    {
       PLOG(PL_ERROR, "ProtoSocket::Bind(%hu) bind() error: %s\n", thePort, GetErrorString());
       return false;
    }

    // Get socket name so we know our port number  
    socklen_t sockLen = addrSize;
    if (getsockname(handle, (struct sockaddr*)&socketAddr, &sockLen) < 0) 
    {    
        PLOG(PL_ERROR, "ProtoSocket::Bind() getsockname() error: %s\n", GetErrorString());
        return false;
    }
	source_addr.SetSockAddr((struct sockaddr&)socketAddr);
    switch(((struct sockaddr*)&socketAddr)->sa_family)
    {
        case AF_INET:    
            source_addr.SetSockAddr((struct sockaddr&)socketAddr);
            port = ntohs(((struct sockaddr_in*)&socketAddr)->sin_port);
            break;
#ifdef HAVE_IPV6        
        case AF_INET6:
            source_addr.SetSockAddr((struct sockaddr&)socketAddr);
            port = ntohs(((struct sockaddr_in6*)&socketAddr)->sin6_port);
            break;
#endif // HAVE_IPV6        
        default:
            PLOG(PL_ERROR, "ProtoSocket::Bind() error: getsockname() returned unknown address type\n");
            return false;
    }
#ifdef WIN32
	// reset input/output readiness since it is a newly bound socket
	input_ready = false;
	output_ready = true;
#endif  // WIN32
    return UpdateNotification();
}  // end ProtoSocket::Bind()

bool ProtoSocket::Shutdown()
{
#ifdef WIN32 
    if (TCP == protocol)
#else
    if (IsConnected() && TCP == protocol)
#endif // WIN32
    {
        bool notifyOutput = notify_output;
        if (notifyOutput)
        {
            notify_output = false;
            UpdateNotification();
        }
#ifdef WIN32
        if (SOCKET_ERROR == shutdown(handle, SD_SEND))
#else
        if (0 != shutdown(handle, SHUT_WR))
#endif // if/else WIN32/UNIX
        {
            // TBD - should we not bother to re-enable output notification here?
            //  (i.e. since the user intended to shutdown the socket?!)
            if (notifyOutput)
            {
                notify_output = true;
                UpdateNotification();
            }
            PLOG(PL_ERROR, "ProtoSocket::Shutdown() error: %s\n", GetErrorString());
            return false;
        }
        else
        {
            return true;
        }
    }
    else
    {
        PLOG(PL_ERROR, "ProtoSocket::Shutdown() error: socket not connected\n");
        return false;
    }
}  // end ProtoSocket::Shutdown()

void ProtoSocket::Close()
{
    if (IsOpen()) 
    {
        if (IsConnected()) Disconnect();
        state = CLOSED;
        UpdateNotification();   
#ifdef WIN32
        if (NULL != input_event_handle)
        {
            WSACloseEvent(input_event_handle);
            input_event_handle = NULL;
        }
#endif // if WIN32
        if (INVALID_HANDLE != handle)
        {
#ifdef WIN32
            if (SOCKET_ERROR == closesocket(handle))
                PLOG(PL_WARN, "ProtoSocket::Close() warning: closesocket() error: %s\n", GetErrorString());
	        ProtoAddress::Win32Cleanup();
            input_ready = output_ready = false;  
#else
            close(handle);
#endif // if/else WIN32/UNIX
	        handle = INVALID_HANDLE;
        }
        port = -1;
    }
}  // end Close() 

bool ProtoSocket::Connect(const ProtoAddress& theAddress)
{
    if (IsConnected()) Disconnect();
    if (!IsOpen() && !Open(0, theAddress.GetType()))
    {
        PLOG(PL_ERROR, "ProtoSocket::Connect() error opening socket!\n");
        return false;
    }
#ifdef HAVE_IPV6
    socklen_t addrSize = (IPv6 == domain) ? sizeof(sockaddr_storage) : 
                                            sizeof(struct sockaddr_in);
#else
    socklen_t addrSize = sizeof(struct sockaddr_in);
#endif // if/else HAVE_IPV6
#ifdef WIN32
    //int result = WSAConnect(handle, &theAddress.GetSockAddr(), addrSize,
    //                      NULL, NULL, NULL, NULL);
	int result = connect(handle, &theAddress.GetSockAddr(), addrSize);
    if (SOCKET_ERROR == result)
    {
	if (WSAEWOULDBLOCK != WSAGetLastError())
        {
            PLOG(PL_ERROR, "ProtoSocket::Connect() WSAConnect() error: (%s)\n", GetErrorString());
            return false;
        } 
        output_ready = false;  // not yet connected
        state = CONNECTING;
    }
#else  // UNIX
#ifdef HAVE_IPV6
    if (flow_label && (ProtoAddress::IPv6 == theAddress.GetType()))
        ((struct sockaddr_in6*)(&theAddress.GetSockAddrStorage()))->sin6_flowinfo = flow_label;
#endif // HAVE_IPV6
    int result = connect(handle, &theAddress.GetSockAddr(), addrSize);
    if (0 != result)
    {
        if (EINPROGRESS != errno)
        {
            PLOG(PL_ERROR, "ProtoSocket::Connect() connect() error: %s\n", GetErrorString());
            return false;
        }
        state = CONNECTING;
    }
#endif // if/else WIN32/UNIX
    else
    {
        state = CONNECTED;
    }
    if (!UpdateNotification())
    {
        PLOG(PL_ERROR, "ProtoSocket::Connect() error updating notification\n");
        state = IDLE;
        UpdateNotification();
        return false;
    }
    // Use getsockname() to get local "port" and "source_addr"
#ifdef HAVE_IPV6
	struct sockaddr_in6 socketAddr;
#else
    struct sockaddr socketAddr;
#endif // if/else HAVE_IPV6
    socklen_t addrLen = sizeof(socketAddr);
    if (getsockname(handle, (struct sockaddr*)&socketAddr, &addrLen) < 0) 
    {  
        // getsockname() failed, so issue a warning
        PLOG(PL_ERROR, "ProtoSocket::Connect() getsockname() error: %s\n", GetErrorString());
        source_addr.Invalidate();
    }
    else
    {
        switch(((struct sockaddr*)&socketAddr)->sa_family)
        {
	        case AF_INET:  
                source_addr.SetSockAddr((struct sockaddr&)socketAddr);  
	            port = ntohs(((struct sockaddr_in*)&socketAddr)->sin_port);
	            break;
#ifdef HAVE_IPV6	    
	        case AF_INET6:
                source_addr.SetSockAddr((struct sockaddr&)socketAddr); 
	            port = ntohs(((struct sockaddr_in6*)&socketAddr)->sin6_port);
	            break;
#endif // HAVE_IPV6	   
#ifndef WIN32
            case AF_UNIX:
                source_addr.Invalidate();
                port = -1;
                break;
#endif // !WIN32 
	        default:
	            PLOG(PL_ERROR, "ProtoSocket::Connect() error: getsockname() returned unknown address type");
                break;
        }  // end switch()
    }
    destination = theAddress;  // cache the destination address
    return true;
}  // end bool ProtoSocket::Connect()

void ProtoSocket::Disconnect()
{
    if (IsConnected() || IsConnecting())
    {
		state = IDLE;
        UpdateNotification();
        //source_addr.Invalidate();
        //destination.Invalidate();
        struct sockaddr nullAddr;
        memset(&nullAddr, 0 , sizeof(struct sockaddr));
#ifdef UNIX
        if (TCP != protocol)
        {
            nullAddr.sa_family = AF_UNSPEC;
            if (connect(handle, &nullAddr, sizeof(struct sockaddr)))
            {
                if (EAFNOSUPPORT != errno)
                    PLOG(PL_WARN, "ProtoSocket::Disconnect() connect() error: %s)\n", GetErrorString());
                // (TBD) should we Close() and re-Open() the socket here?
            }
        }
        else
        {
            // TCP doesn't like the connect(nullAddr) trick, best to just close
            // (TBD) should we Close() and re-Open() the socket here?
            // (but can't easily recall all socket options, so best not I guess)
            //UINT16 savePort = GetPort();
	  
	        // MACOSX & LINUX trigger server resets differently...
#ifdef MACOSX
            Close();
#else
	        nullAddr.sa_family = AF_UNSPEC;
	        if (connect(handle,&nullAddr,sizeof(struct sockaddr)))
	        {
		        if (EAFNOSUPPORT != errno)
		            PLOG(PL_WARN, "ProtoSocket::Disconnect() connect() error (%s)\n", GetErrorString());
				Close();
	        }
#endif
            //Open(savePort);
        }
#else
        if (SOCKET_ERROR == WSAConnect(handle, &nullAddr, sizeof(struct sockaddr),
                                       NULL, NULL, NULL, NULL))
        {
            //PLOG(PL_WARN, "ProtoSocket::Disconnect() WSAConnect() error: %s\n", GetErrorString());
			Close();  // if windows doesn't like the null-connect disconnect trick either
        }
#endif  // WIN32
    }
}  // end ProtoSocket::Disconnect()

bool ProtoSocket::Listen(UINT16 thePort)
{
    if (IsBound())
    {
        if ((0 != thePort) && (thePort != port))
        {
            PLOG(PL_ERROR, "ProtoSocket::Listen() error: socket bound to different port.\n");
            return false;
        }
    }
    else
    {
        if (!Bind(thePort))
        {
            PLOG(PL_ERROR, "ProtoSocket::Listen() error binding socket.\n");
            return false; 
        } 
    } 
    if (TCP == protocol)
		state = LISTENING;
	else
		return true; // UDP sockets don't "listen"
    if (!UpdateNotification())
    {
        state = IDLE;
        PLOG(PL_ERROR, "ProtoSocket::Listen() error updating notification\n");
        return false;
    }
#ifdef WIN32
    if (SOCKET_ERROR == listen(handle, 5))
#else
    if (listen(handle, 5) < 0)
#endif // if/else WIN32/UNIX
    {
        PLOG(PL_ERROR, "ProtoSocket: listen() error: %s\n", GetErrorString());
        return false;
    }
    return true;
}  // end ProtoSocket::Listen()

bool ProtoSocket::Accept(ProtoSocket* newSocket)
{
	if (TCP != protocol)
	{
		PLOG(PL_ERROR, "ProtoSocket::Accept() error non-TCP socket!\n");
		return false;
	}
    ProtoSocket& theSocket = (NULL != newSocket) ? *newSocket : *this;
    // Clone server socket
    if (this != &theSocket) 
    {
        // TBD - should override ProtoSocket copy operator to delete old listener???
        if (NULL != theSocket.listener) delete theSocket.listener;
        theSocket = *this;
        theSocket.listener = NULL; // this->listener is duplicated later (or should we save our old one?) 
    }
#ifdef HAVE_IPV6
	struct sockaddr_in6 socketAddr;
#else
    struct sockaddr socketAddr;
#endif // if/else HAVE_IPV6
    socklen_t addrLen = sizeof(socketAddr);
#ifdef WIN32
    if (this != &theSocket)
    {
        if (!ProtoAddress::Win32Startup())
        {
            PLOG(PL_ERROR, "ProtoSocket::Accept() WSAStartup() error: %s\n", GetErrorString());
            return false;
        }
    }
    Handle theHandle = WSAAccept(handle, (struct sockaddr*)&socketAddr, &addrLen, NULL, NULL);
#else
    Handle theHandle = accept(handle, (struct sockaddr*)&socketAddr, &addrLen);
#endif // if/else WIN32/UNIX
    if (INVALID_HANDLE == theHandle)
    {
#ifdef WIN32
        switch (WSAGetLastError())
        {
            case WSAEWOULDBLOCK:
                if (input_ready)
                {
                    input_ready = false; 
                    UpdateNotification();
                }
                break;
            default:
                PLOG(PL_ERROR, "ProtoSocket::Accept() accept() error: %s\n", GetErrorString());
                break;
        }
#endif
        PLOG(PL_ERROR, "ProtoSocket::Accept() accept() error: %s\n", GetErrorString());
        if (this != &theSocket)
        {
#ifdef WIN32
            ProtoAddress::Win32Cleanup();
#endif // WIN32
            theSocket.handle = INVALID_HANDLE;
            theSocket.state = CLOSED;
        }
        return false;
    }
    // Don't think we need make "input_ready" true on accept?
    if (LOCAL != domain)
        theSocket.destination.SetSockAddr((struct sockaddr&)socketAddr);
    // Get the socket name so we know our port number
    addrLen = sizeof(socketAddr);
    if (getsockname(theHandle, (struct sockaddr*)&socketAddr, &addrLen) < 0) 
    {    
        PLOG(PL_ERROR, "ProtoSocket::Accept() getsockname() error: %s\n", GetErrorString());
        if (this != &theSocket)
        {
#ifdef WIN32
            closesocket(theHandle);
			ProtoAddress::Win32Cleanup();
#endif // WIN32
            theSocket.handle = INVALID_HANDLE;
            theSocket.state = CLOSED;
        }
	    return false;
    }
    switch(((struct sockaddr*)&socketAddr)->sa_family)
    {
	    case AF_INET:  
            theSocket.source_addr.SetSockAddr((struct sockaddr&)socketAddr);
	        theSocket.port = ntohs(((struct sockaddr_in*)&socketAddr)->sin_port);
	        break;
#ifdef HAVE_IPV6	    
	    case AF_INET6:
            theSocket.source_addr.SetSockAddr((struct sockaddr&)socketAddr);
	        theSocket.port = ntohs(((struct sockaddr_in6*)&socketAddr)->sin6_port);
	        break;
#endif // HAVE_IPV6	   
#ifndef WIN32
        case AF_UNIX:
            theSocket.source_addr.Invalidate();
            theSocket.port = -1;
            break;
#endif // !WIN32 
	    default:
	        PLOG(PL_ERROR, "ProtoSocket::Accept() error: getsockname() returned unknown address type");
            if (this != &theSocket)
            {
 #ifdef WIN32
                closesocket(theHandle);
				ProtoAddress::Win32Cleanup();
#endif // WIN32
                theSocket.handle = INVALID_HANDLE;
                theSocket.state = CLOSED;
            }
	        return false;
    }  // end switch()
    if (this == &theSocket)
    {  
        state = CLOSED;
        UpdateNotification();
#ifdef WIN32
        closesocket(theSocket.handle);
		input_ready = false;  // will be notified when there's something to read
		output_ready = true;  // assume new socket ready for writing
#else
        close(theSocket.handle);
#endif // if/else WIN32/UNIX
    }
    else
    {   
#ifdef WIN32
		// Need a new event handle for this new, unopened socket
        if (NULL == (theSocket.input_event_handle = WSACreateEvent()))
        {
            PLOG(PL_ERROR, "ProtoSocket::Accept() WSACreateEvent error: %s\n", GetErrorString());
            theSocket.Close();
            return false;
        }
		theSocket.input_ready = false; // will be notified when there's something to read
		theSocket.output_ready = true; // assume new socket ready for writing
#endif // WIN32
        // TBD - keep old listener / notifier and just do an UpdateNotification() here
        if (NULL != listener)
        {
            if (NULL == (theSocket.listener = listener->duplicate()))
            {
                PLOG(PL_ERROR, "ProtoSocket::Accept() listener duplication error: %s\n", ::GetErrorString());
                theSocket.Close();
                return false;
            }   
        }
        if (NULL != notifier)
        {
            theSocket.handle = theHandle;
            if(!theSocket.SetBlocking(false))
            {
                PLOG(PL_ERROR, "ProtoSocket::Accept() SetBlocking(false) error\n");
                theSocket.Close();
                return false;
	        }
        }
    }  // end if/else (this == &theSocket)
    theSocket.handle = theHandle;  // the socket gets the new handle/descriptor from accept()
    theSocket.state = CONNECTED;
    theSocket.UpdateNotification();
    return true;
}  // end ProtoSocket::Accept()

bool ProtoSocket::Send(const char*         buffer, 
                       unsigned int&       numBytes)
{
    //TRACE("ProtoSocket::Send() ...\n");
    if (IsConnected())
    {
#ifdef WIN32
        WSABUF sendBuf;
        sendBuf.buf = (char*)buffer;
        sendBuf.len = numBytes;
	    DWORD bytesSent;
        if (SOCKET_ERROR == WSASend(handle, &sendBuf, 1, &bytesSent, 0, NULL, NULL))
        {
            numBytes = 0; 
            switch (WSAGetLastError())
            {
                case WSAEINTR:
                    return true;
                case WSAEWOULDBLOCK:
                    if (output_ready)
                    {
						output_ready = false;  
                        UpdateNotification();  // because no longer "output ready"
                    }
                    return true;
                case WSAENETRESET:
                case WSAECONNABORTED:
                case WSAECONNRESET:
                case WSAESHUTDOWN:
                case WSAENOTCONN:
                    if (output_ready)
                    {
                        output_ready = false;
                        UpdateNotification();  // because no longer "output ready"
                    }
                    OnNotify(NOTIFY_ERROR);
                    break;
                default:
                    PLOG(PL_ERROR, "ProtoSocket::Send() WSASend() error: %s\n", GetErrorString());
                    break;
            }
            return false;
        }
        else
        {
            if (bytesSent < numBytes)
			{
                if (output_ready)
                {
                    output_ready = false;
				    UpdateNotification();  // because no longer "output ready"
                }
			}
            else if (!output_ready)
            {
				output_ready = true;
                UpdateNotification();
            }
            numBytes = (unsigned int)bytesSent;
            return true;
        }
#else
        ssize_t result = send(handle, buffer, (size_t)numBytes, 0);
        if (result < 0)
	    {
            numBytes = 0;
	        switch (errno)
            {
                case EINTR:
                case EAGAIN:
                    return true;
                case ENETRESET:
                case ECONNABORTED:
                case ECONNRESET:
                case ESHUTDOWN:
                case ENOTCONN:
                case EPIPE:
                    OnNotify(NOTIFY_ERROR);
                    break;
                case ENOBUFS:
                    PLOG(PL_DEBUG, "ProtoSocket::Send() send() error: %s\n", GetErrorString());
                    return false;
                default:
                    PLOG(PL_ERROR, "ProtoSocket::Send() send() error: %s\n", GetErrorString());
                    break;
            }
            return false;  
        }
        else
        {
            numBytes = (unsigned int)result;
            return true;
        }
#endif // if/else WIN32/UNIX
    }
    else
    {
        PLOG(PL_ERROR, "ProtoSocket::Send() error unconnected socket\n");
        numBytes = 0;
        return false;   
    }
}  // end ProtoSocket::Send()

bool ProtoSocket::Recv(char*            buffer, 
                       unsigned int&    numBytes)
{
#ifdef WIN32
    WSABUF recvBuf;
    recvBuf.buf = buffer;
    recvBuf.len = numBytes;
    DWORD bytesReceived;
    DWORD flags = 0;
    if (SOCKET_ERROR == WSARecv(handle, &recvBuf, 1, &bytesReceived, &flags, NULL, NULL))
    {
        numBytes = 0;
        switch (WSAGetLastError())
        {
            case WSAEINTR:
            case WSAEWOULDBLOCK:
                if (input_ready)
                {
                    input_ready = false;
                    UpdateNotification();  // because no longer "input ready"
                }
                return true; // not really an error, just no bytes read
                break;
            case WSAENETRESET:
            case WSAECONNABORTED:
            case WSAECONNRESET:
            case WSAESHUTDOWN:
            case WSAENOTCONN:
                PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
                OnNotify(NOTIFY_ERROR);
                break;
            default:
                PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
                break;
        }
        return false;
    }
    else
    {
        if ((bytesReceived < numBytes) && (TCP == protocol))
	  {
            input_ready = false;  
	    UpdateNotification();  // because no longer "input ready"
	  }
        else if (!input_ready)
        {
	  input_ready = true;
	  UpdateNotification();
        }
        numBytes = bytesReceived;
        // TBD - Should we do a NOTIFY_NONE here like we do for UNIX?
        return true;
    }
#else
    ssize_t result = recv(handle, buffer, numBytes, 0);
    if (result < 0)
    {
        numBytes = 0;
        switch (errno)
        {
            case EINTR:
            case EAGAIN:
                PLOG(PL_WARN, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());   
                return true;            
                break;
            case ENETRESET:
            case ECONNABORTED:
            case ECONNRESET:
            case ESHUTDOWN:
            case ENOTCONN:
                OnNotify(NOTIFY_ERROR);
                break;
            default:
                PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
                break;
        }
        return false;
    }
    else
    {
        numBytes = (unsigned int)result;
        if (0 == result) OnNotify(NOTIFY_NONE);
        return true;
    }
#endif // if/else WIN32/UNIX
}  // end ProtoSocket::Recv()

// Note the function prototype and behavior here is changing slightly
// from the prior / original ProtoSocket::SendTo() behavior such that
// the EWOULDBLOCK condition no longer returns "false" but instead returns
// "true", but with setting the referenced "buflen" value to zero.
// This lets us differentiate this condition, mainly as a cue for when
// (and when not to) enable socket output notification for async i/o mgmnt.s
bool ProtoSocket::SendTo(const char*         buffer, 
                         unsigned int&       buflen,
                         const ProtoAddress& dstAddr)
{
    if (!IsOpen())
    {
        if (!Open(0, dstAddr.GetType()))
        {
            PLOG(PL_ERROR, "ProtoSocket::SendTo() error: socket not open\n");
            return false;
        }
    }
    if (IsConnected())
    {
        unsigned int numBytes = buflen;
        if (!Send(buffer, numBytes))
        {

	        PLOG(PL_DEBUG, "ProtoSocket::SendTo() error: Send() error\n");
            buflen = 0;
            return false;
        }
        if (numBytes != buflen)
        {
            PLOG(PL_DEBUG, "ProtoSocket::SendTo() error: Send() incomplete\n");
            buflen = 0;
            return true;
        }
        else
        {
            return true;
        }
    }
	else
	{
		socklen_t addrSize;
#ifdef HAVE_IPV6
		if (flow_label && (ProtoAddress::IPv6 == dstAddr.GetType()))
			((struct sockaddr_in6*)(&dstAddr.GetSockAddrStorage()))->sin6_flowinfo = flow_label;
		if (ProtoAddress::IPv6 == dstAddr.GetType())
			addrSize = sizeof(struct sockaddr_in6);
		else
#endif //HAVE_IPV6
			addrSize = sizeof(struct sockaddr_in);
#ifdef WIN32
        WSABUF wsaBuf;
        wsaBuf.len = buflen;  
        wsaBuf.buf = (char*)buffer;
        DWORD numBytes; 
        if (SOCKET_ERROR == WSASendTo(handle, &wsaBuf, 1, &numBytes, 0, 
                                      &dstAddr.GetSockAddr(), addrSize, NULL, NULL))
        {
            buflen = 0;
            switch (WSAGetLastError())
            {
                case WSAEINTR:
                  return true;
                case WSAEWOULDBLOCK:
                  output_ready = false;
                  return true;
                default:
                  break;
            }
            PLOG(PL_ERROR, "ProtoSocket::SendTo() WSASendTo() error: %s\n", GetErrorString());
            return false;
        }
        else
        {
            //ASSERT(numBytes == buflen);
            return true;
        }
#else
        ssize_t result = sendto(handle, buffer, (size_t)buflen, 0, &dstAddr.GetSockAddr(), addrSize);	
        if (result < 0)
        {
            buflen = 0;
            switch (errno)
            {
                case EINTR:
                case EAGAIN:
                    return true;
                case ENOBUFS:
                    PLOG(PL_DEBUG, "ProtoSocket::SendTo() sendto() error: %s\n", GetErrorString());
                    return false;
                default:
                    break;
            }
	        PLOG(PL_ERROR, "ProtoSocket::SendTo() sendto() error: %s\n", GetErrorString());
            return false;
        }
        else
        {   
            //ASSERT(result == buflen);
            return true;
        }
#endif // if/else WIN32/UNIX
	}
}  // end ProtoSocket::SendTo()

bool ProtoSocket::RecvFrom(char*            buffer, 
                           unsigned int&    numBytes, 
                           ProtoAddress&    sourceAddr)
{
	if (!IsBound())
    {
        PLOG(PL_ERROR, "ProtoSocket::RecvFrom() error: socket not bound\n");
        numBytes = 0;    
    }
#ifdef HAVE_IPV6    
    struct sockaddr_storage sockAddr;
#else
    struct sockaddr sockAddr;
#endif  // if/else HAVE_IPV6
    socklen_t addrLen = sizeof(sockAddr);
    // Just do a regular recvfrom()  (TBD - for Win32, should we be using WSARecvFrom()???)
    ssize_t result = recvfrom(handle, buffer, (size_t)numBytes, 0, (struct sockaddr*)&sockAddr, &addrLen);
    if (result < 0)
    {
        numBytes = 0;
#ifdef WIN32
        switch (WSAGetLastError())
        {
            case WSAEINTR:
            case WSAEWOULDBLOCK:
                if (input_ready)
                {
                    input_ready = false;   
				    UpdateNotification(); // because no longer "input ready"
                }
                return true;
                break;
            default:
                PLOG(PL_ERROR, "ProtoSocket::RecvFrom() recvfrom() error: %s\n", GetErrorString());
                break;
        }
#else
        switch (errno)
        {
            case EINTR:
            case EAGAIN:
                //PLOG(PL_WARN, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());   
                return true;            
                break;
            default:
                PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
                break;
        }
#endif // UNIX
        return false;
    }
    else
    {
#ifdef WIN32
        if (!input_ready)
        {
            input_ready = true;
            UpdateNotification();
        }
#endif  // WIN32
        numBytes = (unsigned int)result;
        sourceAddr.SetSockAddr(*((struct sockaddr*)&sockAddr));
        if (!sourceAddr.IsValid())
        {
            PLOG(PL_ERROR, "ProtoSocket::RecvFrom() Unsupported address type!\n");
            return false;
        }
        return true;
    }
}  // end ProtoSocket::RecvFrom()

void ProtoSocket::EnableRecvDstAddr()
{
    if (!ip_recvdstaddr)
    {
        int enable = 1; 
#ifdef IP_RECVDSTADDR
        if (setsockopt(handle, IPPROTO_IP, IP_RECVDSTADDR, (char*)&enable, sizeof(enable)) < 0)
            PLOG(PL_WARN, "ProtoSocket::EnableRecvDstAddr() setsocktopt(IP_RECVDSTADDR) error: %s\n", GetErrorString());
#else
        if (setsockopt(handle, IPPROTO_IP, IP_PKTINFO, (char*)&enable, sizeof(enable)) < 0)
            PLOG(PL_WARN, "ProtoSocket::EnableRecvDstAddr() setsocktopt(IP_PKTINFO) error: %s\n", GetErrorString());
#endif // if/else IP_RECVDSTADDR        
#ifdef HAVE_IPV6
#ifdef IPV6_RECVDSTADDR
        if (setsockopt(handle, IPPROTO_IPV6, IPV6_RECVDSTADDR, (char*)&enable, sizeof(enable)) < 0)
            PLOG(PL_WARN, "ProtoSocket::EnableRecvDstAddr() setsocktopt(IPV6_RECVDSTADDR) error: %s\n", GetErrorString());
#else
        if (setsockopt(handle, IPPROTO_IPV6, IPV6_RECVPKTINFO, (char*)&enable, sizeof(enable)) < 0)
            PLOG(PL_WARN, "ProtoSocket::EnableRecvDstAddr() setsocktopt(IPV6_PKTINFO) error: %s\n", GetErrorString());
#endif // if/else IPV6_RECVDSTADDR
#endif // HAVE_IPV6
        ip_recvdstaddr = true;
    }
#ifdef WIN32
    // On Windows, you have to "load" the WsaRecvMsg() function pointer
    if (NULL == WSARecvMsg)
    {
        // On first call, we need to fetch the WSARecvMsg() function pointer
        GUID WSARecvMsg_GUID = WSAID_WSARECVMSG;
        DWORD NumberOfBytes;
        if (SOCKET_ERROR == WSAIoctl(handle, SIO_GET_EXTENSION_FUNCTION_POINTER, 
                                     &WSARecvMsg_GUID, sizeof(WSARecvMsg_GUID),
                                     &WSARecvMsg, sizeof WSARecvMsg,
                                     &NumberOfBytes, NULL, NULL))
        {
            PLOG(PL_ERROR, "ProtoSocket::EnableRecvDstAddr() error: WSARecvMsg() not supported on this platform!\n");
            WSARecvMsg = NULL;
	    }
    }
#endif // WIN32
}  // end ProtoSocket::EnableRecvDstAddr()

#ifndef WIN32
// Variant RecvFrom() that uses recvmsg() to get destAddr information
bool ProtoSocket::RecvFrom(char*            buffer, 
                           unsigned int&    numBytes, 
                           ProtoAddress&    sourceAddr,
                           ProtoAddress&    destAddr)
{
    if (!IsBound())
    {
        PLOG(PL_ERROR, "ProtoSocket::RecvFrom() error: socket not bound\n");
        numBytes = 0;    
    }
    if (!ip_recvdstaddr) EnableRecvDstAddr();  // should enable ahead of time to make sure you don't miss any
    
#ifdef HAVE_IPV6    
    struct sockaddr_storage sockAddr;
#else
    struct sockaddr sockAddr;
#endif  // if/else HAVE_IPV6
    socklen_t addrLen = sizeof(sockAddr);
    
    char cdata[64];
    struct msghdr msg;  // TBD - should we bzero() our "cdata" and "msg" here???
    struct iovec iov[1];
    iov[0].iov_base = buffer;
    iov[0].iov_len = numBytes;
    msg.msg_name = &sockAddr;
    msg.msg_namelen = addrLen;
    msg.msg_iov = iov;
    msg.msg_iovlen = 1;
    msg.msg_control = cdata;
    msg.msg_controllen = 64;//sizeof(cdata);
    msg.msg_flags = 0;
    destAddr.Invalidate();
    ssize_t result = recvmsg(handle, &msg, 0);
    if (result < 0)
    {
        numBytes = 0;
#ifdef WIN32
        switch (WSAGetLastError())
        {
            case WSAEINTR:
            case WSAEWOULDBLOCK:
				//PLOG(PL_WARN, "ProtoSocket::RecvFrom() recvmsg() error: %s\n", GetErrorString());
				input_ready = false;  
                return true;
                break;
            default:
                PLOG(PL_ERROR, "ProtoSocket::RecvFrom() recvmsg() error: %s\n", GetErrorString());
                break;
        }
#else
        switch (errno)
        {
            case EINTR:
            case EAGAIN:
                //PLOG(PL_WARN, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());   
                return true;            
                break;
            default:
                PLOG(PL_ERROR, "ProtoSocket::Recv() recv() error: %s\n", GetErrorString());
                break;
        }
#endif // UNIX
        return false;
    }
    else
    {
        numBytes = (unsigned int)result;
        sourceAddr.SetSockAddr(*((struct sockaddr*)&sockAddr));
        if (!sourceAddr.IsValid())
        {
            PLOG(PL_ERROR, "ProtoSocket::RecvFrom() Unsupported address type!\n");
            return false;
        }
        // Get destAddr info
        for (struct cmsghdr* cmptr = CMSG_FIRSTHDR(&msg); cmptr != NULL; cmptr = CMSG_NXTHDR(&msg, cmptr)) 
        {
            if (cmptr->cmsg_level == IPPROTO_IP)
            {
#ifdef IP_RECVDSTADDR
                if ((cmptr->cmsg_level == IPPROTO_IP) && (cmptr->cmsg_type == IP_RECVDSTADDR))
                {
                    destAddr.SetRawHostAddress(ProtoAddress::IPv4, (char*)CMSG_DATA(cmptr), 4);
                }
#else
                if (cmptr->cmsg_type == IP_PKTINFO)
                {
                    struct in_pktinfo* pktInfo = (struct in_pktinfo*)((void*)CMSG_DATA(cmptr));
                    destAddr.SetRawHostAddress(ProtoAddress::IPv4, (char*)(&pktInfo->ipi_addr), 4);
                }
#endif // if/else IP_RECVDSTADDR
            }
#ifdef HAVE_IPV6
            if (cmptr->cmsg_level == IPPROTO_IPV6)   
            {             
#ifdef IPV6_RECVDSTADDR
                if (cmptr->cmsg_type == IPV6_RECVDSTADDR)
                {
                    destAddr.SetRawHostAddress(ProtoAddress::IPv6, (char*)CMSG_DATA(cmptr), 16);
                }
#else
                if (cmptr->cmsg_type == IPV6_PKTINFO)
                {
                    struct in6_pktinfo* pktInfo = (struct in6_pktinfo*)((void*)CMSG_DATA(cmptr));
                    destAddr.SetRawHostAddress(ProtoAddress::IPv6, (char*)(&pktInfo->ipi6_addr), 16);
                }
#endif // if/else IPV6_RECVDSTADDR
            }
#endif // HAVE_IPV6    
        } 
        return true;
    }
}  // end ProtoSocket::RecvFrom(w/ destAddr)
#else
// WIN32 implementation
bool ProtoSocket::RecvFrom(char*            buffer, 
                           unsigned int&    numBytes, 
                           ProtoAddress&    sourceAddr,
                           ProtoAddress&    destAddr)
{
	if (!IsBound())
    {
        PLOG(PL_ERROR, "ProtoSocket::RecvFrom() error: socket not bound\n");
        numBytes = 0;    
    }
    if (!ip_recvdstaddr) EnableRecvDstAddr();  // should enable ahead of time to make sure you don't miss any
    destAddr.Invalidate();  // will be filled in if possible
    
    if (NULL == WSARecvMsg)
    {
        PLOG(PL_WARN, "ProtoSocket::RecvFrom() warning: WSARecvMsg() not supported\n");
        return RecvFrom(buffer, numBytes, sourceAddr);
    }
    struct sockaddr sockAddr;
    socklen_t addrLen = sizeof(sockAddr);
    
    // Buffer to receive control data (destAddr info)
    char cdata[256];
    // Buffer to receive data
    WSABUF dbuf[1];
    dbuf[0].len = numBytes;
    dbuf[0].buf = buffer;
    
    WSAMSG msg;
    msg.name = &sockAddr;
    msg.namelen = addrLen;
    msg.lpBuffers = dbuf;
    msg.dwBufferCount = 1;
    msg.Control.len = 64;
    msg.Control.buf = cdata;
    msg.dwFlags = 0;
    destAddr.Invalidate();
    
    DWORD bytesRecvd;
    if (SOCKET_ERROR == WSARecvMsg(handle, &msg, &bytesRecvd, NULL, NULL))
    {
        numBytes = 0;
        switch (WSAGetLastError())
        {
            case WSAEINTR:
            case WSAEWOULDBLOCK:
				//PLOG(PL_WARN, "ProtoSocket::RecvFrom() WSARecvMsg() error: %s\n", GetErrorString());
				input_ready = false;  
                return true;
                break;
            default:
                PLOG(PL_ERROR, "ProtoSocket::RecvFrom() WSARecvMsg() error: %s\n", GetErrorString());
                break;
        }
        return false;
    }
    else
    {
        numBytes = bytesRecvd;
        sourceAddr.SetSockAddr(*((struct sockaddr*)&sockAddr));
        if (!sourceAddr.IsValid())
        {
            PLOG(PL_ERROR, "ProtoSocket::RecvFrom() error: Unsupported address type!\n");
            return false;
        }
        // Get destAddr info
		for (WSACMSGHDR* cmptr = WSA_CMSG_FIRSTHDR(&msg); cmptr != NULL; cmptr = WSA_CMSG_NXTHDR(&msg, cmptr)) 
        {
			if (cmptr->cmsg_level == IPPROTO_IP)
            {
#ifdef IP_RECVDSTADDR
                if ((cmptr->cmsg_level == IPPROTO_IP) && (cmptr->cmsg_type == IP_RECVDSTADDR))
                {
                    destAddr.SetRawHostAddress(ProtoAddress::IPv4, (char*)WSA_CMSG_DATA(cmptr), 4);
                }
#else
                if (cmptr->cmsg_type == IP_PKTINFO)
                {
                    struct in_pktinfo* pktInfo = (struct in_pktinfo*)((void*)WSA_CMSG_DATA(cmptr));
                    destAddr.SetRawHostAddress(ProtoAddress::IPv4, (char*)(&pktInfo->ipi_addr), 4);
                }
#endif // if/else IP_RECVDSTADDR
            }
#ifdef HAVE_IPV6
            if (cmptr->cmsg_level == IPPROTO_IPV6)   
            {             
#ifdef IPV6_RECVDSTADDR
                if (cmptr->cmsg_type == IPV6_RECVDSTADDR)
                {
                    destAddr.SetRawHostAddress(ProtoAddress::IPv6, (char*)WSA_CMSG_DATA(cmptr), 16);
                }
#else
                if (cmptr->cmsg_type == IPV6_PKTINFO)
                {
                    struct in6_pktinfo* pktInfo = (struct in6_pktinfo*)((void*)WSA_CMSG_DATA(cmptr));
                    destAddr.SetRawHostAddress(ProtoAddress::IPv6, (char*)(&pktInfo->ipi6_addr), 16);
                }
#endif // if/else IPV6_RECVDSTADDR
            }
#endif // HAVE_IPV6    
        } 
        return true;
    }
}  // end ProtoSocket::RecvFrom(w/ destAddr) [WIN32]

#endif // if/else !WIN32

#ifdef HAVE_IPV6
#ifndef IPV6_ADD_MEMBERSHIP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif // !IPV6_ADD_MEMBERSHIP
#endif // HAVE_IPV6 

/**
 * @note On WinNT 4.0 (or earlier?), we seem to need WSAJoinLeaf() for multicast to work
 * Thus NT 4.0 probably doesn't support IPv6 multicast???
 * So, here we use WSAJoinLeaf() iff the OS is NT and version 4.0 or earlier.
 */
 // Full SSM support is still work in progress (only supported on Linux and Mac OSX for moment)
bool ProtoSocket::JoinGroup(const ProtoAddress& groupAddress, 
                            const char*         interfaceName,  // optional interface name for group join
                            const ProtoAddress* sourceAddress)  // optional source address for SSM support
{
    if (!IsOpen() && !Open(0, groupAddress.GetType(), false))
    {
        PLOG(PL_ERROR, "ProtoSocket::JoinGroup() error: unable to open socket\n");
        return false;
    }    
#ifdef WIN32
    if (NULL != sourceAddress)
    {
        // WIN32 SSM support will be added in near future
        PLOG(PL_ERROR, "ProtoSocket::JoinGroup() error: Source-specific Multicast (SSM) for WIN32 not yet supported\n");
        return false;
    }
    // on WinNT 4.0 (or earlier?), we seem to need WSAJoinLeaf() for multicast to work
    // Thus NT 4.0 probably doesn't support IPv6 multicast???
    // So, here we use WSAJoinLeaf() iff the OS is NT and version 4.0 or earlier.
    bool useJoinLeaf = false;
    OSVERSIONINFO vinfo;
    vinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&vinfo);
    if ((VER_PLATFORM_WIN32_NT == vinfo.dwPlatformId) &&
        ((vinfo.dwMajorVersion < 4) ||
            ((vinfo.dwMajorVersion == 4) && (vinfo.dwMinorVersion == 0))))
                useJoinLeaf = true;
    if (useJoinLeaf)
    {
        if (interfaceName && !SetMulticastInterface(interfaceName))
            PLOG(PL_ERROR, "ProtoSocket::JoinGroup() warning: error setting socket multicast interface\n");
        SOCKET result = WSAJoinLeaf(handle, &groupAddress.GetSockAddr(), sizeof(struct sockaddr), 
                                    NULL, NULL, NULL, NULL, JL_BOTH);
        if (INVALID_SOCKET == result)
        {
            PLOG(PL_ERROR, "WSAJoinLeaf() error: %d\n", WSAGetLastError());
            return false;
        }
        else
        {
            return true;
        }
    }  // end if (useJoinLeaf)
#endif // WIN32
    int result;
#ifdef HAVE_IPV6
    if  (ProtoAddress::IPv6 == groupAddress.GetType())
    {
        if (NULL != sourceAddress)
        {
            // IPv6 SSM support will be added in near future
            PLOG(PL_ERROR, "ProtoSocket::JoinGroup() error: Source-specific Multicast (SSM) for IPv6 not yet supported\n");
            return false;
        }
        if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr))
        {
            struct ip_mreq mreq;
            mreq.imr_multiaddr.s_addr = 
                (in_addr_t)IN6_V4MAPPED_ADDR(&(((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr));
            if (NULL != interfaceName)
            {
                ProtoAddress interfaceAddress;
#if (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                if (interfaceAddress.ResolveFromString(interfaceName))
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#else
                if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#endif // if/else (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else
                {
                    PLOG(PL_ERROR, "ProtoSocket::JoinGroup() invalid interface name\n");
                    return false;
                }
            }
            else
            {
                mreq.imr_interface.s_addr = INADDR_ANY;  
            } 
            result = setsockopt(handle, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
        }
        else
        {
            struct ipv6_mreq mreq;
            mreq.ipv6mr_multiaddr = ((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr;
            if (NULL != interfaceName)
                mreq.ipv6mr_interface = GetInterfaceIndex(interfaceName);               
            else
                mreq.ipv6mr_interface = 0;
            result = setsockopt(handle, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
       }
    }
    else
#endif // HAVE_IPV6
    {
        // IPv4 group join
        if (NULL == sourceAddress)
        {
            // non-SSM
        
            struct ip_mreq mreq;
#ifdef HAVE_IPV6
            mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddrStorage())->sin_addr;
#else
            mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddr())->sin_addr;
#endif  // end if/else HAVE_IPV6
            if (NULL != interfaceName)
            {
                ProtoAddress interfaceAddress;
#if (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                if (interfaceAddress.ResolveFromString(interfaceName))
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#else
                if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#endif // if/else (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else
                {
                    PLOG(PL_ERROR, "ProtoSocket::JoinGroup() error: invalid interface name\n");
                    return false;
                }
            }
            else
            {
                mreq.imr_interface.s_addr = INADDR_ANY;  
            }
            result = setsockopt(handle, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
        }
        else
        {
            // SSM join   
#if defined(_PROTOSOCKET_IGMPV3_SSM) && defined(IP_ADD_SOURCE_MEMBERSHIP)
            struct ip_mreq_source mreq;
#ifdef HAVE_IPV6
            mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddrStorage())->sin_addr;
            mreq.imr_sourceaddr = ((struct sockaddr_in*)&sourceAddress->GetSockAddrStorage())->sin_addr;
#else
            mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddr())->sin_addr;
            mreq.imr_sourceaddr = ((struct sockaddr_in*)&sourceAddress->GetSockAddr())->sin_addr;
#endif // if/else HAVE_IPV6
            if (NULL != interfaceName)
            {
                ProtoAddress interfaceAddress;
#if (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                if (interfaceAddress.ResolveFromString(interfaceName))
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#else
                if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#endif // if/else (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else
                {
                    PLOG(PL_ERROR, "ProtoSocket::JoinGroup() invalid interface name\n");
                    return false;
                }
            }
            else
            {
                mreq.imr_interface.s_addr = INADDR_ANY;  
            }
            result = setsockopt(handle, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
            if (result  < 0) 
            {
                   PLOG(PL_ERROR, "ProtoSocket::JoinGroup() setsockopt(IP_ADD_SOURCE_MEMBERSHIP) error: %s\n", strerror( errno ));
                   return false;
            }
		    return true;
#else
            PLOG(PL_ERROR, "ProtoSocket:JoinGroup() error: SSM support not included in this build\n");
            return false;
#endif  // end if/else _PROTOSOCKET_IGMPV3_SSM && IP_ADD_SOURCE_MEMBERSHIP
        }
    }
    if (result < 0)
    { 
        PLOG(PL_ERROR, "ProtoSocket:JoinGroup() setsockopt(add membership) error: %s\n", GetErrorString());
        return false;
    }  
    return true;
}  // end ProtoSocket::JoinGroup() 

bool ProtoSocket::LeaveGroup(const ProtoAddress& groupAddress,
                             const char*         interfaceName,
                             const ProtoAddress* sourceAddress)
{    
    if (!IsOpen()) return true;
    int result;
#ifdef HAVE_IPV6
    if (ProtoAddress::IPv6 == groupAddress.GetType())
    {
        // IPv6 leave
        if (NULL != sourceAddress)
        {
            // IPv6 SSM support will be added in near future
            PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() error: Source-specific Multicast (SSM) for IPv6 not yet supported\n");
            return false;
        }
        if (IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr))
        {
            struct ip_mreq mreq;
            mreq.imr_multiaddr.s_addr = 
                (in_addr_t)IN6_V4MAPPED_ADDR(&(((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr));
            if (interfaceName)
            {
                ProtoAddress interfaceAddress;
#if (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                if (interfaceAddress.ResolveFromString(interfaceName))
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#else
                if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#endif // if/else (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else
                {
                    PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() invalid interface name\n");
                    return false;
                }
            }
            else
            {
                mreq.imr_interface.s_addr = INADDR_ANY; 
            }
            result = setsockopt(handle, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
        }
        else
        {
            struct ipv6_mreq mreq;
            mreq.ipv6mr_multiaddr = ((struct sockaddr_in6*)&groupAddress.GetSockAddrStorage())->sin6_addr;
            if (interfaceName)
                mreq.ipv6mr_interface = GetInterfaceIndex(interfaceName);
            else
                mreq.ipv6mr_interface = 0;
            result = setsockopt(handle, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
        }
    }
    else
#endif // HAVE_IPV6
    {
        // IPv4 leave
        if (NULL == sourceAddress)
        {
            // non-SSM
            struct ip_mreq mreq;
#ifdef HAVE_IPV6
            mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddrStorage())->sin_addr;
#else
            mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddr())->sin_addr;
#endif  // end if/else HAVE_IPV6
            if (NULL != interfaceName)
            {
                ProtoAddress interfaceAddress;
#if (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                if (interfaceAddress.ResolveFromString(interfaceName))
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#else
                if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#endif // if/else (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else
                {
                    PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() invalid interface name\n");
                    return false;
                }
            }
            else
            {
                    mreq.imr_interface.s_addr = INADDR_ANY; 
            }
            result = setsockopt(handle, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
        }
        else
        {
            // SSM Leave
#if defined(_PROTOSOCKET_IGMPV3_SSM) && defined(IP_DROP_SOURCE_MEMBERSHIP)
            struct ip_mreq_source   mreq;
#ifdef HAVE_IPV6
            mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddrStorage())->sin_addr;
            mreq.imr_sourceaddr = ((struct sockaddr_in*)&sourceAddress->GetSockAddrStorage())->sin_addr;
#else
            mreq.imr_multiaddr = ((struct sockaddr_in*)&groupAddress.GetSockAddr())->sin_addr;
            mreq.imr_sourceaddr = ((struct sockaddr_in*)&sourceAddress->GetSockAddr())->sin_addr;
#endif  // if/else HAVE_IPV6
            if (interfaceName)
            {
                ProtoAddress interfaceAddress;
#if (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                if (interfaceAddress.ResolveFromString(interfaceName))
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#else
                if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#endif // if/else (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
                {
                    mreq.imr_interface.s_addr = htonl(interfaceAddress.IPv4GetAddress());
                }
                else
                {
                    PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() invalid interface name\n");
                    return false;
                }
            }
            else
            {
                    mreq.imr_interface.s_addr = INADDR_ANY; 
            }
            result = setsockopt(handle, IPPROTO_IP, IP_DROP_SOURCE_MEMBERSHIP, (char*)&mreq, sizeof(mreq));
#else
            PLOG(PL_ERROR, "ProtoSocket:LeaveGroup() error: SSM support not included in this build\n");
            return false;
#endif  // end if/else _PROTOSOCKET_IGMPV3_SSM && IP_DROP_SOURCE_MEMBERSHIP
        }
    }
    if (result < 0)
    {
        PLOG(PL_ERROR, "ProtoSocket::LeaveGroup() error leaving multicast group: %s\n", GetErrorString());
        return false;
    }
    else
    {
        return true;
    }
}  // end ProtoSocket::LeaveGroup() 

// Set MulticastTTL Function name retained for backwards compatability
// See new ProtoSocket::SetUnicastTTL
bool ProtoSocket::SetTTL(unsigned char ttl)
{   
#if defined(WIN32) && !defined(_WIN32_WCE)
    DWORD dwTTL = (DWORD)ttl; 
    DWORD dwBytesXfer;
    int optVal = ttl;
    int optLen = sizeof(int);
    if (WSAIoctl(handle, SIO_MULTICAST_SCOPE, &dwTTL, sizeof(dwTTL),
			    NULL, 0, &dwBytesXfer, NULL, NULL))

#else
    int result = 0;
#ifdef HAVE_IPV6
    if (IPv6 == domain)
    {
#ifdef MACOSX
    // v6 multicast TTL socket option must be an int
        int hops = (int) ttl;

        if (protocol != ProtoSocket::TCP)
            result = setsockopt(handle, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, 
                                &hops, sizeof(hops));

        if (result == 0)
            result = setsockopt(handle, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
                                &hops, sizeof(hops));
#else

        socklen_t hops = (socklen_t) ttl;
        
        if (protocol != ProtoSocket::TCP)
            result = setsockopt(handle, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, 
                                &hops, sizeof(hops));
        
        if (result == 0)
            result = setsockopt(handle, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
                                &hops, sizeof(hops));
#endif // MACOSX
    }
    else
#endif // HAVE_IPV6
    {
#ifdef _WIN32_WCE
        int hops = (int)ttl;
#else
	socklen_t hops = (socklen_t)ttl;
#endif // if/else _WIN32_WCE/UNIX
#ifdef MACOSX
	if (protocol != ProtoSocket::TCP)
	  result = setsockopt(handle, IPPROTO_IP, IP_MULTICAST_TTL, 
                            (char*)&hops, sizeof(hops));

	if (result == 0)
	  result = setsockopt(handle,IPPROTO_IP, IP_TTL,
			      (char*)&hops, sizeof(hops));

#else
	if (protocol != ProtoSocket::TCP)
	  result = setsockopt(handle, IPPROTO_IP, IP_MULTICAST_TTL, 
			      (char*)&hops, sizeof(hops));
#endif 
    }
    if (result < 0) 
#endif // if/else WIN32/UNIX | _WIN32_WCE
    { 
		
		PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_MULTICAST_TTL) error: %s\n", GetErrorString()); 
        return false;
    }
    else
    {   
        return true;
    }
}  // end ProtoSocket::SetTTL()

bool ProtoSocket::SetUnicastTTL(unsigned char ttl)
{   
#if defined(WIN32) && !defined(_WIN32_WCE)
    DWORD dwTTL = (DWORD)ttl; 
    DWORD dwBytesXfer;
    int optVal = ttl;
    int optLen = sizeof(int);
    if (setsockopt(handle,IPPROTO_IP,IP_TTL,(char*)&optVal,optLen) == SOCKET_ERROR)
	{
      PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_TTL) error: %s\n", GetErrorString()); 
	  return false;
	}
#else
    int result = 0;
#ifdef HAVE_IPV6
    if (IPv6 == domain)
    {
        socklen_t hops = (socklen_t) ttl;

#ifdef MACOSX
	result = setsockopt(handle, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
			      &hops, sizeof(&hops));
#else
	result = setsockopt(handle, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
			      &hops, sizeof(hops));
#endif // MACOSX
    }
    else
#endif // HAVE_IPV6
    {
#ifdef _WIN32_WCE
        int hops = (int)ttl;
#else
	socklen_t hops = (socklen_t)ttl;
#endif // if/else _WIN32_WCE/UNIX
#ifdef MACOSX
	result = setsockopt(handle,IPPROTO_IP, IP_TTL,
			    (char*)&hops, sizeof(&hops));

#else
	result = setsockopt(handle,IPPROTO_IP, IP_TTL,
			    (char*)&hops, sizeof(hops));
#endif 
    }
    if (result < 0) 
    { 
		
	PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_MULTICAST_TTL) error: %s\n", GetErrorString()); 
        return false;
    }
#endif // if/else WIN32/UNIX | _WIN32_WCE
    else
    {   
        return true;
    }
}  // end ProtoSocket::SetUnicastTTL()

bool ProtoSocket::SetTOS(UINT8 theTOS)
{ 
    if (!IsOpen())
    {
        tos = theTOS;
        return true;
    }
    if (ecn_capable)
    {
        theTOS |= ((UINT8)ECN_ECT0);  // set ECT0 bit
        theTOS &= ~((UINT8)ECN_ECT1); // clear ECT1 bit
    }
#ifdef NEVER_EVER // (for older LINUX?)                  
   int precedence = IPTOS_PREC(theTOS);
   if (setsockopt(handle, SOL_SOCKET, SO_PRIORITY, (char*)&precedence, sizeof(precedence)) < 0)           
   {     
       PLOG(PL_ERROR, "ProtoSocket: setsockopt(SO_PRIORITY) error: %s\n", GetErrorString()); 
       return false;
    }                          
   int tosBits = IPTOS_TOS(theTOS);
   if (setsockopt(handle, SOL_IP, IP_TOS, (char*)&tosBits, sizeof(tosBits)) < 0) 
#else
    int tosBits = theTOS;
    int result = -1;
#ifdef HAVE_IPV6
    if (IPv6 == domain)
    {
#ifdef IPV6_TCLASS
        result = setsockopt(handle, IPPROTO_IPV6, IPV6_TCLASS, (char*)&tosBits, sizeof(tosBits));
		if (result < 0)
#endif // IPV6_TCLASS
		{
			result = setsockopt(handle, IPPROTO_IPV6, IP_TOS, (char*)&tosBits, sizeof(tosBits));
			if (result < 0)
				PLOG(PL_ERROR,"ProtoSocket::SetTOS() Error setting IPV6 tos/tclass %s",GetErrorString());
		}
        SetFlowLabel(((UINT32)theTOS) << 20);  // set flow label "traffic class" to "tos" value
    }
    else 
#endif // HAVE_IPV6  
    {
        result =  setsockopt(handle, IPPROTO_IP, IP_TOS, (char*)&tosBits, sizeof(tosBits));    
    }
#endif  // if/else NEVER_EVER
    if (result < 0)
    {               
        PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_TOS) error\n");
        return false;
    }
    tos = theTOS;
    return true; 
}  // end ProtoSocket::SetTOS()

/**
 * (TBD) add mechanism to dither ECN ECT0/ECT1 1-bit "nonce" 
 * of RFC3168 (e.g. RFC3540).  For now we set ECT0 bit only.
 */
bool ProtoSocket::SetEcnCapable(bool state)
{
    if (state)
    {
        if (!ecn_capable)
        {
            ecn_capable = true;
            bool result = SetTOS(tos);  // will update saved "tos" value accordingly
            if (!result) ecn_capable = false;
            return result;
        }
    }
    else if (ecn_capable)
    {
        ecn_capable = false;
        bool result = SetTOS(tos);
        if (!result) ecn_capable = true;
        return result;
    }
    return true;
}  // end ProtoSocket::SetEcnCapable()

bool ProtoSocket::SetBroadcast(bool broadcast)
{
#ifdef SO_BROADCAST
#ifdef WIN32
    BOOL state = broadcast ? TRUE : FALSE;
#else
    int state = broadcast ? 1 : 0;
#endif // if/else WIN32
    if (setsockopt(handle, SOL_SOCKET, SO_BROADCAST, (char*)&state, sizeof(state)) < 0)
    {
        PLOG(PL_ERROR, "ProtoSocket::SetBroadcast(): setsockopt(SO_BROADCAST) error: %s\n",
                GetErrorString());
        return false;
    }
#endif // SO_BROADCAST
    return true;
}  // end ProtoSocket::SetBroadcast()


bool ProtoSocket::SetFragmentation(bool enable)
{
#ifdef WIN32
    DWORD df = enable ? FALSE : TRUE;
    if (setsockopt(handle, IPPROTO_IP, IP_DONTFRAGMENT, (char*)&df, sizeof(df)) < 0)
    {
        PLOG(PL_ERROR, "ProtoSocket::SetFragmentation() setsockopt(IP_DONTFRAGMENT) error: %s\n", GetErrorString());
        return false;
    }
#else  // UNIX
#if defined(IP_MTU_DISCOVER)
    // Note PMTUDISC_DONT clears DF flag while PMTUDISC_DO sets DF flag for MTU discovery
    // (thus, IP_PMTUDISC_DONT allows fragmentation to occur)
    int val = enable ? IP_PMTUDISC_DONT : IP_PMTUDISC_DO;
    if (setsockopt(handle, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)) < 0)
    {
#if defined(HAVE_IPV6) && defined(IPV6_DONTFRAG)
        if (IPv6 == domain)
        {
            // For IPv6 sockets, we can try "IPV6_DONTFRAG" as a backup
            // (clear DF to allow fragmenation to occur)
            int df = enable ? 0 : 1;
            if (setsockopt(handle, IPPROTO_IPV6, IPV6_DONTFRAG, &df, sizeof(df)) < 0)
            {
                PLOG(PL_ERROR, "ProtoSocket::SetFragmentation() setsockopt(IPV6_DONTFRAG) error: %s\n", GetErrorString());
                return false;
            }
        }
        else
#endif // HAVE_IPV6 && IPV6_DONTFRAG
        {
            PLOG(PL_ERROR, "ProtoSocket::SetFragmentation() setsockopt(IP_MTU_DISCOVER) error: %s\n", GetErrorString());
            return false;
        }
    }
#elif defined(IP_DONTFRAG)
    int df = enable ? 0 : 1;
    int result;
#if defined(HAVE_IPV6) && defined(IPV6_DONTFRAG)
    if (IPv6 == domain)
        result = setsockopt(handle, IPPROTO_IP, IPV6_DONTFRAG, (char*)&df, sizeof(df));
    else
#endif
        result = setsockopt(handle, IPPROTO_IP, IP_DONTFRAG, (char*)&df, sizeof(df));
    if (result < 0)
    {
        PLOG(PL_ERROR, "ProtoSocket::SetFragmentation() setsockopt(IP_DONTFRAG) error: %s\n", GetErrorString());
        return false;
    }
#else
    PLOG(PL_WARN, "ProtoSocket::SetFragmentation() warning: IP_MTU_DISCOVER or IP_DONTFRAG socket option not supported!\n");
    return false;
#endif // if/else IP_MTU_DISCOVER / IP_DONTFRAG / none
#endif // if/else WIN32 / UNIX
    return true;
}  // end ProtoSocket::SetFragmentation()

bool ProtoSocket::SetLoopback(bool loopback)
{
    ASSERT(IsOpen());
#ifdef WIN32
    DWORD dwLoop = loopback ? TRUE: FALSE;
    DWORD dwBytesXfer;
    if (WSAIoctl(handle, SIO_MULTIPOINT_LOOPBACK , &dwLoop, sizeof(dwLoop),
                 NULL, 0, &dwBytesXfer, NULL, NULL))
#else 
    int result;
    char loop = loopback ? 1 : 0;
#ifdef HAVE_IPV6
    unsigned int loop6 = loopback ? 1 : 0;  // this is needed at least for FreeBSD
    if (IPv6 == domain)
        result = setsockopt(handle, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, 
                            (char*)&loop6, sizeof(loop6));
    else
#endif // HAVE_IPV6
    result = setsockopt(handle, IPPROTO_IP, IP_MULTICAST_LOOP, 
                        (char*)&loop, sizeof(loop));
    if (result < 0)
#endif // if/else WIN32
    {
#ifdef WIN32
        // On NT, this the SIO_MULTIPOINT_LOOPBACK always seems to return an error
        // so we'll ignore the error and return success on NT4 and earlier
        OSVERSIONINFO vinfo;
        vinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        GetVersionEx(&vinfo);
        if ((VER_PLATFORM_WIN32_NT == vinfo.dwPlatformId) &&
            ((vinfo.dwMajorVersion < 4) ||
                ((vinfo.dwMajorVersion == 4) && (vinfo.dwMinorVersion == 0))))
                    return true;
#endif // WIN32
        PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_MULTICAST_LOOP) error: %s\n", GetErrorString());
        return false;
    } 
    else
    {
        return true;
    }
}  // end ProtoSocket::SetLoopback() 

bool ProtoSocket::SetBindInterface(const char* ifaceName)
{
#ifdef SO_BINDTODEVICE
    size_t nameSize = strlen(ifaceName) + 1;  // includes NULL termination
    if (setsockopt(handle, SOL_SOCKET, SO_BINDTODEVICE, ifaceName, nameSize) < 0)
    {
        PLOG(PL_ERROR, "ProtoSocket::SetBindInterface() error: %s\n", GetErrorString());
        return false;
    }
    return true;
#else
    // TBD - For MacOS/BSD, we can use the IP_RECVIF socket options and recvmsg() calls
    //       (under the hood) and filter incoming datagrams for a specific interface
    //       to _simulate_ the behavior of SO_BINDTODEVICE.  Not yet sure what to do
    //       here for WIN32 systems.
    
    PLOG(PL_ERROR, "ProtoSocket::SetBindInterface() error: SO_BINDTODEVICE socket option not supported!\n", GetErrorString());
    return false;
#endif  // if/else SO_BINDTODEVICE
}  // end ProtoSocket::SetBindInterface()

bool ProtoSocket::SetMulticastInterface(const char* interfaceName)
{    
    if (interfaceName)
    {
        int result;
#ifdef HAVE_IPV6
        if (IPv6 == domain)  
        {
#ifdef WIN32
            // (TBD) figure out Win32 IPv6 multicast interface
            PLOG(PL_ERROR, "ProtoSocket::SetMulticastInterface() not yet supported for IPv6 on WIN32?!\n");
            return false;
#else
            unsigned int interfaceIndex = GetInterfaceIndex(interfaceName);
            result = setsockopt(handle, IPPROTO_IPV6, IPV6_MULTICAST_IF,
                                (char*)&interfaceIndex, sizeof(interfaceIndex));
#endif // if/else WIN32
        }
        else 
#endif // HAVE_IPV6 
        {  
            struct in_addr localAddr;
            ProtoAddress interfaceAddress;
#if (defined(WIN32) && (WINVER < 0x0500)) || defined(ANDROID)
            // First check to see if "interfaceName" is the IP address on older Win32 versions
            // since there seem to be issues with iphlpapi.lib (and hence GetInterfaceAddress()) on those platforms
            if (interfaceAddress.ResolveFromString(interfaceName))
            {
                localAddr.s_addr = htonl(interfaceAddress.IPv4GetAddress());
            }
            else if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#else
            if (GetInterfaceAddress(interfaceName, ProtoAddress::IPv4, interfaceAddress))
#endif // if/else WIN32 &&  (WINVER < 0x0500)
			{
                localAddr.s_addr = htonl(interfaceAddress.IPv4GetAddress());
            }
            else
            {
                PLOG(PL_ERROR, "ProtoSocket::SetMulticastInterface() invalid interface name: %s\n", interfaceName);
                return false;
            }
            result = setsockopt(handle, IPPROTO_IP, IP_MULTICAST_IF, (char*)&localAddr, 
                                sizeof(localAddr));
        }
        if (result < 0)
        { 
            PLOG(PL_ERROR, "ProtoSocket: setsockopt(IP_MULTICAST_IF) error: %s\n", GetErrorString());
            return false;
        }         
    }     
    return true;
}  // end ProtoSocket::SetMulticastInterface()

bool ProtoSocket::SetReuse(bool state)
{
#if defined(SO_REUSEADDR) || defined(SO_REUSEPORT)
    bool success = true;
#else
    return false;
#endif
    int reuse = state ? 1 : 0;
#ifdef SO_REUSEADDR
#ifdef WIN32
    BOOL reuseAddr = (BOOL)reuse;
    if (setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, (char*)&reuseAddr, sizeof(reuseAddr)) < 0)
#else
    if (setsockopt(handle, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse)) < 0)
#endif // if/else WIN32
    {
        PLOG(PL_ERROR, "ProtoSocket: setsockopt(REUSE_ADDR) error: %s\n", GetErrorString());
        success = false;
    }
#endif // SO_REUSEADDR            
            
#ifdef SO_REUSEPORT  // not defined on Linux for some reason?
#ifdef WIN32
    BOOL reusePort = (BOOL)reuse;
	if (setsockopt(handle, SOL_SOCKET, SO_REUSEPORT, (char*)&reusePort, sizeof(reusePort)) < 0)
#else
    if (setsockopt(handle, SOL_SOCKET, SO_REUSEPORT, (char*)&reuse, sizeof(reuse)) < 0)
#endif // if/else WIN32
    {
        PLOG(PL_ERROR, "ProtoSocket: setsockopt(SO_REUSEPORT) error: %s\n", GetErrorString());
        success = false;
    }
#endif // SO_REUSEPORT
    return success;
}  // end ProtoSocketError::SetReuse()

#ifdef HAVE_IPV6
bool ProtoSocket::HostIsIPv6Capable()
{
#ifdef WIN32
    if (!ProtoAddress::Win32Startup())
    {
        PLOG(PL_ERROR, "ProtoSocket::HostIsIPv6Capable() WSAStartup() error: %s\n", GetErrorString());
        return false;
    }
    SOCKET handle = socket(AF_INET6, SOCK_DGRAM, 0);
    closesocket(handle);
	ProtoAddress::Win32Cleanup();
    if(INVALID_SOCKET == handle)
        return false;
    else
        return true;
#else
    if (IPV6_UNKNOWN == ipv6_support_status)
    {
        ProtoAddressList addrList;
        ProtoNet::GetHostAddressList(ProtoAddress::IPv6, addrList);
        if (addrList.IsEmpty())
        {
            ipv6_support_status = IPV6_UNSUPPORTED;
        }
        else
        {
            ipv6_support_status = IPV6_SUPPORTED;
        }
    }
    return (IPV6_SUPPORTED == ipv6_support_status);
#endif  // if/else WIN32
}  // end ProtoSocket::HostIsIPv6Capable()

#endif // HAVE_IPV6


bool ProtoSocket::SetTxBufferSize(unsigned int bufferSize)
{
   if (!IsOpen())
   {
        PLOG(PL_ERROR, "ProtoSocket::SetTxBufferSize() error: socket closed\n");     
        return false;
   }
   unsigned int oldBufferSize = GetTxBufferSize();
   if (setsockopt(handle, SOL_SOCKET, SO_SNDBUF, (char*)&bufferSize, sizeof(bufferSize)) < 0) 
   {
        setsockopt(handle, SOL_SOCKET, SO_SNDBUF, (char*)&oldBufferSize, sizeof(oldBufferSize));
        PLOG(PL_ERROR, "ProtoSocket::SetTxBufferSize() setsockopt(SO_SNDBUF) error: %s\n",
                GetErrorString());
        return false;
   }
   return true;
}  // end ProtoSocket::SetTxBufferSize()

unsigned int ProtoSocket::GetTxBufferSize()
{
    if (!IsOpen()) return 0;
    unsigned int txBufferSize = 0;
    socklen_t len = sizeof(txBufferSize);
    if (getsockopt(handle, SOL_SOCKET, SO_SNDBUF, (char*)&txBufferSize, &len) < 0) 
    {
        PLOG(PL_ERROR, "ProtoSocket::GetTxBufferSize() getsockopt(SO_SNDBUF) error: %s\n",
                 GetErrorString());
	    return 0; 
    }
    return ((unsigned int)txBufferSize);
}  // end ProtoSocket::GetTxBufferSize()

bool ProtoSocket::SetRxBufferSize(unsigned int bufferSize)
{
   if (!IsOpen())
   {
        PLOG(PL_ERROR, "ProtoSocket::SetRxBufferSize() error: socket closed\n");    
        return false;
   }
   unsigned int oldBufferSize = GetRxBufferSize();
   if (setsockopt(handle, SOL_SOCKET, SO_RCVBUF, (char*)&bufferSize, sizeof(bufferSize)) < 0) 
   {
        setsockopt(handle, SOL_SOCKET, SO_RCVBUF, (char*)&oldBufferSize, sizeof(oldBufferSize));
        PLOG(PL_ERROR, "ProtoSocket::SetRxBufferSize() setsockopt(SO_RCVBUF) error: %s\n",
                GetErrorString());
        return false;
   }
   return true;
}  // end ProtoSocket::SetRxBufferSize()

unsigned int ProtoSocket::GetRxBufferSize()
{
    if (!IsOpen()) return 0;
    unsigned int rxBufferSize = 0;
    socklen_t len = sizeof(rxBufferSize);
    if (getsockopt(handle, SOL_SOCKET, SO_RCVBUF, (char*)&rxBufferSize, &len) < 0) 
    {
        PLOG(PL_ERROR, "ProtoSocket::GetRxBufferSize() getsockopt(SO_RCVBUF) error: %s\n",
                GetErrorString());
	    return 0; 
    }
    return ((unsigned int)rxBufferSize);
}  // end ProtoSocket::GetRxBufferSize()

#ifdef HAVE_IPV6
bool ProtoSocket::SetFlowLabel(UINT32 label)  
{
    int result = 0; 
#ifdef SOL_IPV6
    if (label && !flow_label)
    {
       int on = 1;
       result = setsockopt(handle, SOL_IPV6, IPV6_FLOWINFO_SEND, (char*)&on, sizeof(on));
    }
    else if (!label && flow_label)
    {
        int off = 0;
        result = setsockopt(handle, SOL_IPV6, IPV6_FLOWINFO_SEND, (char*)&off, sizeof(off));
    }
#endif  // SOL_IPV6
    if (0 == result)
    {
        if (ecn_capable)
        {
            label |= (((UINT32)ECN_ECT0) << 20);    // set ECN_ECT0 bit
            label &= ~(((UINT32)ECN_ECT1) << 20);   // clear ECN_ECT1 bit
        }
        flow_label = htonl(label);
        return true;
    }
    else
    {
        PLOG(PL_ERROR, "ProtoSocket::SetFlowLabel() setsockopt(SOL_IPV6) error\n");
        return false;
    }    
}  // end ProtoSocket::SetFlowLabel()
#endif  //HAVE_IPV6



ProtoSocket::List::List()
 : head(NULL)
{
}

ProtoSocket::List::~List()
{
    Destroy();
}

void ProtoSocket::List::Destroy()
{
    Item* next = head;
    while (next)
    {
        Item* current = next;
        next = next->GetNext();
        delete current->GetSocket();
        delete current;
    }   
    head = NULL;
}  // end ProtoSocket::List::Destroy()

bool ProtoSocket::List::AddSocket(ProtoSocket& theSocket)
{
    Item* item = new Item(&theSocket);
    if (item)
    {
        item->SetPrev(NULL);
        item->SetNext(head);
        head = item;
        return true;
    }
    else
    {
        PLOG(PL_ERROR, "ProtoSocket::List::AddSocket() new Item error: %s\n", GetErrorString());
        return false;
    }
}  // end ProtoSocket::List::AddSocket()

void ProtoSocket::List::RemoveSocket(ProtoSocket& theSocket)
{
    Item* item = head;
    while (item)
    {
        if (&theSocket == item->GetSocket())
        {
            Item* prev = item->GetPrev();
            Item* next = item->GetNext();
            if (prev) 
                prev->SetNext(next);
            else
                head = next;
            if (next) next->SetPrev(prev);
            delete item;
            break;
        }
        item = item->GetNext();   
    }
}  // end ProtoSocket::List::RemoveSocket()

ProtoSocket::List::Item* ProtoSocket::List::FindItem(const ProtoSocket& theSocket) const
{
    Item* item = head;
    while (item)
    {
        if (&theSocket == item->GetSocket())
            return item;
        else
            item = item->GetNext(); 
    }  
    return NULL; 
}  // end ProtoSocket::List::FindItem()

ProtoSocket::List::Item::Item(ProtoSocket* theSocket)
 : socket(theSocket), prev(NULL), next(NULL)
{
}

ProtoSocket::List::Iterator::Iterator(const ProtoSocket::List& theList)
 : next(theList.head)
{
}


////////////////////////////////////////////////////////////////////
// These are some network "helper" functions that get information
// about the system network devices (interfaces), addresses, etc
//
// Note that the "ProtoSocket" implementation of this is being replaced
// by implementation in the "ProtoNet" namespace (see "protoNet.h") and
// the implementations here will eventually be removed _and_ the ProtoSocket
// static method declarations themselves will be eventually deprecated

#include "protoNet.h"

bool ProtoSocket::GetHostAddressList(ProtoAddress::Type  addrType,
				     ProtoAddressList&   addrList)
{
	return ProtoNet::GetHostAddressList(addrType, addrList);
}  // end ProtoSocket::GetHostAddressList()


bool ProtoSocket::GetInterfaceAddress(const char*         ifName, 
				                      ProtoAddress::Type  addrType,
				                      ProtoAddress&       theAddress,
                                      unsigned int*       ifIndex)
{
	return ProtoNet::GetInterfaceAddress(ifName, addrType, theAddress, ifIndex);
}  // end ProtoSocket::GetInterfaceAddress()

bool ProtoSocket::GetInterfaceAddressList(const char*         interfaceName,
                                          ProtoAddress::Type  addressType,
                                          ProtoAddressList&   addrList,
                                          unsigned int*       interfaceIndex)
                                          
{
    return ProtoNet::GetInterfaceAddressList(interfaceName, addressType, addrList, interfaceIndex);
}  // end ProtoSocket::GetInterfaceAddressList()


bool ProtoSocket::FindLocalAddress(ProtoAddress::Type addrType, ProtoAddress& theAddress)
{
	return ProtoNet::FindLocalAddress(addrType, theAddress);
}  // end ProtoSocket::FindLocalAddress()

unsigned int ProtoSocket::GetInterfaceIndex(const char* interfaceName)
{
    return ProtoNet::GetInterfaceIndex(interfaceName);
}  // end ProtoSocket::GetInterfaceIndex()

unsigned int ProtoSocket::GetInterfaceIndices(unsigned int* indexArray, unsigned int indexArraySize)
{
    return ProtoNet::GetInterfaceIndices(indexArray, indexArraySize);
}  // end ProtoSocket::GetInterfaceIndices()


bool ProtoSocket::GetInterfaceName(unsigned int index, char* buffer, unsigned int buflen)
{
    return (0 != ProtoNet::GetInterfaceName(index, buffer, buflen));
}  // end ProtoSocket::GetInterfaceName(by index)


bool ProtoSocket::GetInterfaceName(const ProtoAddress& ifAddr, char* buffer, unsigned int buflen)
{  
    return (0 != ProtoNet::GetInterfaceName(ifAddr, buffer, buflen));
}  // end ProtoSocket::GetInterfaceName(by address)