|
root / base / usr / src / cmd / cmd-inet / usr.sbin / ping
ping Plain Text 5224 lines 137.9 KB
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

PROG=		ping
OBJS=		ping.o ping_aux.o ping_aux6.o

# Hammerhead: Install to /sbin
ROOTFS_PROG = $(PROG)

include	../../../Makefile.cmd

# Hammerhead: /usr/sbin compat symlink
ROOTUSRSBINLINKS = $(PROG:%=$(ROOTUSRSBIN)/%)

$(ROOTSBIN)/ping	:	FILEMODE= 04555

# Ping uses the ancillary data feature which is available only through
# UNIX 98 standards version of Socket interface. This interface is supposed to
# be accessed by -lxnet. In addition -lsocket and is used to
# capture new not-yet-standard interfaces. Someday -lxnet alone should be enough
# when IPv6 inspired new interfaces are part of standards.
LDLIBS +=	-lxnet -lsocket -lm -linetutil

# These #defines are required to use SUSv3 interfaces
CPPFLAGS += -D_XOPEN_SOURCE=600 -D__EXTENSIONS__

CSTD=	$(CSTD_GNU99)

# Hammerhead: Suppress socklen_t type mismatch warnings in legacy code
CERRWARN +=	-Wno-incompatible-pointer-types

.KEEP_STATE:
.PARALLEL:

all:	$(PROG)

$(PROG): $(OBJS)
	$(LINK.c) -o $@ $(OBJS) $(LDLIBS)
	$(POST_PROCESS)

install: all $(ROOTSBINPROG) $(ROOTUSRSBINLINKS)

$(ROOTUSRSBINLINKS):
	-$(RM) $@; $(SYMLINK) ../../sbin/$(@F) $@

clean:
	$(RM) $(OBJS)

include ../../../Makefile.targ
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T
 * All Rights Reserved.
 */

/*
 * University Copyright- Copyright (c) 1982, 1986, 1988
 * The Regents of the University of California.
 * All Rights Reserved.
 *
 * University Acknowledgment- Portions of this document are derived from
 * software developed by the University of California, Berkeley, and its
 * contributors.
 */

/*
 * Copyright (c) 2018, Joyent, Inc.
 * Copyright 2023 Oxide computer Company
 * Copyright 2024 Bill Sommerfeld <sommerfeld@hamachi.org>
 */

#include <assert.h>
#include <stdio.h>
#include <strings.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <limits.h>
#include <math.h>
#include <locale.h>
#include <thread.h>
#include <synch.h>

#include <sys/time.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stropts.h>
#include <sys/file.h>
#include <sys/sysmacros.h>
#include <sys/debug.h>

#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/ip_var.h>
#include <netinet/ip6.h>
#include <netinet/icmp6.h>
#include <netinet/udp.h>
#include <netdb.h>
#include <stdlib.h>
#include <priv_utils.h>

#include <libinetutil.h>
#include "ping.h"

/*
 * This macro is used to compare 16bit, wrapping sequence numbers. Inspired by
 * TCP's SEQ_LEQ macro.
 */
#define	PINGSEQ_LEQ(a, b)	((int16_t)((a)-(b)) <= 0)

#define	MAX_WAIT		10	/* max sec. to wait for response */
#define	MAX_TRAFFIC_CLASS	255	/* max traffic class for IPv6 */
#define	MAX_FLOW_LABEL		0xFFFFF	/* max flow label for IPv6 */
#define	MAX_TOS			255	/* max type-of-service for IPv4 */

#define	TIMEOUT			20	/* default timeout value */
#define	DEFAULT_DATALEN		56

#define	MULTICAST_NOLOOP	1	/* multicast options */
#define	MULTICAST_TTL		2
#define	MULTICAST_IF		4

#define	IF_INDEX		0	/* types of -i argument */
#define	IF_NAME			1
#define	IF_ADDR			2
#define	IF_ADDR6		3

#ifdef BSD
#define	setbuf(s, b)	setlinebuf((s))
#endif /* BSD */


/* interface identification */
union if_id {
	int index;		/* interface index (e.g., 1, 2) */
	char *name;		/* interface name (e.g., le0, hme0) */
	union any_in_addr addr;	/* interface address (e.g., 10.123.4.5) */
};

/* stores the interface supplied by the user */
struct if_entry {
	char *str;		/* unresolved, string input */
	int id_type;		/* type of ID (index, name, addr, addr6) */
	union if_id id;		/* ID */
};

char *progname;
char *targethost;
char *nexthop;

static int send_sock;			/* send sockets */
static int send_sock6;
static struct sockaddr_in to;		/* where to send */
static struct sockaddr_in6 to6;
static union any_in_addr gw_IP_list[MAX_GWS];	/* gateways */
static union any_in_addr gw_IP_list6[MAX_GWS6];
static int if_index = 0;		/* outgoing interface index */
boolean_t is_alive = _B_FALSE;		/* is target host alive */
struct targetaddr *current_targetaddr;	/* current target IP address to probe */
static struct targetaddr *targetaddr_list; /* list of IP addresses to probe */
static int num_targetaddrs;		/* no of target addresses to probe */
static int num_v4 = 0;			/* count of IPv4 addresses */
static int num_v6 = 0;			/* count of IPv6 addresses */
boolean_t verbose = _B_FALSE;		/* verbose output */
boolean_t stats = _B_FALSE;		/* display statistics */
static boolean_t settos = _B_FALSE;	/* set type-of-service value */
boolean_t rr_option = _B_FALSE;		/* true if using record route */
boolean_t send_reply = _B_FALSE;	/* Send an ICMP_{ECHO|TSTAMP}REPLY */
					/* that goes to target and comes back */
					/* to the the sender via src routing. */
boolean_t strict = _B_FALSE;		/* true if using strict source route */
boolean_t ts_option = _B_FALSE;		/* true if using timestamp option */
boolean_t use_icmp_ts = _B_FALSE;	/* Use ICMP timestamp request */
boolean_t use_udp = _B_FALSE;		/* Use UDP instead of ICMP */
boolean_t probe_all = _B_FALSE;		/* probe all the IP addresses */
boolean_t nflag = _B_FALSE;		/* do not reverse lookup addresses */
boolean_t bypass = _B_FALSE;		/* bypass IPsec policy */
static int family_input = AF_UNSPEC;	/* address family supplied by user */
int datalen = DEFAULT_DATALEN;		/* How much data */
int ts_flag;				/* timestamp flag value */
static int num_gw;			/* number of gateways */
static int eff_num_gw;			/* effective number of gateways */
					/* if send_reply, it's 2*num_gw+1 */
static int num_wraps = -1;		/* no of times 64K icmp_seq wrapped */
static ushort_t dest_port = 32768 + 666; /* starting port for the UDP probes */
static char *gw_list[MAXMAX_GWS];	/* list of gateways as user enters */
static int options;			/* socket options */
static int moptions;			/* multicast options */
int npackets;				/* number of packets to send */
static ushort_t tos;			/* type-of-service value */
static int hoplimit = -1;		/* time-to-live value */
static int dontfrag;			/* IP*_DONTFRAG */
static int timeout = TIMEOUT;		/* timeout value (sec) for probes */
static struct if_entry out_if;		/* interface argument */
int ident;				/* ID for this ping run */
static hrtime_t t_last_probe_sent;	/* the time we sent the last probe */
static timer_t timer;			/* timer for waiting */
static volatile boolean_t timer_done = _B_FALSE; /* timer finished? */
static struct itimerspec interval = { { 0, 0 }, { 1, 0 } }; /* Interval for */
					/* -I. The default interval is 1s. */
static hrtime_t mintime = NSEC2MSEC(500);	/* minimum time between pings */

/*
 * Globals for our name services warning. See ns_warning_thr() for more on why
 * this exists.
 */
static mutex_t ns_lock = ERRORCHECKMUTEX; /* Protects the following data */
static boolean_t ns_active = _B_FALSE;	/* Lookup is going on */
static hrtime_t ns_starttime;		/* Time the lookup started */
static int ns_sleeptime = 2;		/* Time in seconds between checks */
static int ns_warntime = 2;		/* Time in seconds before warning */

/*
 * This buffer stores the received packets. Currently it needs to be 32 bit
 * aligned. In the future, we'll be using 64 bit alignment, so let's use 64 bit
 * alignment now.
 */
static uint64_t in_pkt[(IP_MAXPACKET + 1)/8];

/* Used to store the ancillary data that comes with the received packets */
static uint64_t ancillary_data[(IP_MAXPACKET + 1)/8];

static int ntransmitted;	/* number of packet sent to single IP address */
int nreceived;			/* # of packets we got back from target host */
int nreceived_last_target;	/* received from last target IP */
/*
 * These are used for statistics. tmin is initialized to maximum longint value.
 * The max value is also used for timeouts.   All times are in microseconds.
 */
long long tmin = LLONG_MAX;
long long tmax;
int64_t tsum;			/* sum of all times, for doing average */
int64_t tsum2;			/* sum of squared times, for std. dev. */

static struct targetaddr *build_targetaddr_list(struct addrinfo *,
    union any_in_addr *);
static struct targetaddr *create_targetaddr_item(struct sockaddr *,
    union any_in_addr *);
static struct ifaddrlist *find_if(struct ifaddrlist *, int);
static void finish();
static void get_gwaddrs(char *[], int, union any_in_addr *,
    union any_in_addr *, int *, int *);
static void get_hostinfo(char *, int, struct addrinfo **);
static ushort_t in_cksum(ushort_t *, int);
static int int_arg(char *s, char *what);
static void mirror_gws(union any_in_addr *, int);
static void *ns_warning_thr(void *);
static void parse_interval(const char *s);
static void pinger(int, struct sockaddr *, struct msghdr *, int);
static void print_unknown_host_msg(const char *, const char *);
static void recv_icmp_packet(struct addrinfo *, int, int, ushort_t, ushort_t);
static void resolve_nodes(struct addrinfo **, struct addrinfo **,
    union any_in_addr **);
static void select_all_src_addrs(union any_in_addr **, struct addrinfo *,
    union any_in_addr *, union any_in_addr *);
static void select_src_addr(union any_in_addr *, int, union any_in_addr *);
static void set_nexthop(int, struct addrinfo *, int);
static boolean_t setup_socket(int, int *, int *, int *, ushort_t *,
    struct addrinfo *);
static void usage(char *);

/*
 * main()
 */
int
main(int argc, char *argv[])
{
	struct addrinfo	*ai_dst = NULL;		/* addrinfo host list */
	struct addrinfo	*ai_nexthop = NULL;		/* addrinfo nexthop */
	union any_in_addr *src_addr_list = NULL;	/* src addrs to use */
	int recv_sock = -1;				/* receive sockets */
	int recv_sock6 = -1;
	ushort_t udp_src_port;			/* src ports for UDP probes */
	ushort_t udp_src_port6;			/* used to identify replies */
	uint_t flowinfo = 0;
	uint_t class = 0;
	char abuf[INET6_ADDRSTRLEN];
	int c;
	int i;
	boolean_t has_sys_ip_config;

	progname = argv[0];

	(void) setlocale(LC_ALL, "");

	/*
	 * This program needs the net_icmpaccess privilege for creating
	 * raw ICMP sockets.  It needs sys_ip_config for using the
	 * IP_NEXTHOP socket option (IPv4 only).  We'll fail
	 * on the socket call and report the error there when we have
	 * insufficient privileges.
	 *
	 * Shared-IP zones don't have the sys_ip_config privilege, so
	 * we need to check for it in our limit set before trying
	 * to set it.
	 */
	has_sys_ip_config = priv_ineffect(PRIV_SYS_IP_CONFIG);

	(void) __init_suid_priv(PU_CLEARLIMITSET, PRIV_NET_ICMPACCESS,
	    has_sys_ip_config ? PRIV_SYS_IP_CONFIG : (char *)NULL,
	    (char *)NULL);

	setbuf(stdout, (char *)0);

	while ((c = getopt(argc, argv,
	    "abA:c:dDF:G:g:I:i:LlnN:P:p:rRSsTt:UvX:x:Y0123?")) != -1) {
		switch ((char)c) {
		case 'A':
			if (strcmp(optarg, "inet") == 0) {
				family_input = AF_INET;
			} else if (strcmp(optarg, "inet6") == 0) {
				family_input = AF_INET6;
			} else {
				Fprintf(stderr,
				    "%s: unknown address family %s\n",
				    progname, optarg);
				exit(EXIT_FAILURE);
			}
			break;

		case 'a':
			probe_all = _B_TRUE;
			break;

		case 'c':
			i = int_arg(optarg, "traffic class");
			if (i > MAX_TRAFFIC_CLASS) {
				Fprintf(stderr, "%s: traffic class %d out of "
				    "range\n", progname, i);
				exit(EXIT_FAILURE);
			}
			class = (uint_t)i;
			break;

		case 'd':
			options |= SO_DEBUG;
			break;

		case 'D':
			dontfrag = 1;
			break;

		case 'b':
			bypass = _B_TRUE;
			break;

		case 'F':
			i = int_arg(optarg, "flow label");
			if (i > MAX_FLOW_LABEL) {
				Fprintf(stderr, "%s: flow label %d out of "
				    "range\n", progname, i);
				exit(EXIT_FAILURE);
			}
			flowinfo = (uint_t)i;
			break;

		case 'I':
			stats = _B_TRUE;
			parse_interval(optarg);
			break;

		case 'i':
			/*
			 * this can accept interface index, interface name, and
			 * address configured on the interface
			 */
			moptions |= MULTICAST_IF;
			out_if.str = optarg;

			if (inet_pton(AF_INET6, optarg, &out_if.id.addr) > 0) {
				out_if.id_type = IF_ADDR6;
			} else if (inet_pton(AF_INET, optarg,
			    &out_if.id.addr) > 0) {
				out_if.id_type = IF_ADDR;
			} else if (strcmp(optarg, "0") == 0) {
				out_if.id_type = IF_INDEX;
				out_if.id.index = 0;
			} else if ((out_if.id.index = atoi(optarg)) != 0) {
				out_if.id_type = IF_INDEX;
			} else {
				out_if.id.name = optarg;
				out_if.id_type = IF_NAME;
			}
			break;

		case 'L':
			moptions |= MULTICAST_NOLOOP;
			break;

		case 'l':
			send_reply = _B_TRUE;
			strict = _B_FALSE;
			break;

		case 'n':
			nflag = _B_TRUE;
			break;

		case 'P':
			settos = _B_TRUE;
			i = int_arg(optarg, "type-of-service");
			if (i > MAX_TOS) {
				Fprintf(stderr, "%s: tos value %d out of "
				    "range\n", progname, i);
				exit(EXIT_FAILURE);
			}
			tos = (ushort_t)i;
			break;

		case 'p':
			i = int_arg(optarg, "port number");
			if (i > MAX_PORT) {
				Fprintf(stderr, "%s: port number %d out of "
				    "range\n", progname, i);
				exit(EXIT_FAILURE);
			}
			dest_port = (ushort_t)i;
			break;

		case 'r':
			options |= SO_DONTROUTE;
			break;

		case 'R':
			rr_option = _B_TRUE;
			break;

		case 'S':
			send_reply = _B_TRUE;
			strict = _B_TRUE;
			break;

		case 's':
			stats = _B_TRUE;
			break;

		case 'T':
			ts_option = _B_TRUE;
			break;

		case 't':
			moptions |= MULTICAST_TTL;
			hoplimit = int_arg(optarg, "ttl");
			if (hoplimit > MAXTTL) {
				Fprintf(stderr, "%s: ttl %d out of range\n",
				    progname, hoplimit);
				exit(EXIT_FAILURE);
			}
			break;

		case 'U':
			use_udp = _B_TRUE;
			use_icmp_ts = _B_FALSE;
			break;

		case 'v':
			verbose = _B_TRUE;
			break;
		/*
		 * 'x' and 'X' has been undocumented flags for source routing.
		 * Now we document loose source routing with the new flag 'g',
		 * which is same as in traceroute. We still keep x/X as
		 * as undocumented. 'G', which is for strict source routing is
		 * also undocumented.
		 */
		case 'x':
		case 'g':
			strict = _B_FALSE;
			if (num_gw > MAXMAX_GWS) {
				Fprintf(stderr, "%s: too many gateways\n",
				    progname);
				exit(EXIT_FAILURE);
			}
			gw_list[num_gw++] = optarg;
			break;

		case 'X':
		case 'G':
			strict = _B_TRUE;
			if (num_gw > MAXMAX_GWS) {
				Fprintf(stderr, "%s: too many gateways\n",
				    progname);
				exit(EXIT_FAILURE);
			}
			gw_list[num_gw++] = optarg;
			break;

		case 'N':
			if (nexthop != NULL) {
				Fprintf(stderr, "%s: only one next hop gateway"
				    " allowed\n", progname);
				exit(EXIT_FAILURE);
			}
			nexthop = optarg;
			break;

		case 'Y':
			use_icmp_ts = _B_TRUE;
			use_udp = _B_FALSE;
			break;

		case '0':
		case '1':
		case '2':
		case '3':
			ts_flag = (char)c - '0';
			break;

		case '?':
			usage(progname);
			exit(EXIT_FAILURE);
			break;

		default:
			usage(progname);
			exit(EXIT_FAILURE);
			break;
		}
	}

	if (optind >= argc) {
		usage(progname);
		exit(EXIT_FAILURE);
	}

	/*
	 * send_reply, which sends the probe packet back to itself
	 * doesn't work with UDP
	 */
	if (use_udp)
		send_reply = _B_FALSE;

	if (getenv("MACHINE_THAT_GOES_PING") != NULL)
		stats = _B_TRUE;

	targethost = argv[optind];
	optind++;
	if (optind < argc) {
		if (stats) {
			datalen = int_arg(argv[optind], "data size");
			optind++;
			if (optind < argc) {
				npackets = int_arg(argv[optind],
				    "packet count");
				if (npackets < 1) {
					Fprintf(stderr, "%s: packet count %d "
					    "out of range\n", progname,
					    npackets);
					exit(EXIT_FAILURE);
				}
			}
		} else {
			timeout = int_arg(argv[optind], "timeout");
		}
	}

	/*
	 * Let's prepare sockaddr_in* structures, cause we might need both of
	 * them.
	 */
	bzero((char *)&to, sizeof (struct sockaddr_in));
	to.sin_family = AF_INET;

	bzero((char *)&to6, sizeof (struct sockaddr_in6));
	to6.sin6_family = AF_INET6;
	to6.sin6_flowinfo = htonl((class << 20) | flowinfo);

	if (stats)
		(void) sigset(SIGINT, finish);

	ident = (int)getpid() & 0xFFFF;

	/* resolve the hostnames */
	resolve_nodes(&ai_dst, &ai_nexthop, &src_addr_list);

	/*
	 * We should make sure datalen is reasonable.
	 *	IP_MAXPACKET >= IPv4/IPv6 header length +
	 *			IPv4 options/IPv6 routing header length +
	 *			ICMP/ICMP6/UDP header length +
	 *			datalen
	 */

	if (family_input == AF_INET6 ||
	    (family_input == AF_UNSPEC && num_v6 != 0)) {
		size_t exthdr_len = 0;

		if (send_reply) {
			exthdr_len = sizeof (struct ip6_rthdr0) +
			    2 * num_gw * sizeof (struct in6_addr);
		} else if (num_gw > 0) {
			exthdr_len = sizeof (struct ip6_rthdr0) +
			    num_gw * sizeof (struct in6_addr);
		}

		/*
		 * Size of ICMP6 header and UDP header are the same. Let's
		 * use ICMP6_MINLEN.
		 */
		if (datalen > (IP_MAXPACKET - (sizeof (struct ip6_hdr) +
		    exthdr_len + ICMP6_MINLEN))) {
			Fprintf(stderr,
			    "%s: data size too large for IPv6 packet\n",
			    progname);
			num_v6 = 0;
		}
	}

	if (family_input == AF_INET ||
	    (family_input == AF_UNSPEC && num_v4 != 0)) {
		size_t opt_len = 0;

		if (send_reply) {
			/*
			 * Includes 3 bytes code+ptr+len, the intermediate
			 * gateways, the actual and the effective target.
			 */
			opt_len = 3 +
			    (2 * num_gw + 2) * sizeof (struct in_addr);
		} else if (num_gw > 0) {
			opt_len = 3 + (num_gw + 1) * sizeof (struct in_addr);
		}

		if (rr_option) {
			opt_len = MAX_IPOPTLEN;
		} else if (ts_option) {
			if ((ts_flag & 0x0f) <= IPOPT_TS_TSANDADDR) {
				opt_len = MAX_IPOPTLEN;
			} else {
				opt_len += IPOPT_MINOFF +
				    2 * sizeof (struct ipt_ta);
				/*
				 * Note: BSD/4.X is broken in their check so we
				 * have to  bump up this number by at least one.
				 */
				opt_len++;
			}
		}

		/* Round up to 4 byte boundary */
		if (opt_len & 0x3)
			opt_len = (opt_len & ~0x3) + 4;

		if (datalen > (IP_MAXPACKET - (sizeof (struct ip) + opt_len +
		    ICMP_MINLEN))) {
			Fprintf(stderr,
			    "%s: data size too large for IPv4 packet\n",
			    progname);
			num_v4 = 0;
		}
	}

	if (num_v4 == 0 && num_v6 == 0) {
		exit(EXIT_FAILURE);
	}

	/* setup the sockets */
	if (num_v6 != 0) {
		if (!setup_socket(AF_INET6, &send_sock6, &recv_sock6,
		    &if_index, &udp_src_port6, ai_nexthop))
			exit(EXIT_FAILURE);
	}

	if (num_v4 != 0) {
		if (!setup_socket(AF_INET, &send_sock, &recv_sock, &if_index,
		    &udp_src_port, ai_nexthop))
			exit(EXIT_FAILURE);
	}

	__priv_relinquish();

	/*
	 * If sending back to ourself, add the mirror image of current
	 * gateways, so that the probes travel to and from the target
	 * by visiting the same gateways in reverse order.
	 */
	if (send_reply) {
		if (num_v6 != 0)
			mirror_gws(gw_IP_list6, AF_INET6);
		if (num_v4 != 0)
			mirror_gws(gw_IP_list, AF_INET);

		/* We add 1 because we put the target as the middle gateway */
		eff_num_gw = 2 * num_gw + 1;

	} else {
		eff_num_gw = num_gw;
	}

	targetaddr_list = build_targetaddr_list(ai_dst, src_addr_list);
	current_targetaddr = targetaddr_list;

	/*
	 * Set the starting_seq_num for the first targetaddr.
	 * If we are sending ICMP Echo Requests, the sequence number is same as
	 * ICMP sequence number, and it starts from zero. If we are sending UDP
	 * packets, the sequence number is the destination UDP port number,
	 * which starts from dest_port. At each probe, this sequence number is
	 * incremented by one.
	 * We set the starting_seq_num for first targetaddr here. The
	 * following ones will be set by looking at where we left with the last
	 * targetaddr.
	 */
	current_targetaddr->starting_seq_num = use_udp ? dest_port : 0;

	if (stats) {
		if (probe_all || !nflag) {
			Printf("PING %s: %d data bytes\n", targethost, datalen);
		} else {
			if (ai_dst->ai_family == AF_INET) {
				(void) inet_ntop(AF_INET,
				    &((struct sockaddr_in *)(void *)
				    ai_dst->ai_addr)->sin_addr,
				    abuf, sizeof (abuf));
			} else {
				(void) inet_ntop(AF_INET6,
				    &((struct sockaddr_in6 *)(void *)
				    ai_dst->ai_addr)->sin6_addr,
				    abuf, sizeof (abuf));
			}
			Printf("PING %s (%s): %d data bytes\n",
			    targethost, abuf, datalen);
		}
	}

	/* Create our timer for future use */
	if (timer_create(CLOCK_REALTIME, NULL, &timer) != 0) {
		Fprintf(stderr, "%s: failed to create timer: %s\n",
		    progname, strerror(errno));
		exit(EXIT_FAILURE);
	}

	/*
	 * Finally start up the name services warning thread.
	 */
	if (thr_create(NULL, 0, ns_warning_thr, NULL,
	    THR_DETACHED | THR_DAEMON, NULL) != 0) {
		Fprintf(stderr, "%s: failed to create name services "
		    "thread: %s\n", progname, strerror(errno));
		exit(EXIT_FAILURE);
	}

	/* Let's get things going */
	send_scheduled_probe();

	/* SIGALRM is used to send the next scheduled probe */
	(void) sigset(SIGALRM, sigalrm_handler);
	schedule_sigalrm();

	/*
	 * From now on, we'll always be listening to ICMP packets. As SIGALRM
	 * comes in, sigalrm_handler() will be invoked and send another
	 * probe.
	 */
	recv_icmp_packet(ai_dst, recv_sock6, recv_sock, udp_src_port6,
	    udp_src_port);

	return (EXIT_SUCCESS);	/* should never come here */
}

/*
 * Build the target IP address list. Use command line options and
 * name lookup results returned from name server to determine which addresses
 * to probe, how many times, in which order.
 */
static struct targetaddr *
build_targetaddr_list(struct addrinfo *ai_dst, union any_in_addr *src_addr_list)
{
	struct targetaddr *head = NULL;
	struct targetaddr *targetaddr;
	struct targetaddr **nextp;
	int num_dst;
	int i;
	struct addrinfo *aip;

	aip = ai_dst;
	if (probe_all)
		num_dst = num_v4 + num_v6;
	else
		num_dst = 1;
	num_targetaddrs = num_dst;
	nextp = &head;
	for (aip = ai_dst, i = 0; aip != NULL; aip = aip->ai_next, i++) {
		if (aip->ai_family == AF_INET && num_v4 != 0) {
			targetaddr = create_targetaddr_item(aip->ai_addr,
			    &src_addr_list[i]);
		} else if (aip->ai_family == AF_INET6 && num_v6 != 0) {
			targetaddr = create_targetaddr_item(aip->ai_addr,
			    &src_addr_list[i]);
		} else {
			continue;
		}
		*nextp = targetaddr;
		nextp = &targetaddr->next;
		if (num_targetaddrs == 1)
			break;
	}
	if (npackets == 0 && stats)
		*nextp = head;	/* keep going indefinitely */

	return (head);
}

/*
 * Given a destination sockaddr (containing address family, address, and
 * perhaps address scope) and a source address, this function creates a
 * targetaddr structure that will become part of the global targetaddr
 * list. Each targetaddr tracks the probes sent to a specific destination.
 */
static struct targetaddr *
create_targetaddr_item(struct sockaddr *dst_addr, union any_in_addr *src_addr)
{
	struct targetaddr *targetaddr;
	struct sockaddr_in *dst4 = (struct sockaddr_in *)dst_addr;
	struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)dst_addr;

	targetaddr = (struct targetaddr *)malloc(sizeof (struct targetaddr));
	if (targetaddr == NULL) {
		Fprintf(stderr, "%s: malloc %s\n", progname, strerror(errno));
		exit(EXIT_FAILURE);
	}
	targetaddr->family = dst_addr->sa_family;
	switch (dst_addr->sa_family) {
	case AF_INET:
		memset(&targetaddr->dst_addr, 0, sizeof (targetaddr->dst_addr));
		targetaddr->dst_addr.addr = dst4->sin_addr;
		targetaddr->dst_scope = 0;
		break;
	case AF_INET6:
		memset(&targetaddr->dst_addr, 0, sizeof (targetaddr->dst_addr));
		targetaddr->dst_addr.addr6 = dst6->sin6_addr;
		targetaddr->dst_scope = dst6->sin6_scope_id;

		if (if_index != 0 && targetaddr->dst_scope != 0 &&
		    if_index != targetaddr->dst_scope) {
			Fprintf(stderr, "%s: warning: conflicting scopes; using"
			    " %s\n", progname, pr_if(targetaddr->dst_scope));
		}
		break;
	}
	targetaddr->src_addr = *src_addr;
	if (stats) {
		/*
		 * npackets is only defined if we are in stats mode.
		 * npackets determines how many probes to send to each target
		 * IP address. npackets == 0 means send only 1 and move on to
		 * next target IP.
		 */
		if (npackets > 0)
			targetaddr->num_probes = npackets;
		else
			targetaddr->num_probes = 1;
	} else {
		targetaddr->num_probes = timeout;
	}
	targetaddr->num_sent = 0;
	targetaddr->got_reply = _B_FALSE;
	targetaddr->probing_done = _B_FALSE;
	targetaddr->starting_seq_num = 0; /* actual value will be set later */
	targetaddr->next = NULL;	/* actual value will be set later */

	return (targetaddr);
}

/*
 * print "unknown host" message
 */
static void
print_unknown_host_msg(const char *protocol, const char *hostname)
{
	Fprintf(stderr, "%s: unknown%s host %s\n", progname, protocol,
	    hostname);
}

/*
 * Resolve hostnames for the target host and gateways. Also, determine source
 * addresses to use for each target address.
 */
static void
resolve_nodes(struct addrinfo **ai_dstp, struct addrinfo **ai_nexthopp,
    union any_in_addr **src_addr_listp)
{
	struct addrinfo *ai_dst = NULL;
	struct addrinfo *ai_nexthop = NULL;
	struct addrinfo *aip = NULL;
	union any_in_addr *src_addr_list = NULL;
	int num_resolved_gw = 0;
	int num_resolved_gw6 = 0;

	get_hostinfo(targethost, family_input, &ai_dst);
	if (ai_dst == NULL) {
		print_unknown_host_msg("", targethost);
		exit(EXIT_FAILURE);
	}
	if (nexthop != NULL) {
		get_hostinfo(nexthop, family_input, &ai_nexthop);
		if (ai_nexthop == NULL) {
			print_unknown_host_msg("", nexthop);
			exit(EXIT_FAILURE);
		}
	}
	/* Get a count of the v4 & v6 addresses */
	for (aip = ai_dst; aip != NULL; aip = aip->ai_next) {
		switch (aip->ai_family) {
		case AF_INET:
			num_v4++;
			break;
		case AF_INET6:
			num_v6++;
			break;
		}
	}

	if (family_input == AF_UNSPEC && !probe_all) {
		family_input = ai_dst->ai_family;
	}

	/* resolve gateways */
	if (num_gw > 0) {
		get_gwaddrs(gw_list, family_input, gw_IP_list, gw_IP_list6,
		    &num_resolved_gw, &num_resolved_gw6);

		/* we couldn't resolve a gateway as an IPv6 host */
		if (num_resolved_gw6 != num_gw && num_v6 != 0 &&
		    (family_input == AF_INET6 || family_input == AF_UNSPEC)) {
			print_unknown_host_msg(" IPv6",
			    gw_list[num_resolved_gw6]);
			num_v6 = 0;
		}

		/* we couldn't resolve a gateway as an IPv4 host */
		if (num_resolved_gw != num_gw && num_v4 != 0 &&
		    (family_input == AF_INET || family_input == AF_UNSPEC)) {
			print_unknown_host_msg(" IPv4",
			    gw_list[num_resolved_gw]);
			num_v4 = 0;
		}
	}

	if (num_v4 == 0 && num_v6 == 0)
		exit(EXIT_FAILURE);

	select_all_src_addrs(&src_addr_list, ai_dst, gw_IP_list, gw_IP_list6);
	*ai_dstp = ai_dst;
	*ai_nexthopp = ai_nexthop;
	*src_addr_listp = src_addr_list;
}

/*
 * Resolve the gateway names, splitting results into v4 and v6 lists.
 * Gateway addresses are added to the appropriate passed-in array; the
 * number of resolved gateways for each af is returned in resolved[6].
 * Assumes that passed-in arrays are large enough for MAX_GWS[6] addrs
 * and resolved[6] ptrs are non-null; ignores array and counter if the
 * address family param makes them irrelevant.
 */
static void
get_gwaddrs(char **gw_list, int family, union any_in_addr *gwIPlist,
    union any_in_addr *gwIPlist6, int *resolved, int *resolved6)
{
	int i;
	boolean_t check_v4 = _B_TRUE, check_v6 = _B_TRUE;
	struct addrinfo	*ai = NULL;
	struct addrinfo	*aip = NULL;

	*resolved = *resolved6 = 0;
	switch (family) {
	case AF_UNSPEC:
		break;
	case AF_INET:
		check_v6 = _B_FALSE;
		break;
	case AF_INET6:
		check_v4 = _B_FALSE;
		break;
	default:
		return;
	}

	if (check_v4 && num_gw >= MAX_GWS) {
		check_v4 = _B_FALSE;
		Fprintf(stderr, "%s: too many IPv4 gateways\n", progname);
	}
	if (check_v6 && num_gw > MAX_GWS6) {
		check_v6 = _B_FALSE;
		Fprintf(stderr, "%s: too many IPv6 gateways\n", progname);
	}

	for (i = 0; i < num_gw; i++) {
		if (!check_v4 && !check_v6)
			return;
		get_hostinfo(gw_list[i], family, &ai);
		if (ai == NULL)
			return;
		if (check_v4 && num_v4 != 0) {
			for (aip = ai; aip != NULL; aip = aip->ai_next) {
				if (aip->ai_family == AF_INET) {
					/* LINTED E_BAD_PTR_CAST_ALIGN */
					bcopy(&((struct sockaddr_in *)
					    aip->ai_addr)->sin_addr,
					    &gwIPlist[i].addr,
					    aip->ai_addrlen);
					(*resolved)++;
					break;
				}
			}
		} else if (check_v4) {
			check_v4 = _B_FALSE;
		}
		if (check_v6 && num_v6 != 0) {
			for (aip = ai; aip != NULL; aip = aip->ai_next) {
				if (aip->ai_family == AF_INET6) {
					/* LINTED E_BAD_PTR_CAST_ALIGN */
					bcopy(&((struct sockaddr_in6 *)
					    aip->ai_addr)->sin6_addr,
					    &gwIPlist6[i].addr6,
					    aip->ai_addrlen);
					(*resolved6)++;
					break;
				}
			}
		} else if (check_v6) {
			check_v6 = _B_FALSE;
		}
	}
	freeaddrinfo(ai);
}

/*
 * Given the list of gateways, extends the list with its mirror image. This is
 * used when -l/-S is used. The middle gateway will be the target address. We'll
 * leave it blank for now.
 */
static void
mirror_gws(union any_in_addr *gwIPlist, int family)
{
	int effective_num_gw;
	int i;

	/* We add 1 because we put the target as the middle gateway */
	effective_num_gw = 2 * num_gw + 1;

	if ((family == AF_INET && effective_num_gw >= MAX_GWS) ||
	    (family == AF_INET6 && effective_num_gw > MAX_GWS6)) {
		Fprintf(stderr, "%s: too many %s gateways\n",
		    progname, (family == AF_INET) ? "IPv4" : "IPv6");
		exit(EXIT_FAILURE);
	}

	for (i = 0; i < num_gw; i++)
		gwIPlist[num_gw + i + 1].addr6 = gwIPlist[num_gw - i - 1].addr6;
}

/*
 * Given IP address or hostname, return addrinfo list.
 * Assumes that addrinfo ** ptr is non-null.
 */
static void
get_hostinfo(char *host, int family, struct addrinfo **aipp)
{
	struct addrinfo hints, *ai;
	struct in6_addr addr6;
	struct in_addr addr;
	boolean_t broadcast;		/* is this 255.255.255.255? */
	char tmp_buf[INET6_ADDRSTRLEN];
	int rc;

	/* check if broadcast */
	if (strcmp(host, "255.255.255.255") == 0)
		broadcast = _B_TRUE;
	else
		broadcast = _B_FALSE;

	/* check if IPv4-mapped address or broadcast */
	if (((inet_pton(AF_INET6, host, &addr6) > 0) &&
	    IN6_IS_ADDR_V4MAPPED(&addr6)) || broadcast) {
		if (!broadcast) {
			/*
			 * Peel off the "mapping" stuff, leaving 32 bit IPv4
			 * address.
			 */
			IN6_V4MAPPED_TO_INADDR(&addr6, &addr);

			/* convert it back to a string */
			(void) inet_ntop(AF_INET, (void *)&addr, tmp_buf,
			    sizeof (tmp_buf));
			/*
			 * Now the host is an IPv4 address.
			 * Since it previously was a v4 mapped v6 address
			 * we can be sure that the size of buffer 'host'
			 * is large enough to contain the associated v4
			 * address and so we don't need to use a strn/lcpy
			 * here.
			 */
			(void) strcpy(host, tmp_buf);
		}
		/*
		 * If it's a broadcast address, it cannot be an IPv6 address.
		 * Also, if it's a mapped address, we convert it into IPv4
		 * address because ping will send and receive IPv4 packets for
		 * that address. Therefore, it's a failure case to ask
		 * get_hostinfo() to treat a broadcast or a mapped address
		 * as an IPv6 address.
		 */
		if (family == AF_INET6) {
			return;
		}
	}

	(void) memset(&hints, 0, sizeof (hints));
	hints.ai_family = family;
	hints.ai_flags = AI_ADDRCONFIG;
	rc = getaddrinfo(host, NULL, &hints, &ai);
	if (rc != 0) {
		if (rc != EAI_NONAME)
			Fprintf(stderr, "%s: getaddrinfo: %s\n", progname,
			    gai_strerror(rc));
		return;
	}
	*aipp = ai;
}

/*
 * For each IP address of the target host, determine a source address to use.
 */
static void
select_all_src_addrs(union any_in_addr **src_addr_list, struct addrinfo *ai,
    union any_in_addr *gwv4, union any_in_addr *gwv6)
{
	union any_in_addr *list;
	struct addrinfo *aip;
	int num_dst = 1;
	int i;

	if (probe_all) {
		for (aip = ai; aip->ai_next != NULL; aip = aip->ai_next)
			num_dst++;
	}

	list = calloc((size_t)num_dst, sizeof (union any_in_addr));
	if (list == NULL) {
		Fprintf(stderr, "%s: calloc: %s\n", progname, strerror(errno));
		exit(EXIT_FAILURE);
	}

	/*
	 * If there's a gateway, a routing header as a consequence, our kernel
	 * picks the source address based on the first hop address, rather than
	 * final destination address.
	 */
	if (num_gw > 0) {
		if (ai->ai_family == AF_INET)
			select_src_addr(gwv4, ai->ai_family, &list[0]);
		else
			select_src_addr(gwv6, ai->ai_family, &list[0]);
		/*
		 * Since the first gateway address is fixed, we'll use the same
		 * src address for every different final destination address
		 * we send to.
		 */
		for (i = 1; i < num_dst; i++)
			list[i] = list[0];
	} else {
		/*
		 * Although something like 'ping -l host' results in a routing
		 * header, the first gateway address is the target host's
		 * address. Therefore, as far as src address selection goes,
		 * the result is same as having no routing header.
		 */
		for (i = 0, aip = ai; i < num_dst && aip != NULL;
		    i++, aip = aip->ai_next) {
			if (aip->ai_family == AF_INET) {
				if (num_v4 != 0) {
					select_src_addr((union any_in_addr *)
					    /* LINTED E_BAD_PTR_CAST_ALIGN */
					    &((struct sockaddr_in *)
					    aip->ai_addr)->sin_addr,
					    aip->ai_family,
					    &list[i]);
				}
			} else {
				if (num_v6 != 0) {
					select_src_addr((union any_in_addr *)
					    /* LINTED E_BAD_PTR_CAST_ALIGN */
					    &((struct sockaddr_in6 *)
					    aip->ai_addr)->sin6_addr,
					    aip->ai_family,
					    &list[i]);
				}
			}
		}
	}

	*src_addr_list = list;
}

/*
 * For a given destination address, determine a source address to use.
 * Returns wildcard address if it cannot determine the source address.
 */
static void
select_src_addr(union any_in_addr *dst_addr, int family,
    union any_in_addr *src_addr)
{
	struct sockaddr *sock;
	struct sockaddr_in *sin = NULL;
	struct sockaddr_in6 *sin6 = NULL;
	int tmp_fd;
	size_t sock_len;

	sock = (struct sockaddr *)malloc(sizeof (struct sockaddr_in6));
	if (sock == NULL) {
		Fprintf(stderr, "%s: malloc: %s\n", progname, strerror(errno));
		exit(EXIT_FAILURE);
	}
	(void) bzero(sock, sizeof (struct sockaddr_in6));

	if (family == AF_INET) {
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin = (struct sockaddr_in *)sock;
		sin->sin_family = AF_INET;
		sin->sin_addr = dst_addr->addr;
		sin->sin_port = IPPORT_ECHO;	/* port shouldn't be 0 */
		sock_len = sizeof (struct sockaddr_in);
	} else {
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin6 = (struct sockaddr_in6 *)sock;
		sin6->sin6_family = AF_INET6;
		sin6->sin6_addr = dst_addr->addr6;
		sin6->sin6_port = IPPORT_ECHO;	/* port shouldn't be 0 */
		sock_len = sizeof (struct sockaddr_in6);
	}

	/* open a UDP socket */
	if ((tmp_fd = socket(family, SOCK_DGRAM, 0)) < 0) {
		Fprintf(stderr, "%s: udp socket: %s\n", progname,
		    strerror(errno));
		exit(EXIT_FAILURE);
	}

	/* connect it */
	if (connect(tmp_fd, sock, sock_len) < 0) {
		/*
		 * If there's no route to the destination, this connect() call
		 * fails. We just return all-zero (wildcard) as the source
		 * address, so that user can get to see "no route to dest"
		 * message, as it'll try to send the probe packet out and will
		 * receive ICMP unreachable.
		 */
		if (family == AF_INET)
			src_addr->addr.s_addr = INADDR_ANY;
		else
			src_addr->addr6 = in6addr_any;
		free(sock);
		return;
	}

	/* get the local sock info */
	if (getsockname(tmp_fd, sock, &sock_len) < 0) {
		Fprintf(stderr, "%s: getsockname: %s\n", progname,
		    strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (family == AF_INET) {
		assert(sin != NULL);
		src_addr->addr = sin->sin_addr;
	} else {
		assert(sin6 != NULL);
		src_addr->addr6 = sin6->sin6_addr;
	}

	(void) close(tmp_fd);
	free(sock);
}

/*
 * Set the IP_NEXTHOP/IPV6_NEXTHOP socket option.
 * exits on failure
 */
static void
set_nexthop(int family, struct addrinfo	*ai_nexthop, int sock)
{
	if (family == AF_INET) {
		ipaddr_t nh;

		/* LINTED E_BAD_PTR_CAST_ALIGN */
		nh = ((struct sockaddr_in *)ai_nexthop->
		    ai_addr)->sin_addr.s_addr;

		/* now we need the sys_ip_config privilege */
		(void) __priv_bracket(PRIV_ON);
		if (setsockopt(sock, IPPROTO_IP, IP_NEXTHOP,
		    &nh, sizeof (ipaddr_t)) < 0) {
			if (errno == EPERM)
				Fprintf(stderr, "%s: Insufficient privilege "
				    "to specify IPv4 nexthop router.\n",
				    progname);
			else
				Fprintf(stderr, "%s: setsockopt %s\n",
				    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
		(void) __priv_bracket(PRIV_OFF);
		/* revert to non-privileged user */
	} else {
		struct sockaddr_in6 *nh;

		/* LINTED E_BAD_PTR_CAST_ALIGN */
		nh = (struct sockaddr_in6 *)ai_nexthop->
		    ai_addr;

		if (setsockopt(sock, IPPROTO_IPV6, IPV6_NEXTHOP,
		    nh, sizeof (struct sockaddr_in6)) < 0) {
			Fprintf(stderr, "%s: setsockopt %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}
}

/*
 * Setup the socket for the given address family.
 * Returns _B_TRUE on success, _B_FALSE on failure. Failure is the case when no
 * interface can be found, or the specified interface (-i) is not found. On
 * library call failures, it exit()s.
 */
static boolean_t
setup_socket(int family, int *send_sockp, int *recv_sockp, int *if_index,
    ushort_t *udp_src_port, struct addrinfo *ai_nexthop)
{
	int send_sock;
	int recv_sock;
	struct sockaddr_in6 sin6;
	struct sockaddr_in sin;
	struct sockaddr *sp;
	struct ipsec_req req;
	size_t slen;
	int on = 1;
	uchar_t char_op;
	int int_op;

	/* now we need the net_icmpaccess privilege */
	(void) __priv_bracket(PRIV_ON);

	recv_sock = socket(family, SOCK_RAW,
	    (family == AF_INET) ? IPPROTO_ICMP : IPPROTO_ICMPV6);

	if (recv_sock < 0) {
		Fprintf(stderr, "%s: socket %s\n", progname, strerror(errno));
		exit(EXIT_FAILURE);
	}

	/* revert to non-privileged user after opening sockets */
	(void) __priv_bracket(PRIV_OFF);

	if (bypass) {
		(void) memset(&req, 0, sizeof (req));
		req.ipsr_ah_req = IPSEC_PREF_NEVER;
		req.ipsr_esp_req = IPSEC_PREF_NEVER;

		if (setsockopt(recv_sock, (family == AF_INET) ? IPPROTO_IP :
		    IPPROTO_IPV6, IP_SEC_OPT, &req, sizeof (req)) < 0) {
			switch (errno) {
			case EPROTONOSUPPORT:
				/*
				 * No IPsec subsystem or policy loaded.
				 * Bypass implicitly allowed.
				 */
				break;
			case EPERM:
				Fprintf(stderr, "%s: Insufficient privilege "
				    "to bypass IPsec policy.\n", progname);
				exit(EXIT_FAILURE);
				break;
			default:
				Fprintf(stderr, "%s: setsockopt %s\n", progname,
				    strerror(errno));
				exit(EXIT_FAILURE);
				break;
			}
		}
	}

	/*
	 * We always receive on raw icmp socket. But the sending socket can be
	 * raw icmp or udp, depending on the use of -U flag.
	 */
	if (use_udp) {
		send_sock = socket(family, SOCK_DGRAM, IPPROTO_UDP);
		if (send_sock < 0) {
			Fprintf(stderr, "%s: socket %s\n", progname,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}

		if (bypass) {
			if (setsockopt(send_sock, (family == AF_INET) ?
			    IPPROTO_IP : IPPROTO_IPV6, IP_SEC_OPT, &req,
			    sizeof (req)) < 0) {
				switch (errno) {
				case EPROTONOSUPPORT:
					/*
					 * No IPsec subsystem or policy loaded.
					 * Bypass implicitly allowed.
					 */
					break;
				case EPERM:
					Fprintf(stderr, "%s: Insufficient "
					    "privilege to bypass IPsec "
					    "policy.\n", progname);
					exit(EXIT_FAILURE);
					break;
				default:
					Fprintf(stderr, "%s: setsockopt %s\n",
					    progname, strerror(errno));
					exit(EXIT_FAILURE);
					break;
				}
			}
		}

		/*
		 * In order to distinguish replies to our UDP probes from
		 * other pings', we need to know our source port number.
		 */
		if (family == AF_INET) {
			sp = (struct sockaddr *)&sin;
			slen = sizeof (sin);
		} else {
			sp = (struct sockaddr *)&sin6;
			slen = sizeof (sin6);
		}
		bzero(sp, slen);
		sp->sa_family = family;

		/* Let's bind() send_sock to wildcard address and port */
		if (bind(send_sock, sp, slen) < 0) {
			Fprintf(stderr, "%s: bind %s\n", progname,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}

		/* .... and see what port kernel picked for us */
		if (getsockname(send_sock, sp, &slen) < 0) {
			Fprintf(stderr, "%s: getsockname %s\n", progname,
			    strerror(errno));
			exit(EXIT_FAILURE);
		}
		*udp_src_port = (family == AF_INET) ? sin.sin_port :
		    sin6.sin6_port;
	} else {
		send_sock = recv_sock;
	}

	if (nexthop != NULL)
		set_nexthop(family, ai_nexthop, send_sock);

	int_op = 48 * 1024;
	if (int_op < datalen)
		int_op = datalen;
	if (setsockopt(recv_sock, SOL_SOCKET, SO_RCVBUF, (char *)&int_op,
	    sizeof (int_op)) == -1) {
		Fprintf(stderr, "%s: setsockopt SO_RCVBUF %s\n", progname,
		    strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (setsockopt(send_sock, SOL_SOCKET, SO_SNDBUF, (char *)&int_op,
	    sizeof (int_op)) == -1) {
		Fprintf(stderr, "%s: setsockopt SO_SNDBUF %s\n", progname,
		    strerror(errno));
		exit(EXIT_FAILURE);
	}

	if (options & SO_DEBUG) {
		if (setsockopt(send_sock, SOL_SOCKET, SO_DEBUG, (char *)&on,
		    sizeof (on)) == -1) {
			Fprintf(stderr, "%s: setsockopt SO_DEBUG %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	if (options & SO_DONTROUTE) {
		if (setsockopt(send_sock, SOL_SOCKET, SO_DONTROUTE, (char *)&on,
		    sizeof (on)) == -1) {
			Fprintf(stderr, "%s: setsockopt SO_DONTROUTE %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	if (moptions & MULTICAST_NOLOOP) {
		if (family == AF_INET) {
			char_op = 0;	/* used to turn off option */

			if (setsockopt(send_sock, IPPROTO_IP, IP_MULTICAST_LOOP,
			    (char *)&char_op, sizeof (char_op)) == -1) {
				Fprintf(stderr, "%s: setsockopt "
				    "IP_MULTICAST_NOLOOP %s\n", progname,
				    strerror(errno));
				exit(EXIT_FAILURE);
			}
		} else {
			int_op = 0;	/* used to turn off option */

			if (setsockopt(send_sock, IPPROTO_IPV6,
			    IPV6_MULTICAST_LOOP, (char *)&int_op,
			    sizeof (int_op)) == -1) {
				Fprintf(stderr, "%s: setsockopt "
				    "IPV6_MULTICAST_NOLOOP %s\n", progname,
				    strerror(errno));
				exit(EXIT_FAILURE);
			}
		}
	}

	if (moptions & MULTICAST_TTL) {
		char_op = hoplimit;

		/* Applies to unicast and multicast. */
		if (family == AF_INET) {
			if (setsockopt(send_sock, IPPROTO_IP, IP_MULTICAST_TTL,
			    (char *)&char_op, sizeof (char)) == -1) {
				Fprintf(stderr, "%s: setsockopt "
				    "IP_MULTICAST_TTL %s\n", progname,
				    strerror(errno));
				exit(EXIT_FAILURE);
			}
			if (setsockopt(send_sock, IPPROTO_IP, IP_TTL,
			    (char *)&hoplimit, sizeof (hoplimit)) == -1) {
				Fprintf(stderr, "%s: setsockopt IP_TTL %s\n",
				    progname, strerror(errno));
				exit(EXIT_FAILURE);
			}
		}
		/*
		 * AF_INET6 case is handled in set_ancillary_data() function.
		 * This is because when ancillary data is used (for routing
		 * header and outgoing interface index), the hoplimit set using
		 * setsockopt() is ignored.
		 */
	}

	/*
	 * did the user specify an interface?
	 * Applies to unicast, broadcast and multicast.
	 */
	if (moptions & MULTICAST_IF) {
		struct ifaddrlist *al = NULL;		/* interface list */
		struct ifaddrlist *my_if;
		char errbuf[ERRBUFSIZE];
		int num_ifs;
		int num_src_ifs;		/* exclude down and loopback */
		int i;

		/* pull out the interface list */
		num_ifs = ifaddrlist(&al, family, LIFC_UNDER_IPMP, errbuf);
		if (num_ifs == -1) {
			Fprintf(stderr, "%s: %s\n", progname, errbuf);
			exit(EXIT_FAILURE);
		}

		/* filter out down and loopback interfaces */
		num_src_ifs = 0;
		for (i = 0; i < num_ifs; i++) {
			if (!(al[i].flags & IFF_LOOPBACK) &&
			    (al[i].flags & IFF_UP))
				num_src_ifs++;
		}

		if (num_src_ifs == 0) {
			Fprintf(stderr, "%s: can't find any %s interface\n",
			    progname, (family == AF_INET) ? "IPv4" : "IPv6");

			return (_B_FALSE);	/* failure */
		}

		/* locate the specified interface */
		my_if = find_if(al, num_ifs);
		if (my_if == NULL) {
			Fprintf(stderr, "%s: %s is an invalid %s interface\n",
			    progname, out_if.str,
			    (family == AF_INET) ? "IPv4" : "IPv6");

			return (_B_FALSE);
		}

		if (family == AF_INET) {
			struct in_pktinfo pktinfo;

			if (setsockopt(send_sock, IPPROTO_IP, IP_MULTICAST_IF,
			    (char *)&my_if->addr.addr,
			    sizeof (struct in_addr)) == -1) {
				Fprintf(stderr, "%s: setsockopt "
				    "IP_MULTICAST_IF %s\n", progname,
				    strerror(errno));
				exit(EXIT_FAILURE);
			}
			bzero(&pktinfo, sizeof (pktinfo));
			pktinfo.ipi_ifindex = my_if->index;
			if (setsockopt(send_sock, IPPROTO_IP, IP_PKTINFO,
			    (char *)&pktinfo, sizeof (pktinfo)) == -1) {
				Fprintf(stderr, "%s: setsockopt "
				    "IP_PKTINFO %s\n", progname,
				    strerror(errno));
				exit(EXIT_FAILURE);
			}
		} else {
			/*
			 * the outgoing interface is set in set_ancillary_data()
			 * function
			 */
			*if_index = my_if->index;
		}

		free(al);
	}

	if (settos && family == AF_INET) {
		int_op = tos;
		if (setsockopt(send_sock, IPPROTO_IP, IP_TOS, (char *)&int_op,
		    sizeof (int_op)) == -1) {
			Fprintf(stderr, "%s: setsockopt IP_TOS %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	/* We enable or disable to not depend on the kernel default */
	if (family == AF_INET) {
		if (setsockopt(send_sock, IPPROTO_IP, IP_DONTFRAG,
		    (char *)&dontfrag, sizeof (dontfrag)) == -1) {
			Fprintf(stderr, "%s: setsockopt IP_DONTFRAG %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
	} else {
		if (setsockopt(send_sock, IPPROTO_IPV6, IPV6_DONTFRAG,
		    (char *)&dontfrag, sizeof (dontfrag)) == -1) {
			Fprintf(stderr, "%s: setsockopt IPV6_DONTFRAG %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	/* receiving IPv6 extension headers in verbose mode */
	if (verbose && family == AF_INET6) {
		if (setsockopt(recv_sock, IPPROTO_IPV6, IPV6_RECVHOPOPTS,
		    (char *)&on, sizeof (on)) == -1) {
			Fprintf(stderr, "%s: setsockopt IPV6_RECVHOPOPTS %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}

		if (setsockopt(recv_sock, IPPROTO_IPV6, IPV6_RECVDSTOPTS,
		    (char *)&on, sizeof (on)) == -1) {
			Fprintf(stderr, "%s: setsockopt IPV6_RECVDSTOPTS %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}

		if (setsockopt(recv_sock, IPPROTO_IPV6, IPV6_RECVRTHDR,
		    (char *)&on, sizeof (on)) == -1) {
			Fprintf(stderr, "%s: setsockopt IPV6_RECVRTHDR %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	/* Ensure that timestamping is requested on the receive socket */
	if (setsockopt(recv_sock, SOL_SOCKET, SO_TIMESTAMP,
	    &on, sizeof (on)) == -1) {
		Fprintf(stderr, "%s: warning: timing accuracy diminished -- "
		    "setsockopt SO_TIMESTAMP failed %s", progname,
		    strerror(errno));
	}

	*send_sockp = send_sock;
	*recv_sockp = recv_sock;

	/* successful */
	return (_B_TRUE);
}

/*
 * Pull out the record containing all the info about the interface specified by
 * `out_if'. Skips interfaces which are down or loopback.
 */
static struct ifaddrlist *
find_if(struct ifaddrlist *al, int num_ifs)
{
	static struct ifaddrlist tmp_if;
	boolean_t found;
	int i;

	i = 0;
	found = _B_FALSE;

	while (i < num_ifs && !found) {
		tmp_if = al[i];

		/* skip down or loopback interfaces */
		if ((tmp_if.flags & IFF_LOOPBACK) || !(tmp_if.flags & IFF_UP)) {
			i++;
			continue;
		}

		/* the type of interface id is variable */
		switch (out_if.id_type) {
		case IF_INDEX:
			if (out_if.id.index == tmp_if.index)
				found = _B_TRUE;
			break;

		case IF_NAME:
			if (strcmp(out_if.id.name, tmp_if.device) == 0)
				found = _B_TRUE;
			break;

		case IF_ADDR:
			if (out_if.id.addr.addr.s_addr ==
			    tmp_if.addr.addr.s_addr) {
				found = _B_TRUE;
			}
			break;

		case IF_ADDR6:
			if (IN6_ARE_ADDR_EQUAL(&out_if.id.addr.addr6,
			    &tmp_if.addr.addr6)) {
				found = _B_TRUE;
			}
			break;

		default:
			break;
		}

		i++;
	}

	if (found)
		return (&tmp_if);
	else
		return (NULL);
}

/*
 * Invoked by SIGALRM, sigalrm_handler() is, responsible for calling
 * send_scheduled_probe() to send next probe.
 */
void
sigalrm_handler(void)
{
	/*
	 * If we've been told that we're done, the timer should be cancelled
	 * and not rescheduled, just return.
	 */
	if (timer_done == _B_TRUE)
		return;

	/*
	 * Guard against denial-of-service attacks. Make sure ping doesn't send
	 * probes for every SIGALRM it receives in the case of errant SIGALRMs.
	 * ping will ignore those which are received too soon (the smaller of
	 * 0.5 sec and the ping interval, if in effect) after it sent the last
	 * probe.  We use gethrtime() instead of gettimeofday() because the
	 * latter is not linear and is prone to resetting or drifting.
	 */
	if ((gethrtime() - t_last_probe_sent) < mintime) {
		return;
	}
	send_scheduled_probe();
	schedule_sigalrm();
}

/*
 * Schedule next SIGALRM.
 */
void
schedule_sigalrm(void)
{
	int waittime;
	struct itimerspec it;

	bzero(&it, sizeof (struct itimerspec));
	if (npackets == 0 ||
	    current_targetaddr->num_sent < current_targetaddr->num_probes) {
		it = interval;
	} else {
		if (current_targetaddr->got_reply) {
			waittime = 2 * tmax / MICROSEC;
			if (waittime == 0)
				waittime = 1;
		} else {
			waittime = MAX_WAIT;
		}
		it.it_value.tv_sec = waittime;
	}

	if (timer_settime(timer, TIMER_RELTIME, &it, NULL) != 0) {
		Fprintf(stderr, "%s: unexpected error updating time: %s\n",
		    progname, strerror(errno));
		exit(EXIT_FAILURE);
	}
}

/*
 * Called by sigalrm_handler(), check_reply() or check_reply6(),
 * send_scheduled_probe() looks at the current_targetaddr and determines what
 * should be sent next and calls pinger().
 */
void
send_scheduled_probe()
{
	static struct msghdr msg6;
	static boolean_t first_probe = _B_TRUE;
	char tmp_buf[INET6_ADDRSTRLEN];

	/*
	 * We are about to move to next targetaddr if it's either we sent
	 * all the probes, or somebody set the probing_done flag to
	 * _B_TRUE prompting us to move on.
	 */
	if (current_targetaddr->num_sent == current_targetaddr->num_probes ||
	    current_targetaddr->probing_done) {
		/*
		 * is this a dead target?
		 */
		if (!stats && !current_targetaddr->got_reply) {
			if (!probe_all) {
				Printf("no answer from %s\n", targethost);
			} else {
				Printf("no answer from %s(%s)\n", targethost,
				    inet_ntop(current_targetaddr->family,
				    &current_targetaddr->dst_addr,
				    tmp_buf, sizeof (tmp_buf)));
			}
		}
		/*
		 * Before we move onto next item, let's do some clean up.
		 */
		current_targetaddr->got_reply = _B_FALSE;
		current_targetaddr->probing_done = _B_FALSE;
		/*
		 * If this is probe-all without stats mode, then we need to
		 * preserve this count. This is needed when we try to map an
		 * icmp_seq to IP address. Otherwise, clear it.
		 */
		if (stats || !probe_all)
			current_targetaddr->num_sent = 0;
		nreceived_last_target = 0;

		current_targetaddr = current_targetaddr->next;

		/*
		 * Did we reach the end of road?
		 */
		if (current_targetaddr == NULL) {
			timer_done = _B_TRUE;
			if (stats)
				finish();
			if (is_alive)
				exit(EXIT_SUCCESS);
			else
				exit(EXIT_FAILURE);
		} else {
			/*
			 * We use starting_seq_num for authenticating replies.
			 * Each time we move to a new targetaddr, which has
			 * a different target IP address, we update this field.
			 */
			current_targetaddr->starting_seq_num = use_udp ?
			    dest_port : (ntransmitted % (MAX_ICMP_SEQ + 1));
		}
	}

	if (current_targetaddr->family == AF_INET6) {
		if (send_reply) {
			/* sending back to ourself */
			to6.sin6_addr = current_targetaddr->src_addr.addr6;
		} else {
			to6.sin6_addr = current_targetaddr->dst_addr.addr6;
		}
		to6.sin6_scope_id = current_targetaddr->dst_scope;

		/*
		 * Setting the ancillary data once is enough, if we are
		 * not using source routing through target (-l/-S). In
		 * case -l/-S used, the middle gateway will be the
		 * IP address of the source, which can be different
		 * for each target IP.
		 */
		if (first_probe ||
		    (send_reply && current_targetaddr->num_sent == 0)) {
			int scope = if_index;
			if (scope != 0 && to6.sin6_scope_id != 0)
				/*
				 * don't bother setting scope in ancillary data
				 * as sin6_scope_id will override it.
				 */
				scope = 0;

			if (send_reply) {
				/* target is the middle gateway now */
				gw_IP_list6[num_gw].addr6 =
				    current_targetaddr->dst_addr.addr6;
			}
			set_ancillary_data(&msg6, hoplimit, gw_IP_list6,
			    eff_num_gw, scope);
			first_probe = _B_FALSE;
		}
		pinger(send_sock6, (struct sockaddr *)&to6, &msg6, AF_INET6);
	} else {
		to.sin_addr = current_targetaddr->dst_addr.addr;
		/*
		 * Set IPv4 options when sending the first probe to a target
		 * IP address. Some options change when the target address
		 * changes.
		 */
		if (current_targetaddr->num_sent == 0) {
			if (eff_num_gw > 0) {
				gw_IP_list[num_gw].addr =
				    current_targetaddr->dst_addr.addr;
				/*
				 * If send_reply, the target becomes the
				 * middle gateway, sender becomes the last
				 * gateway.
				 */
				if (send_reply) {
					gw_IP_list[eff_num_gw].addr =
					    current_targetaddr->src_addr.addr;
				}
			}
			/*
			 * In IPv4, if source routing is used, the target
			 * address shows up as the last gateway, hence +1.
			 */
			set_IPv4_options(send_sock, gw_IP_list,
			    (eff_num_gw > 0) ? eff_num_gw + 1 : 0,
			    &current_targetaddr->src_addr.addr, &to.sin_addr);
		}
		pinger(send_sock, (struct sockaddr *)&to, NULL, AF_INET);
	}

	current_targetaddr->num_sent++;
}

/*
 * recv_icmp_packet()'s job is to listen to icmp packets and filter out
 * those ping is interested in.
 */
static void
recv_icmp_packet(struct addrinfo *ai_dst, int recv_sock6, int recv_sock,
    ushort_t udp_src_port6, ushort_t udp_src_port)
{
	struct msghdr in_msg;
	struct iovec iov;
	struct sockaddr_in6 from6;
	fd_set fds;
	int result;
	int cc;
	boolean_t always_true = _B_TRUE; /* lint doesn't like while(_B_TRUE) */

	while (always_true) {
		(void) FD_ZERO(&fds);
		if (recv_sock6 != -1)
			FD_SET(recv_sock6, &fds);
		if (recv_sock != -1)
			FD_SET(recv_sock, &fds);

		result = select(MAX(recv_sock6, recv_sock) + 1, &fds,
		    (fd_set *)NULL, (fd_set *)NULL, (struct timeval *)NULL);
		if (result == -1) {
			if (errno == EINTR) {
				continue;
			} else {
				Fprintf(stderr, "%s: select %s\n", progname,
				    strerror(errno));
				exit(EXIT_FAILURE);
			}
		} else if (result > 0) {
			in_msg.msg_name = &from6;
			in_msg.msg_namelen = sizeof (from6);
			iov.iov_base = in_pkt;
			iov.iov_len = sizeof (in_pkt);
			in_msg.msg_iov = &iov;
			in_msg.msg_iovlen = 1;
			in_msg.msg_control = ancillary_data;
			in_msg.msg_controllen = sizeof (ancillary_data);

			/* Do we have an ICMP6 packet waiting? */
			if ((recv_sock6 != -1) &&
			    (FD_ISSET(recv_sock6, &fds))) {
				cc = recvmsg(recv_sock6, &in_msg, 0);
				if (cc < 0) {
					if (errno != EINTR) {
						Fprintf(stderr,
						    "%s: recvmsg %s\n",
						    progname, strerror(errno));
					}
					continue;
				} else if (cc > 0) {
					check_reply6(ai_dst, &in_msg, cc,
					    udp_src_port6);
				}
			}
			/* Do we have an ICMP packet waiting? */
			if ((recv_sock != -1) && (FD_ISSET(recv_sock, &fds))) {
				cc = recvmsg(recv_sock, &in_msg, 0);
				if (cc < 0) {
					if (errno != EINTR) {
						Fprintf(stderr,
						    "%s: recvmsg %s\n",
						    progname, strerror(errno));
					}
					continue;
				} else if (cc > 0) {
					check_reply(ai_dst, &in_msg, cc,
					    udp_src_port);
				}
			}
		}
		/*
		 * If we were probing last IP address of the target host and
		 * received a reply for each probe sent to this address,
		 * then we are done!
		 */
		if ((npackets > 0) && (current_targetaddr->next == NULL) &&
		    (nreceived_last_target == npackets)) {
			timer_done = _B_TRUE;
			finish();
		}
	} /* infinite loop */
}

/*
 * Given a host (with possibly multiple IP addresses) and an IP address, this
 * function determines if this IP address is one of the host's addresses to
 * which we're sending probes. Used to determine if we are interested in a
 * packet.
 */
boolean_t
is_a_target(struct addrinfo *ai, union any_in_addr *addr)
{
	int num_addrs;
	int i;
	struct addrinfo *aip;

	aip = ai;
	if (probe_all)
		num_addrs = num_v4 + num_v6;
	else
		num_addrs = 1;
	for (i = 0; i < num_addrs && aip != NULL; i++) {
		if (aip->ai_family == AF_INET6) {
			/* LINTED E_BAD_PTR_CAST_ALIGN */
			if (IN6_ARE_ADDR_EQUAL(&((struct sockaddr_in6 *)
			    aip->ai_addr)->sin6_addr, &addr->addr6))
				return (_B_TRUE);
		} else {
			/* LINTED E_BAD_PTR_CAST_ALIGN */
			if (((struct sockaddr_in *)
			    aip->ai_addr)->sin_addr.s_addr == addr->addr.s_addr)
				return (_B_TRUE);
		}
	}

	return (_B_FALSE);
}

/*
 * Compose and transmit an ICMP ECHO REQUEST packet.  The IP packet
 * will be added on by the kernel.  The ID field is our UNIX process ID,
 * and the sequence number is an ascending integer.  The first 8 bytes
 * of the data portion are used to hold a UNIX "timeval" struct in network
 * byte-order, to compute the round-trip time.
 */
static void
pinger(int send_sock, struct sockaddr *whereto, struct msghdr *msg6,
    int family)
{
	static uint64_t out_pkt_buf[(IP_MAXPACKET + 1) / 8];
	uchar_t *out_pkt = (uchar_t *)&out_pkt_buf;
	/* LINTED E_BAD_PTR_CAST_ALIGN */
	struct icmp *icp = (struct icmp *)out_pkt;
	/* LINTED E_BAD_PTR_CAST_ALIGN */
	struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)whereto;
	/* LINTED E_BAD_PTR_CAST_ALIGN */
	struct sockaddr_in *to = (struct sockaddr_in *)whereto;
	struct timeval *tp;
	struct timeval t_snd;
	uchar_t *datap;
	struct iovec iov;
	int start = 0;
	int cc;
	int i;

	/* using UDP? */
	if (use_udp) {
		cc = datalen;

		/* LINTED E_BAD_PTR_CAST_ALIGN */
		tp = (struct timeval *)out_pkt;
		datap = &out_pkt[sizeof (struct timeval)];

		/*
		 * This sets the port whether we are handling a v4 or v6
		 * sockaddr structure.
		 */
		to->sin_port = htons(dest_port);

		dest_port = (dest_port + 1) % (MAX_PORT + 1);
		ntransmitted++;
	} else {	/* using ICMP */
		cc = datalen + ICMP_MINLEN;

		if (family == AF_INET6) {
			icp->icmp_type = send_reply ?
			    ICMP6_ECHO_REPLY : ICMP6_ECHO_REQUEST;
		} else if (use_icmp_ts) {	/* family is AF_INET */
			icp->icmp_type = send_reply ?
			    ICMP_TSTAMPREPLY : ICMP_TSTAMP;
		} else {
			icp->icmp_type = send_reply ?
			    ICMP_ECHOREPLY : ICMP_ECHO;
		}

		icp->icmp_code = 0;
		icp->icmp_cksum = 0;
		icp->icmp_seq = htons(ntransmitted++ % (MAX_ICMP_SEQ + 1));
		if (icp->icmp_seq == 0)
			num_wraps++;
		icp->icmp_id = htons(ident);		/* ID */

		/* LINTED E_BAD_PTR_CAST_ALIGN */
		tp = (struct timeval *)&out_pkt[ICMP_MINLEN];
		datap = &out_pkt[ICMP_MINLEN + sizeof (struct timeval)];
	}

	start = sizeof (struct timeval);	/* skip for time */

	(void) gettimeofday(&t_snd, (struct timezone *)NULL);

	/* if packet is big enough to store timeval OR ... */
	if ((datalen >= sizeof (struct timeval)) ||
	    (family == AF_INET && use_icmp_ts))
		*tp = t_snd;

	if (family == AF_INET && use_icmp_ts) {
		start = sizeof (struct id_ts);	/* skip for ICMP timestamps */
		/* Number of milliseconds since midnight */
		icp->icmp_otime = htonl((tp->tv_sec % (24*60*60)) * 1000 +
		    tp->tv_usec / 1000);
	}

	for (i = start; i < datalen; i++)
		*datap++ = i;

	if (family == AF_INET) {
		if (!use_udp)
			icp->icmp_cksum = in_cksum((ushort_t *)icp, cc);

		i = sendto(send_sock, (char *)out_pkt, cc, 0, whereto,
		    sizeof (struct sockaddr_in));
	} else {
		/*
		 * Fill in the rest of the msghdr structure. msg_control is set
		 * in set_ancillary_data().
		 */
		msg6->msg_name = to6;
		msg6->msg_namelen = sizeof (struct sockaddr_in6);

		iov.iov_base = out_pkt;
		iov.iov_len = cc;

		msg6->msg_iov = &iov;
		msg6->msg_iovlen = 1;

		i = sendmsg(send_sock, msg6, 0);
	}

	/* This is a more precise time (right after we send the packet) */
	t_last_probe_sent = gethrtime();

	if (i < 0 || i != cc)  {
		if (i < 0) {
			Fprintf(stderr, "%s: sendto %s\n", progname,
			    strerror(errno));
			if (!stats)
				exit(EXIT_FAILURE);
		}
		Printf("ping: wrote %s %d chars, ret=%d\n",
		    targethost, cc, i);
		(void) fflush(stdout);
	}
}

/*
 * Return a hostname for the given IP address.
 */
char *
pr_name(char *addr, int family)
{
	struct sockaddr_in sin;
	struct sockaddr_in6 sin6;
	struct sockaddr *sa;

	switch (family) {
	case AF_INET:
		(void) memset(&sin, 0, sizeof (sin));
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin.sin_addr = *(struct in_addr *)addr;
		sin.sin_port = 0;
		sa = (struct sockaddr *)&sin;
		break;
	case AF_INET6:
		(void) memset(&sin6, 0, sizeof (sin6));
		/* LINTED E_BAD_PTR_CAST_ALIGN */
		sin6.sin6_addr = *(struct in6_addr *)addr;
		sin6.sin6_port = 0;
		sa = (struct sockaddr *)&sin6;
		break;
	default:
		sa = (struct sockaddr *)&sin6;
		break;
	}
	sa->sa_family = family;
	return (pr_name_sa(sa));
}

char *
pr_name_sa(const struct sockaddr *sa)
{
	const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
	const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
	int family = sa->sa_family;
	static struct in6_addr prev_addr = IN6ADDR_ANY_INIT;
	static int prev_scope = 0;
	char *cp;
	char abuf[INET6_ADDRSTRLEN];
	static char buf[NI_MAXHOST + INET6_ADDRSTRLEN + 3];
	uint_t slen, alen, hlen;
	char *addr;
	int scope;

	switch (family) {
	case AF_INET:
		slen = sizeof (struct sockaddr_in);
		alen = sizeof (struct in_addr);
		addr = (char *)&sin->sin_addr;
		scope = 0;
		break;
	case AF_INET6:
		slen = sizeof (struct sockaddr_in6);
		alen = sizeof (struct in6_addr);
		addr = (char *)&sin6->sin6_addr;
		scope = sin6->sin6_scope_id;
		break;
	default:
		(void) snprintf(buf, sizeof (buf), "<invalid address family>");
		return (buf);
	}

	/* compare with the buffered (previous) lookup */
	if (scope != prev_scope || memcmp(addr, &prev_addr, alen) != 0) {
		int flags = (nflag) ? NI_NUMERICHOST : NI_NAMEREQD;
		mutex_enter(&ns_lock);
		ns_active = _B_TRUE;
		ns_starttime = gethrtime();
		mutex_exit(&ns_lock);
		if (getnameinfo(sa, slen, buf, sizeof (buf),
		    NULL, 0, flags) != 0) {
			/* getnameinfo() failed; return just the address */
			if (getnameinfo(sa, slen, buf, sizeof (buf),
			    NULL, 0, NI_NUMERICHOST) != 0) {
				buf[0] = 0;
			}
		} else if (!nflag) {
			/* append numeric address to hostname string */
			hlen = strlen(buf);
			cp = (char *)(buf + hlen);
			(void) snprintf(cp, sizeof (buf) - hlen, " (%s)",
			    inet_ntop(family, (const void *)addr, abuf,
			    sizeof (abuf)));
		}
		mutex_enter(&ns_lock);
		ns_active = _B_FALSE;
		mutex_exit(&ns_lock);

		/* LINTED E_BAD_PTR_CAST_ALIGN */
		prev_addr = *(struct in6_addr *)addr;
		prev_scope = scope;
	}
	return (buf);
}

char *
pr_name4(const struct sockaddr_in *sin)
{
	return (pr_name_sa((const struct sockaddr *)sin));
}

char *
pr_name6(const struct sockaddr_in6 *sin6)
{
	return (pr_name_sa((const struct sockaddr *)sin6));
}

/*
 * Return the protocol string, given its protocol number.
 */
char *
pr_protocol(int prot)
{
	static char buf[20];

	switch (prot) {
	case IPPROTO_ICMPV6:
		(void) strlcpy(buf, "icmp6", sizeof (buf));
		break;

	case IPPROTO_ICMP:
		(void) strlcpy(buf, "icmp", sizeof (buf));
		break;

	case IPPROTO_TCP:
		(void) strlcpy(buf, "tcp", sizeof (buf));
		break;

	case IPPROTO_UDP:
		(void) strlcpy(buf, "udp", sizeof (buf));
		break;

	default:
		(void) snprintf(buf, sizeof (buf), "prot %d", prot);
		break;
	}

	return (buf);
}

char *
pr_if(int ifindex)
{
	static struct ifaddrlist *al = NULL;
	static int count = 0;
	static char errbuf[ERRBUFSIZE];
	int i;

	if (al == NULL) {
		count = ifaddrlist(&al, AF_INET6, 0, errbuf);
		if (count < 0)
			count = 0;
	}
	for (i = 0; i < count; i++) {
		if (al[i].index == ifindex)
			return (al[i].device);
	}
	(void) sprintf(errbuf, "%d", ifindex);
	return (errbuf);
}

/*
 * Checks if value is between seq_begin and seq_begin+seq_len. Note that
 * sequence numbers wrap around after MAX_ICMP_SEQ (== MAX_PORT).
 */
boolean_t
seq_match(ushort_t seq_begin, int seq_len, ushort_t value)
{
	/*
	 * If seq_len is too big, like some value greater than MAX_ICMP_SEQ/2,
	 * truncate it down to MAX_ICMP_SEQ/2. We are not going to accept any
	 * reply which come 83hr later!
	 */
	if (seq_len > MAX_ICMP_SEQ / 2) {
		seq_begin = (seq_begin + seq_len - MAX_ICMP_SEQ / 2) %
		    (MAX_ICMP_SEQ + 1);
		seq_len = MAX_ICMP_SEQ / 2;
	}

	if (PINGSEQ_LEQ(seq_begin, value) &&
	    PINGSEQ_LEQ(value, (seq_begin + seq_len - 1) % (MAX_ICMP_SEQ + 1)))
		return (_B_TRUE);
	else
		return (_B_FALSE);
}

/*
 * For a given icmp_seq, find which destination address we must have sent this
 * to.
 */
void
find_dstaddr(ushort_t icmpseq, union any_in_addr *ipaddr)
{
	struct targetaddr *target = targetaddr_list;
	int real_seq;
	int targetaddr_index;
	int real_npackets;
	int i;

	ipaddr->addr6 = in6addr_any;

	/*
	 * If this is probe_all and not stats, then the number of probes sent to
	 * each IP address may be different (remember, we stop sending to one IP
	 * address as soon as it replies). They are stored in target->num_sent
	 * field. Since we don't wrap around the list (!stats), they are also
	 * preserved.
	 */
	if (probe_all && !stats) {
		do {
			if (seq_match(target->starting_seq_num,
			    target->num_sent, icmpseq)) {
				ipaddr->addr6 = target->dst_addr.addr6;
				/*
				 * We are not immediately return()ing here.
				 * Because of wrapping, we might find another
				 * match later, which is more likely to be the
				 * real one.
				 */
			}
			target = target->next;
		} while (target != NULL);
	} else {
		/*
		 * Find the absolute (non-wrapped) seq number within the last
		 * 64K
		 */
		if (icmpseq < (ntransmitted % (MAX_ICMP_SEQ + 1))) {
			real_seq = num_wraps * (MAX_ICMP_SEQ + 1) + icmpseq;
		} else {
			real_seq = (num_wraps - 1) * (MAX_ICMP_SEQ + 1) +
			    icmpseq;
		}

		/* Make sure it's non-negative */
		if (real_seq < 0)
			return;
		real_npackets = (npackets == 0) ? 1 : npackets;

		/*
		 * We sent npackets many packets to each of those
		 * num_targetaddrs many IP addresses.
		 */
		targetaddr_index =
		    (real_seq % (num_targetaddrs * real_npackets)) /
		    real_npackets;
		for (i = 0; i < targetaddr_index; i++)
			target = target->next;
		ipaddr->addr6 = target->dst_addr.addr6;
	}
}

/*
 * Checksum routine for Internet Protocol family headers (C Version)
 */
static ushort_t
in_cksum(ushort_t *addr, int len)
{
	int nleft = len;
	ushort_t *w = addr;
	ushort_t answer;
	ushort_t odd_byte = 0;
	int sum = 0;

	/*
	 *  Our algorithm is simple, using a 32 bit accumulator (sum),
	 *  we add sequential 16 bit words to it, and at the end, fold
	 *  back all the carry bits from the top 16 bits into the lower
	 *  16 bits.
	 */
	while (nleft > 1) {
		sum += *w++;
		nleft -= 2;
	}

	/* mop up an odd byte, if necessary */
	if (nleft == 1) {
		*(uchar_t *)(&odd_byte) = *(uchar_t *)w;
		sum += odd_byte;
	}

	/*
	 * add back carry outs from top 16 bits to low 16 bits
	 */
	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
	sum += (sum >> 16);			/* add carry */
	answer = ~sum;				/* truncate to 16 bits */
	return (answer);
}

/*
 * Subtract 2 timeval structs:  out = out - in.
 * Out is assumed to be >= in.
 */
void
tvsub(struct timeval *out, struct timeval *in)
{
	if ((out->tv_usec -= in->tv_usec) < 0) {
		out->tv_sec--;
		out->tv_usec += 1000000;
	}
	out->tv_sec -= in->tv_sec;
}

/*
 * Print out statistics, and give up.
 * Heavily buffered STDIO is used here, so that all the statistics
 * will be written with 1 sys-write call.  This is nice when more
 * than one copy of the program is running on a terminal;  it prevents
 * the statistics output from becoming intermingled.
 */
static void
finish()
{
	Printf("\n----%s PING Statistics----\n", targethost);
	Printf("%d packets transmitted, ", ntransmitted);
	Printf("%d packets received, ", nreceived);
	if (ntransmitted) {
		if (nreceived <= ntransmitted) {
			Printf("%d%% packet loss",
			    (int)(((ntransmitted-nreceived)*100) /
			    ntransmitted));
		} else {
			Printf("%.2f times amplification",
			    (double)nreceived / (double)ntransmitted);
		}
	}
	(void) putchar('\n');

	/* if packet is big enough to store timeval AND ... */
	if ((datalen >= sizeof (struct timeval)) && (nreceived > 0)) {
		double mean = (double)tsum / nreceived;
		double smean = (double)tsum2 / nreceived;
		double sd =
		    sqrt(((smean - mean*mean) * nreceived) / (nreceived-1));

		Printf("round-trip (ms)  min/avg/max/stddev = "
		    TIMEFORMAT "/" TIMEFORMAT "/"
		    TIMEFORMAT "/" TIMEFORMAT "\n",
		    (double)tmin / 1000, mean / 1000,
		    (double)tmax / 1000, sd / 1000);
	}
	(void) fflush(stdout);

	exit(is_alive ? EXIT_SUCCESS : EXIT_FAILURE);
}

/*
 * print the usage line
 */
static void
usage(char *cmdname)
{
	Fprintf(stderr, "usage: %s host [timeout]\n", cmdname);
	Fprintf(stderr,
/* CSTYLED */
"usage: %s -s [-l | -U] [-abdDLnRrv] [-A addr_family] [-c traffic_class]\n\t"
"[-g gateway [-g gateway ...]] [-N nexthop] [-F flow_label] [-I interval]\n\t"
"[-i interface] [-P tos] [-p port] [-t ttl] host [data_size] [npackets]\n",
	    cmdname);
}

/*
 * Parse integer argument; exit with an error if it's not a number.
 * Now it also accepts hex. values.
 */
static int
int_arg(char *s, char *what)
{
	char *cp;
	char *ep;
	int num;

	errno = 0;
	if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
		cp = s + 2;
		num = (int)strtol(cp, &ep, 16);
	} else {
		num = (int)strtol(s, &ep, 10);
	}

	if (errno || *ep != '\0' || num < 0) {
		Fprintf(stderr, "%s: bad %s: %s\n", progname, what, s);
		exit(EXIT_FAILURE);
	}

	return (num);
}

/*
 * Parse the interval into a itimerspec. The interval used to originally be
 * parsed as an integer argument. That means that one used to be able to specify
 * an interval in hex. The strtod() family honors that at times, with strtod
 * sometimes doing so depending on the compilation environment and strtof() and
 * srtold() always doing that. To facilitiate that and not worry about a
 * careless Makefile change breaking us, we instead just use strtold here, even
 * though we really don't need the precision.
 */
static void
parse_interval(const char *s)
{
	long double val;
	char *end;

	errno = 0;
	val = strtold(s, &end);
	if (errno != 0 || *end != '\0') {
		Fprintf(stderr, "%s: bad interval: %s\n", progname, s);
		exit(EXIT_FAILURE);
	}

	/*
	 * Check values that we know are going to be bad. Anything greater than
	 * INT_MAX, anything less than 0, look for specific NaNs. Also, clamp
	 * the value at 0.01 seconds.
	 */
	if (val == NAN || val <= 0.0 || val >= INT_MAX) {
		Fprintf(stderr, "%s: bad interval: %s\n", progname, s);
		exit(EXIT_FAILURE);
	}

	if (val < 0.01L) {
		Fprintf(stderr, "%s: interval too small: %Lf\n", progname, val);
		exit(EXIT_FAILURE);
	}

	interval.it_value.tv_sec = (long)val;
	interval.it_value.tv_nsec = (long)((val - interval.it_value.tv_sec) *
	    NANOSEC);

	if (interval.it_value.tv_sec == 0 &&
	    interval.it_value.tv_nsec < mintime) {
		mintime = interval.it_value.tv_nsec;
	}
}

/*
 * We should have an SO_TIMESTAMP message for this socket to indicate
 * the actual time that the message took. If we don't we'll fall back to
 * gettimeofday(); however, that can cause any delays due to DNS
 * resolution and the like to end up wreaking havoc on us.
 */
void
ping_gettime(struct msghdr *msg, struct timeval *tv)
{
	struct cmsghdr *cmsg;

	for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
	    cmsg = CMSG_NXTHDR(msg, cmsg)) {
		if (cmsg->cmsg_level == SOL_SOCKET &&
		    cmsg->cmsg_type == SO_TIMESTAMP &&
		    cmsg->cmsg_len == CMSG_LEN(sizeof (*tv))) {
			bcopy(CMSG_DATA(cmsg), tv, sizeof (*tv));
			return;
		}
	}

	(void) gettimeofday(tv, (struct timezone *)NULL);
}

/*
 * The purpose of this thread is to try and inform a user that we're blocked
 * doing name lookups. For various reasons, ping has to try and look up the IP
 * addresses it receives via name services unless the -n flag is specified. The
 * irony of this is that when trying to use ping to actually diagnose a broken
 * network, name services are unlikely to be available and that will result in a
 * lot of confusion as to why pings seem like they're not working. As such, we
 * basically wake up every 2 seconds and check whether or not we've hit such a
 * condition where we should inform the user via stderr.
 *
 * Once they've been informed, we do not inform them again until approximately a
 * minute of time has passed, in case that things are working intermittently.
 */
/*ARGSUSED*/
static void *
ns_warning_thr(void *unused)
{
	for (;;) {
		hrtime_t now;

		(void) sleep(ns_sleeptime);
		now = gethrtime();
		mutex_enter(&ns_lock);
		if (ns_active == _B_TRUE &&
		    now - ns_starttime >= ns_warntime * NANOSEC) {
			Fprintf(stderr, "%s: warning: ICMP responses "
			    "received, but name service lookups are "
			    "taking a while. Use ping -n to disable "
			    "name service lookups.\n",
			    progname);
			mutex_exit(&ns_lock);
			return (NULL);
		}
		mutex_exit(&ns_lock);
	}

	/* LINTED: E_STMT_NOT_REACHED */
	return (NULL);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */
/*
 * Copyright 2024 Bill Sommerfeld <sommerfeld@hamachi.org>
 */


#ifndef _PING_H
#define	_PING_H

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>

#ifdef __cplusplus
extern "C" {
#endif

#define	MAX_PORT	65535   /* max port number for UDP probes */
#define	MAX_ICMP_SEQ	65535   /* max icmp sequence value */

/*
 * Maximum number of source route space. Please note that because of the API,
 * we can only specify 8 gateways, the last address has to be the target
 * address.
 */
#define	MAX_GWS		9

/*
 * This is the max it can be. But another limiting factor is the PMTU,
 * so in any instance, it can be less than 127.
 */
#define	MAX_GWS6	127

/* maximum of above two */
#define	MAXMAX_GWS	MAX(MAX_GWS, MAX_GWS6)

/* size of buffer to store the IPv4 gateway addresses */
#define	ROUTE_SIZE	(IPOPT_OLEN + IPOPT_OFFSET + \
			MAX_GWS * sizeof (struct in_addr))

#define	A_CNT(ARRAY) (sizeof (ARRAY) / sizeof ((ARRAY)[0]))


#define	Printf (void) printf
#define	Fprintf (void) fprintf

#define	TIMEFORMAT "%#.3f"


/*
 * For each target IP address we are going to probe, we store required info,
 * such as address family, IP address of target, source IP address to use
 * for that target address, and number of probes to send in the targetaddr
 * structure.
 * All target addresses are also linked to each other and used in
 * scheduling probes. Each targetaddr structure identifies a batch of probes to
 * send : where to send, how many to send. We capture state information, such as
 * number of probes already sent (in this batch only), whether target replied
 * as we probe it, whether we are done with probing this address (can happen
 * in regular (!stats) mode when we get a reply for a probe sent in current
 * batch), and starting sequence number which is used together with number of
 * probes sent to determine if the incoming reply is for a probe we sent in
 * current batch.
 */
struct targetaddr {
	int family;
	union any_in_addr dst_addr;	/* dst address for the probe */
	union any_in_addr src_addr;	/* src addr to use for this dst addr */
	int dst_scope;			/* scope of dst addr or zero */
	int num_probes;			/* num of probes to send to this dst */
	int num_sent;			/* number of probes already sent */
	boolean_t got_reply;		/* received a reply from dst while */
					/* still probing it */
	boolean_t probing_done;		/* skip without sending all probes */
	ushort_t starting_seq_num;	/* initial icmp_seq/UDP port, used */
					/* for authenticating replies */
	struct targetaddr *next;	/* next targetaddr item in the list */
};

struct hostinfo {
	char *name;			/* hostname */
	int family;			/* address family */
	int num_addr;			/* number of addresses */
	union any_in_addr *addrs;	/* address list */
};

struct icmptype_table {
	int type;		/* ICMP type */
	char *message;		/* corresponding string message */
};

extern struct targetaddr *current_targetaddr;
extern int nreceived;
extern int nreceived_last_target;
extern int npackets;
extern boolean_t is_alive;
extern int datalen;
extern boolean_t nflag;
extern int ident;
extern boolean_t probe_all;
extern char *progname;
extern boolean_t rr_option;
extern boolean_t stats;
extern boolean_t strict;
extern char *targethost;
extern long long tmax;
extern long long tmin;
extern int ts_flag;
extern boolean_t ts_option;
extern int64_t tsum;
extern int64_t tsum2;
extern boolean_t use_icmp_ts;
extern boolean_t use_udp;
extern boolean_t verbose;
extern boolean_t send_reply;

extern void ping_gettime(struct msghdr *, struct timeval *);
extern void set_ancillary_data(struct msghdr *, int, union any_in_addr *,
    int, uint_t);
extern void check_reply(struct addrinfo *, struct msghdr *, int, ushort_t);
extern void check_reply6(struct addrinfo *, struct msghdr *, int, ushort_t);
extern void find_dstaddr(ushort_t, union any_in_addr *);
extern boolean_t is_a_target(struct addrinfo *, union any_in_addr *);
extern char *pr_if(int);
extern char *pr_name(char *, int);
extern char *pr_name_sa(const struct sockaddr *);
extern char *pr_name4(const struct sockaddr_in *);
extern char *pr_name6(const struct sockaddr_in6 *);
extern char *pr_protocol(int);
extern void schedule_sigalrm(void);
extern void send_scheduled_probe(void);
extern boolean_t seq_match(ushort_t, int, ushort_t);
extern void set_IPv4_options(int, union any_in_addr *, int, struct in_addr *,
    struct in_addr *);
extern void sigalrm_handler();
extern void tvsub(struct timeval *, struct timeval *);
#ifdef __cplusplus
}
#endif

#endif /* _PING_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved	*/

/*
 * Copyright 2015, Joyent, Inc.
 * Copyright 2024 Bill Sommerfeld <sommerfeld@hamachi.org>
 */

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

#include <sys/time.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stropts.h>
#include <sys/file.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/udp.h>
#include <netdb.h>
#include <stdlib.h>

#include <libinetutil.h>
#include "ping.h"


/*
 * IPv4 source routing option.
 * In order to avoid padding for the alignment of IPv4 addresses, ipsr_addrs
 * is defined as a 2-D array of uint8_t, instead of 1-D array of struct in_addr.
 */
struct ip_sourceroute {
	uint8_t ipsr_code;
	uint8_t ipsr_len;
	uint8_t ipsr_ptr;
	/* up to 9 IPv4 addresses */
	uint8_t ipsr_addrs[1][sizeof (struct in_addr)];
};

static void pr_options(uchar_t *, int);
static void pr_rropt(uchar_t *, int, boolean_t);
static void pr_tsopt(uchar_t *, int);
static char *pr_type(int);

/*
 * Set IPv4 options
 */
void
set_IPv4_options(int sock, union any_in_addr *gw_IP_list, int gw_count,
    struct in_addr *src, struct in_addr *dst)
{
	int req_size;
	char srr[ROUTE_SIZE + 1];
	char *bufp;
	int optsize = ROUTE_SIZE;
	struct ip_sourceroute *srp;
	struct ip_timestamp *tsp;
	int i;

	if (rr_option || ts_option || gw_count > 0) {
		bzero(srr, sizeof (srr));
		bufp = srr;

		if (gw_count > 0) {
			/* 3 = 1 (code) + 1 (len) + 1 (ptr) of src route opt. */
			req_size = 3 + (sizeof (struct in_addr)) * gw_count;

			if (optsize < req_size) {
				Fprintf(stderr, "%s: too many IPv4 gateways\n",
				    progname);
				exit(EXIT_FAILURE);
			}

			srp = (struct ip_sourceroute *)bufp;
			srp->ipsr_code = strict ? IPOPT_SSRR : IPOPT_LSRR;
			srp->ipsr_len = req_size;
			srp->ipsr_ptr = IPOPT_MINOFF;

			for (i = 0; i < gw_count; i++) {
				bcopy((char *)&gw_IP_list[i].addr,
				    &srp->ipsr_addrs[i],
				    sizeof (struct in_addr));
			}
			optsize -= srp->ipsr_len;
			bufp += srp->ipsr_len;
		}
		/* do we send a timestamp option? */
		if (ts_option) {
			if (optsize < IPOPT_MINOFF) {
				Fprintf(stderr,
				    "%s: no room for timestamp option\n",
				    progname);
				exit(EXIT_FAILURE);
			}
			/* LINTED */
			tsp = (struct ip_timestamp *)bufp;
			tsp->ipt_code = IPOPT_TS;
			tsp->ipt_len = optsize;
			tsp->ipt_ptr = IPOPT_MINOFF + 1;
			tsp->ipt_flg = ts_flag & 0x0f;

			if (tsp->ipt_flg > IPOPT_TS_TSANDADDR) {
				req_size = IPOPT_MINOFF +
				    2 * sizeof (struct ipt_ta);
				/*
				 * Note: BSD/4.X is broken in their check so we
				 * have to  bump up this number by at least one.
				 */
				req_size++;

				if (optsize < req_size) {
					Fprintf(stderr, "%s: no room for "
					    "timestamp option\n", progname);
					exit(EXIT_FAILURE);
				}

				bcopy((char *)dst,
				    &tsp->ipt_timestamp.ipt_ta[0].ipt_addr,
				    sizeof (struct in_addr));

				bcopy((char *)src,
				    &tsp->ipt_timestamp.ipt_ta[1].ipt_addr,
				    sizeof (struct in_addr));
				tsp->ipt_len = req_size;

			}
			optsize -= tsp->ipt_len;
			bufp += tsp->ipt_len;
		}
		/* do we send a record route option? */
		if (rr_option) {
			if (optsize < IPOPT_MINOFF) {
				Fprintf(stderr,
				    "%s: no room for record route option\n",
				    progname);
				exit(EXIT_FAILURE);

			}
			/*
			 * Format of record route option is same as source
			 * route option.
			 */
			srp = (struct ip_sourceroute *)bufp;
			srp->ipsr_code = IPOPT_RR;
			srp->ipsr_len = optsize;
			srp->ipsr_ptr = IPOPT_MINOFF;

			optsize -= srp->ipsr_len;
			bufp += srp->ipsr_len;
		}
		optsize = bufp - srr;
		/* Round up to 4 byte boundary */
		if (optsize & 0x3)
			optsize = (optsize & ~0x3) + 4;
		if (setsockopt(sock, IPPROTO_IP, IP_OPTIONS, srr, optsize) <
		    0) {
			Fprintf(stderr, "%s: setsockopt IP_OPTIONS %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}
}

/*
 * Check out the packet to see if it came from us.  This logic is necessary
 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
 * which arrive ('tis only fair).  This permits multiple copies of this
 * program to be run without having intermingled output (or statistics!).
 */
void
check_reply(struct addrinfo *ai_dst, struct msghdr *msg, int cc,
    ushort_t udp_src_port)
{
	struct ip *ip;
	struct icmp *icp;
	struct udphdr *up;
	union any_in_addr dst_addr;
	uchar_t *buf;
	int32_t *intp;
	struct sockaddr_in *from;
	struct timeval *tp;
	struct timeval tv;
	int hlen, hlen1;
	int64_t triptime;
	boolean_t valid_reply = _B_FALSE;
	boolean_t reply_matched_current_target = _B_FALSE; /* Is the source */
						/* address of this reply same */
						/* as where we're sending */
						/* currently? */
	boolean_t last_reply_from_targetaddr = _B_FALSE; /* Is this stats, */
						/* probe all with npackets>0 */
						/* and we received reply for */
						/* the last probe sent to */
						/* targetaddr */
	int cc_left;
	char tmp_buf[INET6_ADDRSTRLEN];
	static char *unreach[] = {
	    "Net Unreachable",
	    "Host Unreachable",
	    "Protocol Unreachable",
	    "Port Unreachable",
	    "Fragmentation needed and DF set",
	    "Source Route Failed",
	    /* The following are from RFC1700 */
	    "Net Unknown",
	    "Host Unknown",
	    "Source Host Isolated",
	    "Dest Net Prohibited",
	    "Dest Host Prohibited",
	    "Net Unreachable for TOS",
	    "Host Unreachable for TOS",
	    "Communication Administratively Prohibited",
	    "Host Precedence Violation",
	    "Precedence Cutoff in Effect"
	};
	static char *redirect[] = {
	    "Net",
	    "Host",
	    "TOS Net",
	    "TOS Host"
	};
	static char *timexceed[] = {
	    "Time exceeded in transit",
	    "Time exceeded during reassembly"
	};
	boolean_t print_newline = _B_FALSE;
	int i;

	/* decompose msghdr into useful pieces */
	buf = (uchar_t *)msg->msg_iov->iov_base;
	from = (struct sockaddr_in *)msg->msg_name;

	/* LINTED */
	intp = (int32_t *)buf;

	ping_gettime(msg, &tv);

	/* LINTED */
	ip = (struct ip *)buf;
	hlen = ip->ip_hl << 2;

	if ((cc < sizeof (struct ip)) || (cc < hlen + ICMP_MINLEN)) {
		if (verbose) {
			Printf("packet too short (%d bytes) from %s\n", cc,
			    pr_name4(from));
		}
		return;
	}

	cc -= hlen;
	/* LINTED */
	icp = (struct icmp *)(buf + hlen);

	if (ip->ip_p == 0) {
		/*
		 * Assume that we are running on a pre-4.3BSD system
		 * such as SunOS before 4.0
		 */
		/* LINTED */
		icp = (struct icmp *)buf;
	}
	cc_left = cc - ICMP_MINLEN;

	switch (icp->icmp_type) {
	case ICMP_UNREACH:
		ip = &icp->icmp_ip;
		hlen1 = ip->ip_hl << 2;

		/* check if we have enough of the packet to work on */
		if ((cc_left < sizeof (struct ip)) ||
		    (cc_left < hlen1 + sizeof (struct udphdr))) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name4(from));
			}
			return;
		}

		/* get the UDP packet */
		cc_left -= hlen1 + sizeof (struct udphdr);
		/* LINTED */
		up = (struct udphdr *)((uchar_t *)ip + hlen1);

		/* check to see if this is what we sent */
		if (icp->icmp_code == ICMP_UNREACH_PORT &&
		    ip->ip_p == IPPROTO_UDP &&
		    udp_src_port == up->uh_sport &&
		    use_udp) {
			valid_reply = _B_TRUE;
		} else {
			valid_reply = _B_FALSE;
		}

		if (valid_reply) {
			/*
			 * For this valid reply, if we are still sending to
			 * this target IP address, we'd like to do some
			 * updates to targetaddr, so hold SIGALRMs.
			 */
			(void) sighold(SIGALRM);
			is_alive = _B_TRUE;
			nreceived++;
			reply_matched_current_target =
			    seq_match(current_targetaddr->starting_seq_num,
			    current_targetaddr->num_sent,
			    ntohs(up->uh_dport));
			if (reply_matched_current_target) {
				current_targetaddr->got_reply = _B_TRUE;
				nreceived_last_target++;
				/*
				 * Determine if stats, probe-all, and
				 * npackets != 0, and this is the reply for
				 * the last probe we sent to current target
				 * address.
				 */
				if (stats && probe_all && npackets > 0 &&
				    ((current_targetaddr->starting_seq_num +
				    current_targetaddr->num_probes - 1) %
				    (MAX_PORT + 1) == ntohs(up->uh_dport)) &&
				    (current_targetaddr->num_probes ==
				    current_targetaddr->num_sent))
					last_reply_from_targetaddr = _B_TRUE;
			} else {
				/*
				 * If it's just probe_all and we just received
				 * a reply from a target address we were
				 * probing and had timed out (now we are probing
				 * some other target address), we ignore
				 * this reply.
				 */
				if (probe_all && !stats) {
					valid_reply = _B_FALSE;
					/*
					 * Only if it's verbose, we get a
					 * message regarding this reply,
					 * otherwise we are done here.
					 */
					if (!verbose) {
						(void) sigrelse(SIGALRM);
						return;
					}
				}
			}
		}

		/* stats mode doesn't print 'alive' messages */
		if (valid_reply && !stats) {
			/*
			 * if we are still sending to the same target address,
			 * then stop it, because we know it's alive.
			 */
			if (reply_matched_current_target) {
				(void) alarm(0);	/* cancel alarm */
				(void) sigset(SIGALRM, SIG_IGN);
				current_targetaddr->probing_done = _B_TRUE;
			}
			(void) sigrelse(SIGALRM);

			if (!probe_all) {
				Printf("%s is alive\n", targethost);
			} else {
				(void) inet_ntop(AF_INET, (void *)&ip->ip_dst,
				    tmp_buf, sizeof (tmp_buf));

				if (nflag) {
					Printf("%s is alive\n", tmp_buf);
				} else {
					Printf("%s (%s) is alive\n",
					    targethost, tmp_buf);
				}
			}
			if (reply_matched_current_target) {
				/*
				 * Let's get things going again, but now
				 * ping will start sending to next target IP
				 * address.
				 */
				send_scheduled_probe();
				(void) sigset(SIGALRM, sigalrm_handler);
				schedule_sigalrm();
			}
			return;
		} else {
			/*
			 * If we are not moving to next targetaddr, let's
			 * release the SIGALRM now. We don't want to stall in
			 * the middle of probing a targetaddr if the pr_name()
			 * call (see below) takes longer.
			 */
			if (!last_reply_from_targetaddr)
				(void) sigrelse(SIGALRM);
			/* else, we'll release it later */
		}

		dst_addr.addr = ip->ip_dst;
		if (valid_reply) {
			Printf("%d bytes from %s: ", cc, pr_name4(from));
			Printf("udp_port=%d. ", ntohs(up->uh_dport));
			print_newline = _B_TRUE;
		} else if (is_a_target(ai_dst, &dst_addr) || verbose) {
			if (icp->icmp_code >= A_CNT(unreach)) {
				Printf("ICMP %d Unreachable from gateway %s\n",
				    icp->icmp_code, pr_name4(from));
			} else {
				Printf("ICMP %s from gateway %s\n",
				    unreach[icp->icmp_code], pr_name4(from));
			}
			Printf(" for %s from %s", pr_protocol(ip->ip_p),
			    pr_name((char *)&ip->ip_src, AF_INET));
			Printf(" to %s", pr_name((char *)&ip->ip_dst, AF_INET));
			if (ip->ip_p == IPPROTO_TCP ||
			    ip->ip_p == IPPROTO_UDP) {
				Printf(" port %d ", ntohs(up->uh_dport));
			}
			print_newline = _B_TRUE;
		}

		/* if we are timing and the reply has a timeval */
		if (valid_reply && datalen >= sizeof (struct timeval) &&
		    cc_left >= sizeof (struct timeval)) {
			/* LINTED */
			tp = (struct timeval *)((char *)up +
			    sizeof (struct udphdr));
			(void) tvsub(&tv, tp);
			triptime = (int64_t)tv.tv_sec * MICROSEC + tv.tv_usec;
			Printf("time=" TIMEFORMAT " ms", triptime/1000.0);
			tsum += triptime;
			tsum2 += triptime*triptime;
			if (triptime < tmin)
				tmin = triptime;
			if (triptime > tmax)
				tmax = triptime;
			print_newline = _B_TRUE;
		}
		if (print_newline)
			(void) putchar('\n');
		/*
		 * If it's stats, probe-all, npackets > 0, and we received reply
		 * for the last probe sent to this target address, then we
		 * don't need to wait anymore, let's move on to next target
		 * address, now!
		 */
		if (last_reply_from_targetaddr) {
			(void) alarm(0);	/* cancel alarm */
			current_targetaddr->probing_done = _B_TRUE;
			(void) sigrelse(SIGALRM);
			send_scheduled_probe();
			schedule_sigalrm();
		}
		break;

	case ICMP_REDIRECT:
		if (cc_left < sizeof (struct ip)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name4(from));
			}
			return;
		}

		ip = &icp->icmp_ip;
		dst_addr.addr = ip->ip_dst;
		if (is_a_target(ai_dst, &dst_addr) || verbose) {
			if (icp->icmp_code >= A_CNT(redirect)) {
				Printf("ICMP %d redirect from gateway %s\n",
				    icp->icmp_code, pr_name4(from));
			} else {
				Printf("ICMP %s redirect from gateway %s\n",
				    redirect[icp->icmp_code], pr_name4(from));
			}
			Printf(" to %s",
			    pr_name((char *)&icp->icmp_gwaddr, AF_INET));
			Printf(" for %s\n",
			    pr_name((char *)&ip->ip_dst, AF_INET));
		}
		break;

	case ICMP_ECHOREPLY:
		if (ntohs(icp->icmp_id) == ident) {
			if (!use_udp && !use_icmp_ts)
				valid_reply = _B_TRUE;
			else
				valid_reply = _B_FALSE;
		} else {
			return;
		}

		if (valid_reply) {
			/*
			 * For this valid reply, if we are still sending to
			 * this target IP address, we'd like to do some
			 * updates to targetaddr, so hold SIGALRMs.
			 */
			(void) sighold(SIGALRM);
			is_alive = _B_TRUE;
			nreceived++;
			reply_matched_current_target =
			    seq_match(current_targetaddr->starting_seq_num,
			    current_targetaddr->num_sent,
			    ntohs(icp->icmp_seq));
			if (reply_matched_current_target) {
				current_targetaddr->got_reply = _B_TRUE;
				nreceived_last_target++;
				/*
				 * Determine if stats, probe-all, and
				 * npackets != 0, and this is the reply for
				 * the last probe we sent to current target
				 * address.
				 */
				if (stats && probe_all && npackets > 0 &&
				    ((current_targetaddr->starting_seq_num +
				    current_targetaddr->num_probes - 1) %
				    (MAX_ICMP_SEQ + 1) ==
				    ntohs(icp->icmp_seq)) &&
				    (current_targetaddr->num_probes ==
				    current_targetaddr->num_sent))
					last_reply_from_targetaddr = _B_TRUE;
			} else {
				/*
				 * If it's just probe_all and we just received
				 * a reply from a target address we were
				 * probing and had timed out (now we are probing
				 * some other target address), we ignore
				 * this reply.
				 */
				if (probe_all && !stats) {
					valid_reply = _B_FALSE;
					/*
					 * Only if it's verbose, we get a
					 * message regarding this reply,
					 * otherwise we are done here.
					 */
					if (!verbose) {
						(void) sigrelse(SIGALRM);
						return;
					}
				}
			}
		}

		if (!stats && valid_reply) {
			/*
			 * if we are still sending to the same target address,
			 * then stop it, because we know it's alive.
			 */
			if (reply_matched_current_target) {
				(void) alarm(0);	/* cancel alarm */
				(void) sigset(SIGALRM, SIG_IGN);
				current_targetaddr->probing_done = _B_TRUE;
			}
			(void) sigrelse(SIGALRM);

			if (!probe_all) {
				Printf("%s is alive\n", targethost);
			} else {
				/*
				 * If we are using send_reply, the real
				 * target address is not the src address of the
				 * replies. Use icmp_seq to find out where this
				 * probe was sent to.
				 */
				if (send_reply) {
					(void) find_dstaddr(
					    ntohs(icp->icmp_seq), &dst_addr);
					(void) inet_ntop(AF_INET,
					    (void *)&dst_addr.addr,
					    tmp_buf, sizeof (tmp_buf));
				} else {
					(void) inet_ntop(AF_INET,
					    (void *)&from->sin_addr,
					    tmp_buf, sizeof (tmp_buf));
				}
				if (nflag) {
					Printf("%s is alive\n", tmp_buf);
				} else {
					Printf("%s (%s) is alive\n",
					    targethost, tmp_buf);
				}
			}
			if (reply_matched_current_target) {
				/*
				 * Let's get things going again, but now
				 * ping will start sending to next target IP
				 * address.
				 */
				send_scheduled_probe();
				(void) sigset(SIGALRM, sigalrm_handler);
				schedule_sigalrm();
			}
			return;
		} else {
			/*
			 * If we are not moving to next targetaddr, let's
			 * release the SIGALRM now. We don't want to stall in
			 * the middle of probing a targetaddr if the pr_name()
			 * call (see below) takes longer.
			 */
			if (!last_reply_from_targetaddr)
				(void) sigrelse(SIGALRM);
			/* else, we'll release it later */
		}
		/*
		 * If we are using send_reply, the real target address is
		 * not the src address of the replies. Use icmp_seq to find out
		 * where this probe was sent to.
		 */
		if (send_reply) {
			(void) find_dstaddr(ntohs(icp->icmp_seq), &dst_addr);
			Printf("%d bytes from %s: ", cc,
			    pr_name((char *)&dst_addr.addr,  AF_INET));
		} else {
			Printf("%d bytes from %s: ", cc, pr_name4(from));
		}
		Printf("icmp_seq=%d. ", ntohs(icp->icmp_seq));

		if (valid_reply && datalen >= sizeof (struct timeval) &&
		    cc_left >= sizeof (struct timeval)) {
			/* LINTED */
			tp = (struct timeval *)&icp->icmp_data[0];
			(void) tvsub(&tv, tp);
			triptime = (int64_t)tv.tv_sec * MICROSEC + tv.tv_usec;
			Printf("time=" TIMEFORMAT " ms", triptime/1000.0);
			tsum += triptime;
			tsum2 += triptime*triptime;
			if (triptime < tmin)
				tmin = triptime;
			if (triptime > tmax)
				tmax = triptime;
		}
		(void) putchar('\n');

		/*
		 * If it's stats, probe-all, npackets > 0, and we received reply
		 * for the last probe sent to this target address, then we
		 * don't need to wait anymore, let's move on to next target
		 * address, now!
		 */
		if (last_reply_from_targetaddr) {
			(void) alarm(0);	/* cancel alarm */
			current_targetaddr->probing_done = _B_TRUE;
			(void) sigrelse(SIGALRM);
			send_scheduled_probe();
			schedule_sigalrm();
		}
		break;

	case ICMP_SOURCEQUENCH:
		if (cc_left < sizeof (struct ip)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name4(from));
			}
			return;
		}
		ip = &icp->icmp_ip;
		hlen1 = ip->ip_hl << 2;
		dst_addr.addr = ip->ip_dst;
		if (is_a_target(ai_dst, &dst_addr) || verbose) {
			Printf("ICMP Source Quench from %s\n", pr_name4(from));
			Printf(" for %s from %s", pr_protocol(ip->ip_p),
			    pr_name((char *)&ip->ip_src, AF_INET));
			Printf(" to %s", pr_name((char *)&ip->ip_dst, AF_INET));

			/*
			 * if it's a UDP or TCP packet, we need at least first
			 * 4 bytes of it to see the src/dst ports
			 */
			if ((ip->ip_p == IPPROTO_TCP ||
			    ip->ip_p == IPPROTO_UDP) &&
			    (cc_left >= hlen1 + 4)) {
				/* LINTED */
				up = (struct udphdr *)((uchar_t *)ip + hlen1);
				Printf(" port %d", ntohs(up->uh_dport));
			}
			(void) putchar('\n');
		}
		break;

	case ICMP_PARAMPROB:
		if (cc_left < sizeof (struct ip)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name4(from));
			}
			return;
		}
		ip = &icp->icmp_ip;
		hlen1 = ip->ip_hl << 2;
		dst_addr.addr = ip->ip_dst;
		if (is_a_target(ai_dst, &dst_addr) || verbose) {
			switch (icp->icmp_code) {
			case ICMP_PARAMPROB_OPTABSENT:
				Printf("ICMP Missing a Required Option "
				    "parameter problem from %s\n",
				    pr_name4(from));
				Printf(" option type = %d", icp->icmp_pptr);
				break;
			case ICMP_PARAMPROB_BADLENGTH:
				Printf("ICMP Bad Length parameter problem "
				    "from %s\n", pr_name4(from));
				Printf(" in byte %d", icp->icmp_pptr);
				if (icp->icmp_pptr <= hlen1) {
					Printf(" (value 0x%x)",
					    *((char *)ip + icp->icmp_pptr));
				}
				break;
			case 0:
			default:
				Printf("ICMP Parameter Problem from %s\n",
				    pr_name4(from));
				Printf(" in byte %d", icp->icmp_pptr);
				if (icp->icmp_pptr <= hlen1) {
					Printf(" (value 0x%x)",
					    *((char *)ip + icp->icmp_pptr));
				}
				break;
			}

			Printf(" for %s from %s", pr_protocol(ip->ip_p),
			    pr_name((char *)&ip->ip_src, AF_INET));
			Printf(" to %s", pr_name((char *)&ip->ip_dst, AF_INET));

			/*
			 * if it's a UDP or TCP packet, we need at least first
			 * 4 bytes of it to see the src/dst ports
			 */
			if ((ip->ip_p == IPPROTO_TCP ||
			    ip->ip_p == IPPROTO_UDP) &&
			    (cc_left >= hlen1 + 4)) {
				/* LINTED */
				up = (struct udphdr *)((uchar_t *)ip + hlen1);
				Printf(" port %d", ntohs(up->uh_dport));
			}
			(void) putchar('\n');
		}
		break;

	case ICMP_TIMXCEED:
		if (cc_left < sizeof (struct ip)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name4(from));
			}
			return;
		}
		ip = &icp->icmp_ip;
		hlen1 = ip->ip_hl << 2;
		dst_addr.addr = ip->ip_dst;
		if (is_a_target(ai_dst, &dst_addr) || verbose) {
			if (icp->icmp_code >= A_CNT(timexceed)) {
				Printf("ICMP %d time exceeded from %s\n",
				    icp->icmp_code, pr_name4(from));
			} else {
				Printf("ICMP %s from %s\n",
				    timexceed[icp->icmp_code],
				    pr_name4(from));
			}
			Printf(" for %s from %s", pr_protocol(ip->ip_p),
			    pr_name((char *)&ip->ip_src, AF_INET));
			Printf(" to %s", pr_name((char *)&ip->ip_dst, AF_INET));
			if ((ip->ip_p == IPPROTO_TCP ||
			    ip->ip_p == IPPROTO_UDP) &&
			    (cc_left >= hlen1 + 4)) {
				/* LINTED */
				up = (struct udphdr *)((uchar_t *)ip + hlen1);
				Printf(" port %d", ntohs(up->uh_dport));
			}
			(void) putchar('\n');
		}
		break;

	case ICMP_TSTAMPREPLY:
		/* the packet should have enough space to store timestamps */
		if (cc_left < sizeof (struct id_ts)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name4(from));
			}
			return;
		}

		if (ntohs(icp->icmp_id) == ident) {
			if (use_icmp_ts)
				valid_reply = _B_TRUE;
			else
				valid_reply = _B_FALSE;
		} else {
			return;
		}

		if (valid_reply) {
			/*
			 * For this valid reply, if we are still sending to
			 * this target IP address, we'd like to do some
			 * updates to targetaddr, so hold SIGALRMs.
			 */
			(void) sighold(SIGALRM);
			is_alive = _B_TRUE;
			nreceived++;
			reply_matched_current_target =
			    seq_match(current_targetaddr->starting_seq_num,
			    current_targetaddr->num_sent,
			    ntohs(icp->icmp_seq));
			if (reply_matched_current_target) {
				current_targetaddr->got_reply = _B_TRUE;
				nreceived_last_target++;
				/*
				 * Determine if stats, probe-all, and
				 * npackets != 0, and this is the reply for
				 * the last probe we sent to current target
				 * address.
				 */
				if (stats && probe_all && npackets > 0 &&
				    ((current_targetaddr->starting_seq_num +
				    current_targetaddr->num_probes - 1) %
				    (MAX_ICMP_SEQ + 1) ==
				    ntohs(icp->icmp_seq)) &&
				    (current_targetaddr->num_probes ==
				    current_targetaddr->num_sent))
					last_reply_from_targetaddr = _B_TRUE;
			} else {
				/*
				 * If it's just probe_all and we just received
				 * a reply from a target address we were
				 * probing and had timed out (now we are probing
				 * some other target address), we ignore
				 * this reply.
				 */
				if (probe_all && !stats) {
					valid_reply = _B_FALSE;
					/*
					 * Only if it's verbose, we get a
					 * message regarding this reply,
					 * otherwise we are done here.
					 */
					if (!verbose) {
						(void) sigrelse(SIGALRM);
						return;
					}
				}
			}
		}

		if (!stats && valid_reply) {
			/*
			 * if we are still sending to the same target address,
			 * then stop it, because we know it's alive.
			 */
			if (reply_matched_current_target) {
				(void) alarm(0);	/* cancel alarm */
				(void) sigset(SIGALRM, SIG_IGN);
				current_targetaddr->probing_done = _B_TRUE;
			}
			(void) sigrelse(SIGALRM);

			if (!probe_all) {
				Printf("%s is alive\n", targethost);
			} else {
				/*
				 * If we are using send_reply, the real
				 * target address is not the src address of the
				 * replies. Use icmp_seq to find out where this
				 * probe was sent to.
				 */
				if (send_reply) {
					(void) find_dstaddr(
					    ntohs(icp->icmp_seq), &dst_addr);
					(void) inet_ntop(AF_INET,
					    (void *)&dst_addr.addr,
					    tmp_buf, sizeof (tmp_buf));
				} else {
					(void) inet_ntop(AF_INET,
					    (void *)&from->sin_addr,
					    tmp_buf, sizeof (tmp_buf));
				}
				if (nflag) {
					Printf("%s is alive\n", tmp_buf);
				} else {
					Printf("%s (%s) is alive\n",
					    targethost, tmp_buf);
				}
			}
			if (reply_matched_current_target) {
				/*
				 * Let's get things going again, but now
				 * ping will start sending to next target IP
				 * address.
				 */
				send_scheduled_probe();
				(void) sigset(SIGALRM, sigalrm_handler);
				schedule_sigalrm();
			}
			return;
		} else {
			/*
			 * If we are not moving to next targetaddr, let's
			 * release the SIGALRM now. We don't want to stall in
			 * the middle of probing a targetaddr if the pr_name()
			 * call (see below) takes longer.
			 */
			if (!last_reply_from_targetaddr)
				(void) sigrelse(SIGALRM);
			/* else, we'll release it later */
		}

		/*
		 * If we are using send_reply, the real target address is
		 * not the src address of the replies. Use icmp_seq to find out
		 * where this probe was sent to.
		 */
		if (send_reply) {
			(void) find_dstaddr(ntohs(icp->icmp_seq), &dst_addr);
			Printf("%d bytes from %s: ", cc,
			    pr_name((char *)&dst_addr.addr,  AF_INET));
		} else {
			Printf("%d bytes from %s: ", cc, pr_name4(from));
		}
		Printf("icmp_seq=%d. ", ntohs(icp->icmp_seq));
		Printf("orig = %lu, recv = %lu, xmit = %lu ",
		    (ulong_t)ntohl(icp->icmp_otime),
		    (ulong_t)ntohl(icp->icmp_rtime),
		    (ulong_t)ntohl(icp->icmp_ttime));

		if (valid_reply) {
			/*
			 * icp->icmp_otime is the time passed since midnight.
			 * Therefore we need to adjust tv value, which is
			 * the time passed since Jan 1, 1970.
			 */
			triptime = (tv.tv_sec % (24LL * 60 * 60)) * MILLISEC +
			    (tv.tv_usec / (MICROSEC/MILLISEC));
			triptime -= ntohl(icp->icmp_otime);
			if (triptime < 0)
				triptime += 24LL * 60 * 60 * MILLISEC;

			Printf("time=%d. ms", (int)triptime);
			triptime *= (MICROSEC/MILLISEC);
			tsum += triptime;
			tsum2 += triptime*triptime;
			if (triptime < tmin)
				tmin = triptime;
			if (triptime > tmax)
				tmax = triptime;
		}
		(void) putchar('\n');
		/*
		 * If it's stats, probe-all, npackets > 0, and we received reply
		 * for the last probe sent to this target address, then we
		 * don't need to wait anymore, let's move on to next target
		 * address, now!
		 */
		if (last_reply_from_targetaddr) {
			(void) alarm(0);	/* cancel alarm */
			current_targetaddr->probing_done = _B_TRUE;
			(void) sigrelse(SIGALRM);
			send_scheduled_probe();
			schedule_sigalrm();
		}
		break;
	case ICMP_ROUTERADVERT:
	case ICMP_ROUTERSOLICIT:
		/* Router discovery messages */
		return;

	case ICMP_ECHO:
	case ICMP_TSTAMP:
	case ICMP_IREQ:
	case ICMP_MASKREQ:
		/* These were never passed out from the SunOS 4.X kernel. */
		return;

	case ICMP_IREQREPLY:
	case ICMP_MASKREPLY:
		/* Replies for information and address mask requests */
		return;

	default:
		if (verbose) {
			Printf("%d bytes from %s:\n", cc, pr_name4(from));
			Printf("icmp_type=%d (%s) ",
			    icp->icmp_type, pr_type(icp->icmp_type));
			Printf("icmp_code=%d\n", icp->icmp_code);
			for (i = 0; i < 12; i++) {
				Printf("x%2.2x: x%8.8x\n",
				    i * sizeof (int32_t), *intp++);
			}
		}
		break;
	}

	buf += sizeof (struct ip);
	hlen -= sizeof (struct ip);

	/* if verbose and there exists IP options */
	if (verbose && hlen > 0)
		pr_options((uchar_t *)buf, hlen);
}

/*
 * Print out the ip options.
 */
static void
pr_options(uchar_t *opt, int optlength)
{
	int curlength;

	Printf("  IP options: ");
	while (optlength > 0) {
		curlength = opt[1];
		switch (*opt) {
		case IPOPT_EOL:
			optlength = 0;
			break;

		case IPOPT_NOP:
			opt++;
			optlength--;
			continue;

		case IPOPT_RR:
			Printf(" <record route> ");
			pr_rropt(opt, curlength, _B_TRUE);
			break;

		case IPOPT_TS:
			Printf(" <time stamp> ");
			pr_tsopt(opt, curlength);
			break;

		case IPOPT_SECURITY:
			Printf(" <security>");
			break;

		case IPOPT_LSRR:
			Printf(" <loose source route> ");
			pr_rropt(opt, curlength, _B_FALSE);
			break;

		case IPOPT_SATID:
			Printf(" <stream id>");
			break;

		case IPOPT_SSRR:
			Printf(" <strict source route> ");
			pr_rropt(opt, curlength, _B_FALSE);
			break;

		default:
			Printf(" <option %d, len %d>", *opt, curlength);
			break;
		}
		/*
		 * Following most options comes a length field
		 */
		opt += curlength;
		optlength -= curlength;
	}
	(void) putchar('\n');
}

/*
 * Print out a recorded route option. If rrflag is _B_TRUE, it prints record
 * route option, otherwise LSRR/SSRR.
 */
static void
pr_rropt(uchar_t *opt, int length, boolean_t rrflag)
{
	struct ip_sourceroute *rrp;
	int sr_index = 0;
	struct in_addr addr;

	rrp = (struct ip_sourceroute *)opt;

	/* data starts at offset 3 */
	length -= 3;
	while (length > 0) {
		/*
		 * Let's see if we are examining the addr pointed by ipsr_ptr
		 */
		if ((rrp->ipsr_ptr == (sr_index + 1) * sizeof (addr)) &&
		    rrflag) {
			Printf(" (End of record)");
			break;
		}

		bcopy(&rrp->ipsr_addrs[sr_index], &addr, sizeof (addr));
		Printf("%s", pr_name((char *)&addr, AF_INET));

		if (rrp->ipsr_ptr == (sr_index + 1) * sizeof (addr)) {
			Printf("(Current)");
		}

		sr_index++;

		length -= sizeof (addr);
		if (length > 0)
			Printf(", ");
	}
}

/*
 * Print out a timestamp option.
 */
static void
pr_tsopt(uchar_t *opt, int length)
{
	boolean_t address_present;
	boolean_t rrflag;		/* End at current entry? */
	struct ip_timestamp *tsp;
	int ts_index = 0;
	struct in_addr addr;
	size_t data_len;
	int32_t time;

	/* LINTED */
	tsp = (struct ip_timestamp *)opt;

	switch (tsp->ipt_flg) {
	case IPOPT_TS_TSONLY:
		address_present = _B_FALSE;
		data_len = sizeof (tsp->ipt_timestamp.ipt_time[0]);
		rrflag = _B_TRUE;
		break;
	case IPOPT_TS_TSANDADDR:
		address_present = _B_TRUE;
		data_len = sizeof (tsp->ipt_timestamp.ipt_ta[0]);
		rrflag = _B_TRUE;
		break;
	case IPOPT_TS_PRESPEC:
	case 3:
		address_present = _B_TRUE;
		data_len = sizeof (tsp->ipt_timestamp.ipt_ta[0]);
		rrflag = _B_FALSE;
		break;
	default:
		Printf("(Bad flag value: 0x%x)", tsp->ipt_flg);
		return;
	}
	if (tsp->ipt_oflw > 0)
		Printf("(Overflow: %d) ", tsp->ipt_oflw);

	/* data starts at offset 4 */
	length -= 4;

	while (length > 0) {
		if (length < data_len)
			break;

		/* the minimum value of ipt_ptr is 5 */
		if ((tsp->ipt_ptr == ts_index * data_len + 5) && rrflag) {
			Printf(" (End of record)");
			break;
		}
		if (address_present) {
			bcopy(&tsp->ipt_timestamp.ipt_ta[ts_index].ipt_addr,
			    &addr, sizeof (addr));
			Printf("%s: ", pr_name((char *)&addr, AF_INET));
			bcopy(&tsp->ipt_timestamp.ipt_ta[ts_index].ipt_time,
			    &time, sizeof (time));
		} else {
			bcopy(&tsp->ipt_timestamp.ipt_time[ts_index],
			    &time, sizeof (time));
		}
		Printf("%d", ntohl(time));

		if (tsp->ipt_ptr == ts_index * data_len + 5)
			Printf("(Current)");

		ts_index++;
		length -= data_len;
		if (length > 0)
			Printf(", ");
	}
}

/*
 * Convert an ICMP "type" field to a printable string.
 */
static char *
pr_type(int icmp_type)
{
	static struct icmptype_table ttab[] = {
		{ICMP_ECHOREPLY,	"Echo Reply"},
		{1,			"ICMP 1"},
		{2,			"ICMP 2"},
		{ICMP_UNREACH,		"Dest Unreachable"},
		{ICMP_SOURCEQUENCH,	"Source Quench"},
		{ICMP_REDIRECT,		"Redirect"},
		{6,			"ICMP 6"},
		{7,			"ICMP 7"},
		{ICMP_ECHO,		"Echo"},
		{ICMP_ROUTERADVERT,	"Router Advertisement"},
		{ICMP_ROUTERSOLICIT,	"Router Solicitation"},
		{ICMP_TIMXCEED,		"Time Exceeded"},
		{ICMP_PARAMPROB,	"Parameter Problem"},
		{ICMP_TSTAMP,		"Timestamp"},
		{ICMP_TSTAMPREPLY,	"Timestamp Reply"},
		{ICMP_IREQ,		"Info Request"},
		{ICMP_IREQREPLY,	"Info Reply"},
		{ICMP_MASKREQ,		"Netmask Request"},
		{ICMP_MASKREPLY,	"Netmask Reply"}
	};
	int i;

	for (i = 0; i < A_CNT(ttab); i++) {
		if (ttab[i].type == icmp_type)
			return (ttab[i].message);
	}

	return ("OUT-OF-RANGE");
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved	*/

/*
 * Copyright 2015, Joyent, Inc.
 * Copyright 2024 Bill Sommerfeld <sommerfeld@hamachi.org>
 */

/*
 * Portions of this source code were derived from Berkeley 4.3 BSD
 * under license from the Regents of the University of California.
 */

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

#include <sys/time.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/stropts.h>
#include <sys/file.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netinet/ip6.h>
#include <netinet/icmp6.h>
#include <netinet/udp.h>
#include <netdb.h>
#include <stdlib.h>

#include <libinetutil.h>
#include "ping.h"

static int IPv6_hdrlen(ip6_t *, int, uint8_t *);
static void pr_ext_headers(struct msghdr *);
static void pr_rthdr(unsigned char *);
static char *pr_type6(uchar_t);

/*
 * Initialize the msghdr for specifying the hoplimit, outgoing interface and
 * routing header.
 */
void
set_ancillary_data(struct msghdr *msgp, int hoplimit,
    union any_in_addr *gwIPlist, int gw_cnt, uint_t if_index)
{
	size_t hoplimit_space;
	size_t rthdr_space;
	size_t pktinfo_space;
	size_t bufspace;
	struct cmsghdr *cmsgp;
	uchar_t *cmsg_datap;
	static boolean_t first = _B_TRUE;
	int i;

	if (hoplimit == -1 && gw_cnt == 0 && if_index == 0)
		return;

	/*
	 * Need to figure out size of buffer needed for ancillary data
	 * containing routing header and packet info options.
	 *
	 * Portable heuristic to compute upper bound on space needed for
	 * N ancillary data options. It assumes up to _MAX_ALIGNMENT padding
	 * after both header and data as the worst possible upper bound on space
	 * consumed by padding.
	 * It also adds one extra "sizeof (struct cmsghdr)" for the last option.
	 * This is needed because we would like to use CMSG_NXTHDR() while
	 * composing the buffer. The CMSG_NXTHDR() macro is designed better for
	 * parsing than composing the buffer. It requires the pointer it returns
	 * to leave space in buffer for addressing a cmsghdr and we want to make
	 * sure it works for us while we skip beyond the last ancillary data
	 * option.
	 *
	 * bufspace[i]  = sizeof(struct cmsghdr) + <pad after header> +
	 *		<option[i] content length> + <pad after data>;
	 *
	 * total_bufspace = bufspace[0] + bufspace[1] + ...
	 *		    ... + bufspace[N-1] + sizeof (struct cmsghdr);
	 */

	rthdr_space = 0;
	pktinfo_space = 0;
	hoplimit_space = 0;
	bufspace = 0;

	if (hoplimit != -1) {
		hoplimit_space = sizeof (int);
		bufspace += sizeof (struct cmsghdr) + _MAX_ALIGNMENT +
		    hoplimit_space + _MAX_ALIGNMENT;
	}

	if (gw_cnt > 0) {
		rthdr_space = inet6_rth_space(IPV6_RTHDR_TYPE_0, gw_cnt);
		bufspace += sizeof (struct cmsghdr) + _MAX_ALIGNMENT +
		    rthdr_space + _MAX_ALIGNMENT;
	}

	if (if_index != 0) {
		pktinfo_space = sizeof (struct in6_pktinfo);
		bufspace += sizeof (struct cmsghdr) + _MAX_ALIGNMENT +
		    pktinfo_space + _MAX_ALIGNMENT;
	}

	/*
	 * We need to temporarily set the msgp->msg_controllen to bufspace
	 * (we will later trim it to actual length used). This is needed because
	 * CMSG_NXTHDR() uses it to check we have not exceeded the bounds.
	 */
	bufspace += sizeof (struct cmsghdr);
	msgp->msg_controllen = bufspace;

	/*
	 * This function is called more than once only if -l/-S used,
	 * since we need to modify the middle gateway. So, don't alloc
	 * new memory, just reuse what msg6 points to.
	 */
	if (first) {
		first = _B_FALSE;
		msgp->msg_control = (struct cmsghdr *)malloc(bufspace);
		if (msgp->msg_control == NULL) {
			Fprintf(stderr, "%s: malloc %s\n",
			    progname, strerror(errno));
			exit(EXIT_FAILURE);
		}
	};
	cmsgp = CMSG_FIRSTHDR(msgp);

	/*
	 * Fill ancillary data. First hoplimit, then rthdr and pktinfo.
	 */

	/* set hoplimit ancillary data if needed */
	if (hoplimit != -1) {
		cmsgp->cmsg_level = IPPROTO_IPV6;
		cmsgp->cmsg_type = IPV6_HOPLIMIT;
		cmsg_datap = CMSG_DATA(cmsgp);
		/* LINTED */
		*(int *)cmsg_datap = hoplimit;
		cmsgp->cmsg_len = cmsg_datap + hoplimit_space -
		    (uchar_t *)cmsgp;
		cmsgp = CMSG_NXTHDR(msgp, cmsgp);
	}

	/* set rthdr ancillary data if needed */
	if (gw_cnt > 0) {
		struct ip6_rthdr0 *rthdr0p;

		cmsgp->cmsg_level = IPPROTO_IPV6;
		cmsgp->cmsg_type = IPV6_RTHDR;
		cmsg_datap = CMSG_DATA(cmsgp);

		/*
		 * Initialize rthdr structure
		 */
		/* LINTED */
		rthdr0p = (struct ip6_rthdr0 *)cmsg_datap;
		if (inet6_rth_init(rthdr0p, rthdr_space,
		    IPV6_RTHDR_TYPE_0, gw_cnt) == NULL) {
			Fprintf(stderr, "%s: inet6_rth_init failed\n",
			    progname);
			exit(EXIT_FAILURE);
		}

		/*
		 * Stuff in gateway addresses
		 */
		for (i = 0; i < gw_cnt; i++) {
			if (inet6_rth_add(rthdr0p, &gwIPlist[i].addr6) == -1) {
				Fprintf(stderr,
				    "%s: inet6_rth_add\n", progname);
				exit(EXIT_FAILURE);
			}
		}

		cmsgp->cmsg_len = cmsg_datap + rthdr_space - (uchar_t *)cmsgp;
		cmsgp = CMSG_NXTHDR(msgp, cmsgp);
	}

	/* set pktinfo ancillary data if needed */
	if (if_index != 0) {
		struct in6_pktinfo *pktinfop;

		cmsgp->cmsg_level = IPPROTO_IPV6;
		cmsgp->cmsg_type = IPV6_PKTINFO;
		cmsg_datap = CMSG_DATA(cmsgp);

		/* LINTED */
		pktinfop = (struct in6_pktinfo *)cmsg_datap;
		/*
		 * We don't know if pktinfop->ipi6_addr is aligned properly,
		 * therefore let's use bcopy, instead of assignment.
		 */
		(void) bcopy(&in6addr_any, &pktinfop->ipi6_addr,
		    sizeof (struct in6_addr));

		/*
		 *  We can assume pktinfop->ipi6_ifindex is 32 bit aligned.
		 */
		pktinfop->ipi6_ifindex = if_index;
		cmsgp->cmsg_len = cmsg_datap + pktinfo_space - (uchar_t *)cmsgp;
		cmsgp = CMSG_NXTHDR(msgp, cmsgp);
	}

	msgp->msg_controllen = (char *)cmsgp - (char *)msgp->msg_control;
}

/*
 * Check out the packet to see if it came from us.  This logic is necessary
 * because ALL readers of the ICMP socket get a copy of ALL ICMP packets
 * which arrive ('tis only fair).  This permits multiple copies of this
 * program to be run without having intermingled output (or statistics!).
 */
void
check_reply6(struct addrinfo *ai_dst, struct msghdr *msg, int cc,
    ushort_t udp_src_port)
{
	struct icmp6_hdr *icmp6;
	ip6_t *ip6h;
	nd_redirect_t *nd_rdrct;
	struct udphdr *up;
	union any_in_addr dst_addr;
	uchar_t *buf;
	int32_t *intp;
	struct sockaddr_in6 *from6;
	struct timeval tv;
	struct timeval *tp;
	int64_t triptime;
	boolean_t valid_reply = _B_FALSE;
	boolean_t reply_matched_current_target = _B_FALSE; /* Is the source */
						/* address of this reply same */
						/* as where we're sending */
						/* currently? */
	boolean_t last_reply_from_targetaddr = _B_FALSE; /* Is this stats, */
						/* probe all with npackets>0 */
						/* and we received reply for */
						/* the last probe sent to */
						/* targetaddr */
	uint32_t ip6hdr_len;
	uint8_t last_hdr;
	int cc_left;
	int i;
	char tmp_buf[INET6_ADDRSTRLEN];
	static char *unreach6[] = {
	    "No Route to Destination",
	    "Communication Administratively Prohibited",
	    "Not a Neighbor (obsoleted ICMPv6 code)",
	    "Address Unreachable",
	    "Port Unreachable"
	};
	static char *timexceed6[] = {
	    "Hop limit exceeded in transit",
	    "Fragment reassembly time exceeded"
	};
	static char *param_prob6[] = {
	    "Erroneous header field encountered",
	    "Unrecognized next header type encountered",
	    "Unrecognized IPv6 option encountered"
	};
	boolean_t print_newline = _B_FALSE;

	/* decompose msghdr into useful pieces */
	buf = (uchar_t *)msg->msg_iov->iov_base;
	from6 = (struct sockaddr_in6 *)msg->msg_name;

	/* LINTED */
	intp = (int32_t *)buf;

	ping_gettime(msg, &tv);

	/* Ignore packets > 64k or control buffers that don't fit */
	if (msg->msg_flags & (MSG_TRUNC|MSG_CTRUNC)) {
		if (verbose) {
			Printf("Truncated message: msg_flags 0x%x from %s\n",
			    msg->msg_flags, pr_name6(from6));
		}
		return;
	}
	if (cc < ICMP6_MINLEN) {
		if (verbose) {
			Printf("packet too short (%d bytes) from %s\n", cc,
			    pr_name6(from6));
		}
		return;
	}
	/* LINTED */
	icmp6 = (struct icmp6_hdr *)buf;
	cc_left = cc - ICMP6_MINLEN;

	switch (icmp6->icmp6_type) {
	case ICMP6_DST_UNREACH:
		/* LINTED */
		ip6h = (ip6_t *)((char *)icmp6 + ICMP6_MINLEN);
		if (cc_left < sizeof (ip6_t)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name6(from6));
			}
			return;
		}

		/*
		 * Determine the total length of IPv6 header and extension
		 * headers, also the upper layer header (UDP, TCP, ICMP, etc.)
		 * following.
		 */
		ip6hdr_len = IPv6_hdrlen(ip6h, cc_left, &last_hdr);

		cc_left -= ip6hdr_len;

		/* LINTED */
		up = (struct udphdr *)((char *)ip6h + ip6hdr_len);
		if (cc_left < sizeof (struct udphdr)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name6(from6));
			}
			return;
		}
		cc_left -= sizeof (struct udphdr);

		/* determine if this is *the* reply */
		if (icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT &&
		    last_hdr == IPPROTO_UDP &&
		    udp_src_port == up->uh_sport &&
		    use_udp) {
			valid_reply = _B_TRUE;
		} else {
			valid_reply = _B_FALSE;
		}

		if (valid_reply) {
			/*
			 * For this valid reply, if we are still sending to
			 * this target IP address, we'd like to do some
			 * updates to targetaddr, so hold SIGALRMs.
			 */
			(void) sighold(SIGALRM);
			is_alive = _B_TRUE;
			nreceived++;
			reply_matched_current_target =
			    seq_match(current_targetaddr->starting_seq_num,
			    current_targetaddr->num_sent,
			    ntohs(up->uh_dport));
			if (reply_matched_current_target) {
				current_targetaddr->got_reply = _B_TRUE;
				nreceived_last_target++;
				/*
				 * Determine if stats, probe-all, and
				 * npackets != 0, and this is the reply for
				 * the last probe we sent to current target
				 * address.
				 */
				if (stats && probe_all && npackets > 0 &&
				    ((current_targetaddr->starting_seq_num +
				    current_targetaddr->num_probes - 1) %
				    (MAX_PORT + 1) == ntohs(up->uh_dport)) &&
				    (current_targetaddr->num_probes ==
				    current_targetaddr->num_sent))
					last_reply_from_targetaddr = _B_TRUE;
			} else {
				/*
				 * If it's just probe_all and we just received
				 * a reply from a target address we were
				 * probing and had timed out (now we are probing
				 * some other target address), we ignore
				 * this reply.
				 */
				if (probe_all && !stats) {
					valid_reply = _B_FALSE;
					/*
					 * Only if it's verbose, we get a
					 * message regarding this reply,
					 * otherwise we are done here.
					 */
					if (!verbose) {
						(void) sigrelse(SIGALRM);
						return;
					}
				}
			}
		}

		if (valid_reply && !stats) {
			/*
			 * if we are still sending to the same target address,
			 * then stop it, because we know it's alive.
			 */
			if (reply_matched_current_target) {
				(void) alarm(0);	/* cancel alarm */
				(void) sigset(SIGALRM, SIG_IGN);
				current_targetaddr->probing_done = _B_TRUE;
			}
			(void) sigrelse(SIGALRM);

			if (!probe_all) {
				Printf("%s is alive\n", targethost);
			} else {
				(void) inet_ntop(AF_INET6,
				    (void *)&ip6h->ip6_dst,
				    tmp_buf, sizeof (tmp_buf));
				if (nflag) {
					Printf("%s is alive\n", tmp_buf);
				} else {
					Printf("%s (%s) is alive\n",
					    targethost, tmp_buf);
				}
			}
			if (reply_matched_current_target) {
				/*
				 * Let's get things going again, but now
				 * ping will start sending to next target IP
				 * address.
				 */
				send_scheduled_probe();
				(void) sigset(SIGALRM, sigalrm_handler);
				schedule_sigalrm();
			}
			return;
		} else {
			/*
			 * If we are not moving to next targetaddr, let's
			 * release the SIGALRM now. We don't want to stall in
			 * the middle of probing a targetaddr if the pr_name()
			 * call (see below) takes longer.
			 */
			if (!last_reply_from_targetaddr)
				(void) sigrelse(SIGALRM);
			/* else, we'll release it later */
		}

		dst_addr.addr6 = ip6h->ip6_dst;
		if (valid_reply) {
			Printf("%d bytes from %s: ", cc,
			    pr_name6(from6));
			Printf("udp_port=%d. ", ntohs(up->uh_dport));
			print_newline = _B_TRUE;
		} else if (is_a_target(ai_dst, &dst_addr)|| verbose) {
			if (icmp6->icmp6_code >= A_CNT(unreach6)) {
				Printf("ICMPv6 %d Unreachable from gateway "
				    "%s\n", icmp6->icmp6_code,
				    pr_name6(from6));
			} else {
				Printf("ICMPv6 %s from gateway %s\n",
				    unreach6[icmp6->icmp6_code],
				    pr_name6(from6));
			}
			Printf(" for %s from %s", pr_protocol(last_hdr),
			    pr_name((char *)&ip6h->ip6_src, AF_INET6));
			Printf(" to %s", pr_name((char *)&ip6h->ip6_dst,
			    AF_INET6));
			if (last_hdr == IPPROTO_TCP || last_hdr == IPPROTO_UDP)
				Printf(" port %d ", ntohs(up->uh_dport));
			print_newline = _B_TRUE;
		}

		/*
		 * Update and print the stats, if it's a valid reply and
		 * contains a timestamp.
		 */
		if (valid_reply && datalen >= sizeof (struct timeval) &&
		    cc_left >= sizeof (struct timeval)) {
			/* LINTED */
			tp = (struct timeval *)((char *)up +
			    sizeof (struct udphdr));
			(void) tvsub(&tv, tp);
			triptime = (int64_t)tv.tv_sec * MICROSEC + tv.tv_usec;
			Printf("time=" TIMEFORMAT " ms", triptime/1000.0);
			tsum += triptime;
			tsum2 += triptime*triptime;
			if (triptime < tmin)
				tmin = triptime;
			if (triptime > tmax)
				tmax = triptime;
			print_newline = _B_TRUE;
		}
		if (print_newline)
			(void) putchar('\n');
		/*
		 * If it's stats, probe-all, npackets > 0, and we received reply
		 * for the last probe sent to this target address, then we
		 * don't need to wait anymore, let's move on to next target
		 * address, now!
		 */
		if (last_reply_from_targetaddr) {
			(void) alarm(0);	/* cancel alarm */
			current_targetaddr->probing_done = _B_TRUE;
			(void) sigrelse(SIGALRM);
			send_scheduled_probe();
			schedule_sigalrm();
		}
		break;

	case ICMP6_PACKET_TOO_BIG:
		/* LINTED */
		ip6h = (ip6_t *)((char *)icmp6 + ICMP6_MINLEN);
		if (cc_left < sizeof (ip6_t)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name6(from6));
			}
			return;
		}
		ip6hdr_len = IPv6_hdrlen(ip6h, cc_left, &last_hdr);

		dst_addr.addr6 = ip6h->ip6_dst;
		if (is_a_target(ai_dst, &dst_addr) || verbose) {
			Printf("ICMPv6 packet too big from %s\n",
			    pr_name6(from6));

			Printf(" for %s from %s", pr_protocol(last_hdr),
			    pr_name((char *)&ip6h->ip6_src, AF_INET6));
			Printf(" to %s", pr_name((char *)&ip6h->ip6_dst,
			    AF_INET6));
			if ((last_hdr == IPPROTO_TCP ||
			    last_hdr == IPPROTO_UDP) &&
			    (cc_left >= (ip6hdr_len + 4))) {
				/* LINTED */
				up = (struct udphdr *)
				    ((char *)ip6h + ip6hdr_len);
				Printf(" port %d ", ntohs(up->uh_dport));
			}
			Printf(" MTU = %d\n", ntohl(icmp6->icmp6_mtu));
		}
		break;

	case ICMP6_TIME_EXCEEDED:
		/* LINTED */
		ip6h = (ip6_t *)((char *)icmp6 + ICMP6_MINLEN);
		if (cc_left < sizeof (ip6_t)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name6(from6));
			}
			return;
		}
		ip6hdr_len = IPv6_hdrlen(ip6h, cc_left, &last_hdr);

		dst_addr.addr6 = ip6h->ip6_dst;
		if (is_a_target(ai_dst, &dst_addr) || verbose) {
			if (icmp6->icmp6_code >= A_CNT(timexceed6)) {
				Printf("ICMPv6 %d time exceeded from %s\n",
				    icmp6->icmp6_code, pr_name6(from6));
			} else {
				Printf("ICMPv6 %s from %s\n",
				    timexceed6[icmp6->icmp6_code],
				    pr_name6(from6));
			}
			Printf(" for %s from %s", pr_protocol(last_hdr),
			    pr_name((char *)&ip6h->ip6_src, AF_INET6));
			Printf(" to %s", pr_name((char *)&ip6h->ip6_dst,
			    AF_INET6));
			if ((last_hdr == IPPROTO_TCP ||
			    last_hdr == IPPROTO_UDP) &&
			    (cc_left >= (ip6hdr_len + 4))) {
				/* LINTED */
				up = (struct udphdr *)
				    ((char *)ip6h + ip6hdr_len);
				Printf(" port %d", ntohs(up->uh_dport));
			}
			(void) putchar('\n');
		}
		break;

	case ICMP6_PARAM_PROB:
		/* LINTED */
		ip6h = (ip6_t *)((char *)icmp6 + ICMP6_MINLEN);
		if (cc_left < sizeof (ip6_t)) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name6(from6));
			}
			return;
		}
		ip6hdr_len = IPv6_hdrlen(ip6h, cc_left, &last_hdr);

		dst_addr.addr6 = ip6h->ip6_dst;
		if (is_a_target(ai_dst, &dst_addr) || verbose) {
			if (icmp6->icmp6_code >= A_CNT(param_prob6)) {
				Printf("ICMPv6 %d parameter problem from %s\n",
				    icmp6->icmp6_code, pr_name6(from6));
			} else {
				Printf("ICMPv6 %s from %s\n",
				    param_prob6[icmp6->icmp6_code],
				    pr_name6(from6));
			}
			icmp6->icmp6_pptr = ntohl(icmp6->icmp6_pptr);
			Printf(" in byte %d", icmp6->icmp6_pptr);
			if (icmp6->icmp6_pptr <= ip6hdr_len) {
				Printf(" (value 0x%x)",
				    *((uchar_t *)ip6h + icmp6->icmp6_pptr));
			}
			Printf(" for %s from %s", pr_protocol(last_hdr),
			    pr_name((char *)&ip6h->ip6_src, AF_INET6));
			Printf(" to %s", pr_name((char *)&ip6h->ip6_dst,
			    AF_INET6));
			if ((last_hdr == IPPROTO_TCP ||
			    last_hdr == IPPROTO_UDP) &&
			    (cc_left >= (ip6hdr_len + 4))) {
				/* LINTED */
				up = (struct udphdr *)
				    ((char *)ip6h + ip6hdr_len);
				Printf(" port %d", ntohs(up->uh_dport));
			}
			(void) putchar('\n');
		}
		break;

	case ICMP6_ECHO_REQUEST:
		return;

	case ICMP6_ECHO_REPLY:
		if (ntohs(icmp6->icmp6_id) == ident) {
			if (!use_udp)
				valid_reply = _B_TRUE;
			else
				valid_reply = _B_FALSE;
		} else {
			return;
		}

		if (valid_reply) {
			/*
			 * For this valid reply, if we are still sending to
			 * this target IP address, we'd like to do some
			 * updates to targetaddr, so hold SIGALRMs.
			 */
			(void) sighold(SIGALRM);
			is_alive = _B_TRUE;
			nreceived++;
			reply_matched_current_target =
			    seq_match(current_targetaddr->starting_seq_num,
			    current_targetaddr->num_sent,
			    ntohs(icmp6->icmp6_seq));
			if (reply_matched_current_target) {
				current_targetaddr->got_reply = _B_TRUE;
				nreceived_last_target++;
				/*
				 * Determine if stats, probe-all, and
				 * npackets != 0, and this is the reply for
				 * the last probe we sent to current target
				 * address.
				 */
				if (stats && probe_all && npackets > 0 &&
				    ((current_targetaddr->starting_seq_num +
				    current_targetaddr->num_probes - 1) %
				    (MAX_ICMP_SEQ + 1) ==
				    ntohs(icmp6->icmp6_seq)) &&
				    (current_targetaddr->num_probes ==
				    current_targetaddr->num_sent))
					last_reply_from_targetaddr = _B_TRUE;
			} else {
				/*
				 * If it's just probe_all and we just received
				 * a reply from a target address we were
				 * probing and had timed out (now we are probing
				 * some other target address), we ignore
				 * this reply.
				 */
				if (probe_all && !stats) {
					valid_reply = _B_FALSE;
					/*
					 * Only if it's verbose, we get a
					 * message regarding this reply,
					 * otherwise we are done here.
					 */
					if (!verbose) {
						(void) sigrelse(SIGALRM);
						return;
					}
				}
			}
		}

		if (!stats && valid_reply) {
			/*
			 * if we are still sending to the same target address,
			 * then stop it, because we know it's alive.
			 */
			if (reply_matched_current_target) {
				(void) alarm(0);	/* cancel alarm */
				(void) sigset(SIGALRM, SIG_IGN);
				current_targetaddr->probing_done = _B_TRUE;
			}
			(void) sigrelse(SIGALRM);

			if (!probe_all) {
				Printf("%s is alive\n", targethost);
			} else {
				/*
				 * If we are using send_reply, the real
				 * target address is not the src address of the
				 * replies. Use icmp_seq to find out where this
				 * probe was sent to.
				 */
				if (send_reply) {
					(void) find_dstaddr(
					    ntohs(icmp6->icmp6_seq), &dst_addr);
					(void) inet_ntop(AF_INET6,
					    (void *)&dst_addr.addr6,
					    tmp_buf, sizeof (tmp_buf));
				} else {
					(void) inet_ntop(AF_INET6,
					    (void *)&from6->sin6_addr,
					    tmp_buf, sizeof (tmp_buf));
				}

				if (nflag) {
					Printf("%s is alive\n", tmp_buf);
				} else {
					Printf("%s (%s) is alive\n",
					    targethost, tmp_buf);
				}
			}
			if (reply_matched_current_target) {
				/*
				 * Let's get things going again, but now
				 * ping will start sending to next target IP
				 * address.
				 */
				send_scheduled_probe();
				(void) sigset(SIGALRM, sigalrm_handler);
				schedule_sigalrm();
			}
			return;
		} else {
			/*
			 * If we are not moving to next targetaddr, let's
			 * release the SIGALRM now. We don't want to stall in
			 * the middle of probing a targetaddr if the pr_name()
			 * call (see below) takes longer.
			 */
			if (!last_reply_from_targetaddr)
				(void) sigrelse(SIGALRM);
			/* else, we'll release it later */
		}

		/*
		 * If we are using send_reply, the real target address is
		 * not the src address of the replies. Use icmp_seq to find out
		 * where this probe was sent to.
		 */
		if (send_reply) {
			(void) find_dstaddr(ntohs(icmp6->icmp6_seq), &dst_addr);
			Printf("%d bytes from %s: ", cc,
			    pr_name((char *)&dst_addr.addr6,  AF_INET6));
		} else {
			Printf("%d bytes from %s: ", cc, pr_name6(from6));
		}
		Printf("icmp_seq=%d. ", ntohs(icmp6->icmp6_seq));

		if (valid_reply && datalen >= sizeof (struct timeval) &&
		    cc_left >= sizeof (struct timeval)) {
			/* LINTED */
			tp = (struct timeval *)&icmp6->icmp6_data16[2];
			(void) tvsub(&tv, tp);
			triptime = (int64_t)tv.tv_sec * MICROSEC + tv.tv_usec;
			Printf("time=" TIMEFORMAT " ms", triptime/1000.0);
			tsum += triptime;
			tsum2 += triptime*triptime;
			if (triptime < tmin)
				tmin = triptime;
			if (triptime > tmax)
				tmax = triptime;
		}
		(void) putchar('\n');
		/*
		 * If it's stats, probe-all, npackets > 0, and we received reply
		 * for the last probe sent to this target address, then we
		 * don't need to wait anymore, let's move on to next target
		 * address, now!
		 */
		if (last_reply_from_targetaddr) {
			(void) alarm(0);	/* cancel alarm */
			current_targetaddr->probing_done = _B_TRUE;
			(void) sigrelse(SIGALRM);
			send_scheduled_probe();
			schedule_sigalrm();
		}
		break;

	case MLD_LISTENER_QUERY:
	case MLD_LISTENER_REPORT:
	case MLD_LISTENER_REDUCTION:
	case ND_ROUTER_SOLICIT:
	case ND_ROUTER_ADVERT:
	case ND_NEIGHBOR_SOLICIT:
	case ND_NEIGHBOR_ADVERT:
		return;

	case ND_REDIRECT:
		nd_rdrct = (nd_redirect_t *)icmp6;

		if (cc_left < sizeof (nd_redirect_t) - ICMP6_MINLEN) {
			if (verbose) {
				Printf("packet too short (%d bytes) from %s\n",
				    cc, pr_name6(from6));
			}
			return;
		}
		dst_addr.addr6 = nd_rdrct->nd_rd_dst;
		if (is_a_target(ai_dst, &dst_addr) || verbose) {
			Printf("ICMPv6 redirect from gateway %s\n",
			    pr_name6(from6));

			Printf(" to %s",
			    pr_name((char *)&nd_rdrct->nd_rd_target, AF_INET6));
			Printf(" for %s\n",
			    pr_name((char *)&nd_rdrct->nd_rd_dst, AF_INET6));
		}
		break;

	default:
		if (verbose) {
			Printf("%d bytes from %s:\n", cc, pr_name6(from6));
			Printf("icmp6_type=%d (%s) ", icmp6->icmp6_type,
			    pr_type6(icmp6->icmp6_type));
			Printf("icmp6_code=%d\n", icmp6->icmp6_code);
			for (i = 0; i < 12; i++) {
				Printf("x%2.2x: x%8.8x\n",
				    i * sizeof (int32_t), *intp++);
			}
		}
		break;
	}

	/*
	 * If it's verbose mode and we recv'd ancillary data, print extension
	 * headers.
	 */
	if (verbose && msg->msg_controllen > 0)
		pr_ext_headers(msg);
}

/*
 * Convert an ICMP6 "type" field to a printable string.
 */
static char *
pr_type6(uchar_t icmp6_type)
{
	static struct icmptype_table ttab6[] = {
		{ICMP6_DST_UNREACH,		"Dest Unreachable"},
		{ICMP6_PACKET_TOO_BIG,		"Packet Too Big"},
		{ICMP6_TIME_EXCEEDED,		"Time Exceeded"},
		{ICMP6_PARAM_PROB,		"Parameter Problem"},
		{ICMP6_ECHO_REQUEST,		"Echo Request"},
		{ICMP6_ECHO_REPLY,		"Echo Reply"},
		{MLD_LISTENER_QUERY,		"Multicast Listener Query"},
		{MLD_LISTENER_REPORT,		"Multicast Listener Report"},
		{MLD_LISTENER_REDUCTION,	"Multicast Listener Done"},
		{ND_ROUTER_SOLICIT,		"Router Solicitation"},
		{ND_ROUTER_ADVERT,		"Router Advertisement"},
		{ND_NEIGHBOR_SOLICIT,		"Neighbor Solicitation"},
		{ND_NEIGHBOR_ADVERT,		"Neighbor Advertisement"},
		{ND_REDIRECT,			"Redirect Message"},
	};
	int i;

	for (i = 0; i < A_CNT(ttab6); i++) {
		if (ttab6[i].type == icmp6_type)
			return (ttab6[i].message);

	}

	return ("OUT-OF-RANGE");
}

/*
 * Return the length of the IPv6 related headers (including extension headers).
 * It also sets the *last_hdr_rtrn to the first upper layer protocol header
 * following IPv6 header and extension headers. If print_flag is _B_TRUE, it
 * prints extension headers.
 */
static int
IPv6_hdrlen(ip6_t *ip6h, int pkt_len, uint8_t *last_hdr_rtrn)
{
	int length;
	int exthdrlength;
	uint8_t nexthdr;
	uint8_t *whereptr;
	ip6_hbh_t *hbhhdr;
	ip6_dest_t *desthdr;
	ip6_rthdr_t *rthdr;
	ip6_frag_t *fraghdr;
	uint8_t	*endptr;

	length = sizeof (ip6_t);

	whereptr = ((uint8_t *)&ip6h[1]);	/* point to next hdr */
	endptr = ((uint8_t *)ip6h) + pkt_len;

	nexthdr = ip6h->ip6_nxt;
	*last_hdr_rtrn = IPPROTO_NONE;

	if (whereptr >= endptr)
		return (length);

	while (whereptr < endptr) {
		*last_hdr_rtrn = nexthdr;
		switch (nexthdr) {
		case IPPROTO_HOPOPTS:
			hbhhdr = (ip6_hbh_t *)whereptr;
			exthdrlength = 8 * (hbhhdr->ip6h_len + 1);
			if ((uchar_t *)hbhhdr + exthdrlength > endptr)
				return (length);
			nexthdr = hbhhdr->ip6h_nxt;
			length += exthdrlength;
			break;

		case IPPROTO_DSTOPTS:
			desthdr = (ip6_dest_t *)whereptr;
			exthdrlength = 8 * (desthdr->ip6d_len + 1);
			if ((uchar_t *)desthdr + exthdrlength > endptr)
				return (length);
			nexthdr = desthdr->ip6d_nxt;
			length += exthdrlength;
			break;

		case IPPROTO_ROUTING:
			rthdr = (ip6_rthdr_t *)whereptr;
			exthdrlength = 8 * (rthdr->ip6r_len + 1);
			if ((uchar_t *)rthdr + exthdrlength > endptr)
				return (length);
			nexthdr = rthdr->ip6r_nxt;
			length += exthdrlength;
			break;

		case IPPROTO_FRAGMENT:
			/* LINTED */
			fraghdr = (ip6_frag_t *)whereptr;
			if ((uchar_t *)&fraghdr[1] > endptr)
				return (length);
			nexthdr = fraghdr->ip6f_nxt;
			length += sizeof (struct ip6_frag);
			break;

		case IPPROTO_NONE:
		default:
			return (length);
		}
		whereptr = (uint8_t *)ip6h + length;
	}
	*last_hdr_rtrn = nexthdr;

	return (length);
}

/*
 * Print extension headers
 */
static void
pr_ext_headers(struct msghdr *msg)
{
	struct cmsghdr *cmsg;

	Printf("  IPv6 extension headers: ");

	for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
	    cmsg = CMSG_NXTHDR(msg, cmsg)) {
		if (cmsg->cmsg_level == IPPROTO_IPV6) {
			switch (cmsg->cmsg_type) {
			case IPV6_HOPOPTS:
				Printf(" <hop-by-hop options>");
				break;

			case IPV6_DSTOPTS:
				Printf(" <destination options (after routing"
				    "header)>");
				break;

			case IPV6_RTHDRDSTOPTS:
				Printf(" <destination options (before routing"
				    "header)>");
				break;

			case IPV6_RTHDR:
				pr_rthdr((uchar_t *)CMSG_DATA(cmsg));
				break;

			default:
				Printf(" <option type %d>", cmsg->cmsg_type);
				break;
			}
		}
	}
	(void) putchar('\n');
}

/*
 * Print the routing header 0 information
 */
static void
pr_rthdr(uchar_t *buf)
{
	ip6_rthdr_t *rthdr;
	ip6_rthdr0_t *rthdr0;
	struct in6_addr *gw_addr;
	int i, num_addr;

	rthdr = (ip6_rthdr_t *)buf;
	Printf(" <type %d routing header, segleft %u> ",
	    rthdr->ip6r_type, rthdr->ip6r_segleft);

	if (rthdr->ip6r_type == 0) {
		/* LINTED */
		rthdr0 = (ip6_rthdr0_t *)buf;
		gw_addr = (struct in6_addr *)(rthdr0 + 1);
		num_addr = rthdr0->ip6r0_len / 2;

		for (i = 0; i < num_addr; i++) {
			Printf("%s", pr_name((char *)gw_addr, AF_INET6));
			if (i == (num_addr - rthdr0->ip6r0_segleft))
				Printf("(Current)");
			gw_addr++;
			if (i != num_addr - 1)
				Printf(",  ");
		}
	}
}