summaryrefslogtreecommitdiff
path: root/mbglib/common/lan_util.c
blob: 19cbcfcf502987abe86df3e165f7b822bda3252a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938

/**************************************************************************
 *
 *  $Id: lan_util.c 1.11.1.14 2017/04/10 13:05:16 martin TEST $
 *
 *  Copyright (c) Meinberg Funkuhren, Bad Pyrmont, Germany
 *
 *  Description:
 *    Utility functions useful for network programming.
 *
 * -----------------------------------------------------------------------
 *  $Log: lan_util.c $
 *  Revision 1.11.1.14  2017/04/10 13:05:16  martin
 *  Fixed some compiler warnings.
 *  Revision 1.11.1.13  2017/02/23 15:24:22Z  martin
 *  Fixed macro definition syntax to avoid clang compiler warnings.
 *  Revision 1.11.1.12  2016/10/31 17:39:47  martin
 *  Only return standard MBG_RETURN_CODES.
 *  Removed definitions of old MBG_LU_... return codes.
 *  Renamed check_octets_not_all_zero() to octets_are_all_zero(), which returns a bool now.
 *  Renamed check_mac_addr_not_all_zero() to mac_addr_all_zero(), which returns a bool now.
 *  Removed get_port_mac_addr_check().
 *  Updated doxygen comments.
 *  Revision 1.11.1.11  2016/09/22 12:25:26  thomas-b
 *  Fixed compiler warning for uninitialized vars
 *  Revision 1.11.1.10  2016/08/10 12:25:54  martin
 *  Check for MBG_TGT_POSIX instead of MBG_TGT_UNIX.
 *  Revision 1.11.1.9  2016/08/09 07:10:22  martin
 *  *** empty log message ***
 *  Revision 1.11.1.8  2015/12/01 11:35:31  martin
 *  Doxygen fixes.
 *  Revision 1.11.1.7  2015/11/11 18:16:08  martin
 *  New function snprint_ptp_clock_id().
 *  Revision 1.11.1.6  2015/11/04 17:06:35Z  martin
 *  *** empty log message ***
 *  Revision 1.11.1.5  2015/09/17 10:06:30  martin
 *  Revision 1.11.1.4  2015/08/31 10:26:26Z  martin
 *  Revision 1.11.1.3  2015/08/27 16:23:16Z  martin
 *  Use safe string functions from str_util.c.
 *  Cleanup.
 *  Revision 1.11.1.2  2015/04/13 15:26:50  hannes
 *  Added all function defintions for IP6.
 *  FIX: Fixed snprint_ip4_cidr_mask to behave as expected.
 *  It will concatenate the cidr mask bits to the ip address now.
 *  Revision 1.11.1.1  2015/04/02 15:28:31  hannes
 *  Started adding the ipv4 functions for ipv6.
 *  Revision 1.11  2015/04/01 14:31:14  hannes
 *  Fix: cidr_str_to_ip4_addr_and_net_mask: Defaults correctly to
 *  netmask 0.0.0.0 (/0) for no CIDR extension in cidr_str.
 *  Revision 1.10  2014/10/17 12:45:48  martin
 *  Let str_to_ip4_addr() return 0 if an empty string has been passed.
 *  Revision 1.9  2014/09/24 08:31:00  martin
 *  Exclude get_ip4_gateway() from build if USE_MBG_TSU is defined.
 *  Fixed some compiler warnings.
 *  Added and modified some comments.
 *  Revision 1.8  2013/10/02 07:19:13  martin
 *  New function get_port_intf_idx.
 *  Fixed naming.of local netlink support functions.
 *  Revision 1.7  2013/05/22 16:49:42  martin
 *  Fixed some return codes.
 *  Revision 1.6  2013/03/19 10:24:51  martin
 *  Fixed bugs in get_ip4_gateway(): A skipped routing entry was
 *  taken as default route, and thus a wrong default route 0.0.0.0
 *  could be returned erraneously. Also, malloc() was used without
 *  checking the result.
 *  Added conditional debug code.
 *  Revision 1.5  2013/02/19 15:13:10  martin
 *  Added some new functions.
 *  Updated doxygen comments.
 *  Revision 1.4  2012/11/02 09:16:57  martin
 *  Fixed build under Windows.
 *  Revision 1.3  2012/10/02 18:23:28Z  martin
 *  Removed obsolete code to avoid compiler warning.
 *  Revision 1.2  2012/03/09 08:49:19  martin
 *  Added some commonly used functions.
 *  Revision 1.1  2011/03/04 10:01:32Z  martin
 *  Initial revision.
 *
 **************************************************************************/

#define _LAN_UTIL
  #include <lan_util.h>
#undef _LAN_UTIL

#include <words.h>
#include <str_util.h>
#include <mbgerror.h>

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

#if defined( MBG_TGT_POSIX )

  #if defined( MBG_TGT_LINUX )

    #include <linux/types.h>

    // Some older versions of linux/types.h don't define u8..u64
    // for user space applications. However, if they do they also
    // define BITS_PER_LONG, so we use this symbol to figure out
    // if we need to define u8..u64 by ourselves.
    #if !defined( BITS_PER_LONG )
      typedef uint8_t u8;
      typedef uint16_t u16;
      typedef uint32_t u32;
      typedef uint64_t u64;
    #endif

    #include <linux/sockios.h>
    #include <linux/ethtool.h>
    #include <linux/rtnetlink.h>
  #endif

  #include <unistd.h>
  #include <syslog.h>
  #include <sys/ioctl.h>
  #include <arpa/inet.h>
  #include <netinet/in.h>

#else

  // dummy codes, the functions will report an error ...
  #define SIOCGIFADDR      0
  #define SIOCGIFNETMASK   0
  #define SIOCGIFBRDADDR   0

  #if defined( MBG_TGT_WIN32 )
    #define snprintf _snprintf
  #endif

#endif


#if !defined( DEBUG_NETLINK )
  #if ( 0 && defined( DEBUG ) && defined( MBG_TGT_LINUX ) )
    #define DEBUG_NETLINK  1
  #else
    #define DEBUG_NETLINK  0
  #endif
#endif


#if DEBUG_NETLINK
  // we need a function to output debugging information
  #if !defined STANDALONE
    #include <ptp2_cnf.h>  // for mbglog() from the ARM PTP projects
  #else
    // to be provided by the application
    extern __attribute__( ( format( printf, 2, 3 ) ) ) void mbglog( int priority, const char *fmt, ... );
  #endif
#endif  // DEBUG_NETLINK



// Maximum size of an IPv4 address string in dotted quad format,
// including a terminating 0, and thus the required minimum size
// for a buffer to take such a string. i.e. "aaa.bbb.ccc.ddd\0".
#define MAX_IP4_ADDR_STR_SIZE   16


#if defined( MBG_TGT_LINUX )

struct route_info
{
  struct in_addr dstAddr;
  struct in_addr srcAddr;
  struct in_addr gateWay;
  char ifName[IF_NAMESIZE];
};

#endif



/*HDR*/
/**
 * @brief Count the number of sequential bits in an IPv4 net mask
 *
 * Counting starts from MSB, i.e. for 0xC0 and 0xC1 the results
 * are both 2 since only the 2 MSBs are sequentially set.
 *
 * @param[in]  p_mask  The IPv4 net mask to be evaluated
 *
 * @return The number of sequential MSB bits set in *p_mask
 *
 * @see ::ip4_net_mask_from_cidr
 */
int get_ip4_net_mask_bits( const IP4_ADDR *p_mask )
{
  IP4_ADDR msb_mask = IP4_MSB_MASK;
  int i;

  for ( i = 0; i < MAX_IP4_BITS; i++ )
  {
    if ( ( *p_mask & msb_mask ) == 0 )
      break;

    msb_mask >>= 1;
  }

  return i;

}  // get_ip4_net_mask_bits



/*HDR*/
/**
 * @brief Print an IPv4 address to a dotted quad formatted string
 *
 * @param[out] s        The string buffer to be filled
 * @param[in]  max_len  Size of the output buffer for 0-terminated string
 * @param[in]  p_addr   The IPv4 address to be evaluated
 * @param[in]  info     An optional string which is prepended to the string, or NULL
 *
 * @return The overall number of characters printed to the string
 *
 * @see ::snprint_ip4_cidr_addr
 * @see ::str_to_ip4_addr
 * @see ::cidr_str_to_ip4_addr_and_net_mask
 */
size_t snprint_ip4_addr( char *s, size_t max_len, const IP4_ADDR *p_addr, const char *info )
{
  size_t n = 0;
  ulong ul = *p_addr;

  if ( info )
    n += snprintf_safe( s, max_len, "%s", info );

  // Don't use byte pointers here since this is not safe
  // for both little and big endian targets.
  n += snprintf_safe( &s[n], max_len - n, "%u.%u.%u.%u",
                 BYTE_3( ul ), BYTE_2( ul ),
                 BYTE_1( ul ), BYTE_0( ul )
               );
  return n;

}  // snprint_ip4_addr



/*HDR*/
/**
 * @brief Print an IPv4 address plus net mask in CIDR notation to a string
 *
 * The printed CIDR string is something like "172.16.3.250/24"
 *
 * @param[out] s        The string buffer to be filled
 * @param[in]  max_len  Size of the output buffer for 0-terminated string
 * @param[in]  p_addr   The IPv4 address to be evaluated
 * @param[in]  p_mask   The associated IPv4 net mask
 * @param[in]  info     An optional string which is prepended to the string, or NULL
 *
 * @return The overall number of characters printed to the string
 *
 * @see ::snprint_ip4_addr
 * @see ::str_to_ip4_addr
 * @see ::cidr_str_to_ip4_addr_and_net_mask
 */
size_t snprint_ip4_cidr_addr( char *s, size_t max_len, const IP4_ADDR *p_addr,
                              const IP4_ADDR *p_mask, const char *info )
{
  int cidr_mask_bits;
  size_t n = snprint_ip4_addr( s, max_len, p_addr, info );

  cidr_mask_bits = get_ip4_net_mask_bits( p_mask );

  if ( ( cidr_mask_bits >= MIN_IP4_CIDR_NETMASK_BITS ) &&
       ( cidr_mask_bits <= MAX_IP4_CIDR_NETMASK_BITS ) )
    n += snprintf_safe( &s[n], max_len - n, "/%i", cidr_mask_bits );

  return n;

}  // snprint_ip4_cidr_addr



/*HDR*/
/**
 * @brief Convert a string to an ::IP4_ADDR
 *
 * If output parameter is specified as NULL then this function
 * can be used to check if the IPv4 address string is formally correct.
 *
 * @param[out] p_addr  Pointer to an ::IP4_ADDR variable to be filled, or NULL
 * @param[in]  s       An IPv4 address string to be converted
 *
 * @return  A number >= 0 (::MBG_SUCCESS) according to the number of characters evaluated
 *          from the input string, or one of the @ref MBG_ERROR_CODES on error,
 *          specifically ::MBG_ERR_INV_PARM if an invalid number or character was found in the string.
 *
 * @see ::snprint_ip4_addr
 * @see ::snprint_ip4_cidr_addr
 * @see ::cidr_str_to_ip4_addr_and_net_mask
 */
int str_to_ip4_addr( IP4_ADDR *p_addr, const char *s )
{
  IP4_ADDR tmp_ip4_addr = 0;
  const char *cp = s;
  int i;

  if ( strlen( s ) )
  {
    for ( i = 0; ; )
    {
      unsigned long ul = strtoul( (char *) cp, (char **) &cp, 10 );

      if ( ul > 0xFFUL )  // invalid number
        return MBG_ERR_INV_PARM;

      tmp_ip4_addr |= ul << ( 8 * (3 - i) );

      if ( ++i >= 4 )
        break;        // done

      if ( *cp != '.' )
        return MBG_ERR_INV_PARM;    // invalid string format, dot expected

      cp++;  // skip dot
    }
  }

  if ( p_addr )
    *p_addr = tmp_ip4_addr;

  // success: return the number of evaluated chars
  return (int) ( cp - s );

}  // str_to_ip4_addr



/*HDR*/
/**
 * @brief Convert a string in CIDR notation to an ::IP4_ADDR and net mask
 *
 * If output parameters are specified as NULL then this function
 * can be used to check if the CIDR string is formally correct.
 *
 * @param[out] p_addr    Pointer to an ::IP4_ADDR variable to be filled with
 *                       the IPv4 address, or NULL
 * @param[out] p_mask    Pointer to an ::IP4_ADDR variable to be filled with
 *                       the IPv4 net mask, or NULL
 * @param[in]  cidr_str  The string to be converted, in CIDR format, e.g. "172.16.3.250/24"
 *
 * @return  A number >= 0 (::MBG_SUCCESS) according to the number of characters evaluated
 *          from the input string, or one of the @ref MBG_ERROR_CODES on error,
 *          specifically ::MBG_ERR_INV_PARM if an invalid number or character was found in the string.
 *
 * @see ::snprint_ip4_addr
 * @see ::snprint_ip4_cidr_addr
 * @see ::str_to_ip4_addr
 */
int cidr_str_to_ip4_addr_and_net_mask( IP4_ADDR *p_addr, IP4_ADDR *p_mask,
                                       const char *cidr_str )
{
  IP4_ADDR mask;
  long cidr_mask_bits;
  const char *cp;
  int l;
  int rc = str_to_ip4_addr( p_addr, cidr_str );

  if ( mbg_rc_is_error( rc ) )
    return rc;


  l = (int) strlen( cidr_str );

  if ( l < rc )  // input string too short
    return MBG_ERR_INV_PARM;


  cp = &cidr_str[rc];

  if ( *cp == 0 )  // end of string
  {
    // The string has no CIDR extension, so
    // assume "/0", i.e. host mask 0.0.0.0;
    mask = (IP4_ADDR) 0;
    goto done;
  }


  if ( *cp != '/' )
    return MBG_ERR_INV_PARM;


  cp++;
  cidr_mask_bits = strtol( (char *) cp, (char **) &cp, 10 );

  if ( ( cidr_mask_bits < MIN_IP4_CIDR_NETMASK_BITS ) ||
       ( cidr_mask_bits > MAX_IP4_CIDR_NETMASK_BITS ) )
    return MBG_ERR_RANGE;


  mask = ip4_net_mask_from_cidr( (int) cidr_mask_bits );

done:
  if ( p_mask )
    *p_mask = mask;

  // success: return the number of evaluated chars
  return (int) ( cp - cidr_str );

}  // cidr_str_to_ip4_addr_and_net_mask



/*HDR*/
/**
 * @brief Count the number of sequential bits in an IPv6 net mask
 *
 * Counting starts from MSB, i.e. for 0xC0 and 0xC1 the results
 * are both 2 since only the 2 MSBs are sequentially set.
 *
 * @param[in]  p_mask  The IPv6 net mask to be evaluated
 *
 * @return The number of sequential MSB bits set in *p_mask
 *
 * @see ::ip6_net_mask_from_cidr
 */
int get_ip6_net_mask_bits( const IP6_ADDR *p_mask )
{
  int i;
  int cnt = 0;
  uint8_t msb_mask = IP6_MSB_MASK;

  for ( i = IP6_ADDR_BYTES - 1 ; i >= 0; i-- )
  {
    if ( p_mask->b[i] == 0xff )
      cnt += 8;
    else
    {
      for ( ; cnt < MAX_IP6_CIDR_NETMASK_BITS; cnt++ )
      {
        if ( ( p_mask->b[i] & msb_mask ) == 0 )
          break;

        msb_mask >>= 1;
      }
      break;
    }
  }

  return cnt;

}  // get_ip6_net_mask_bits



/*HDR*/
/**
 * @brief Print an IPv6 address in optimized format to a string
 *
 * @param[out] s        The string buffer to be filled
 * @param[in]  max_len  Size of the output buffer for 0-terminated string
 * @param[in]  p_addr   The IPv6 address to be evaluated
 * @param[in]  info     An optional string which is prepended to the string, or NULL
 *
 * @return The overall number of characters printed to the string
 *
 * @see ::snprint_ip6_cidr_addr
 * @see ::snprint_ip6_cidr_mask_addr
 * @see ::str_to_ip6_addr
 * @see ::cidr_str_to_ip6_addr_and_cidr_bits
 * @see ::cidr_str_to_ip6_addr_and_net_mask
 */
size_t snprint_ip6_addr( char *s, size_t max_len, const IP6_ADDR *p_addr, const char *info )
{
  // Copied from inet_ntop.c, and reversed byte order

  IP6_ADDR_STR tmp;
  char *tp;
  #define NUM_WORDS ( (int) ( sizeof( IP6_ADDR_STR ) / sizeof( uint16_t ) ) )
  uint16_t words[NUM_WORDS] = { 0 };
  int i;
  size_t n = 0;
  struct
  {
    int base;
    int len;
  } best = { 0 }, cur = { 0 };

  /*
   * Preprocess:
   *      Copy the input (bytewise) array into a wordwise array.
   *      Find the longest run of 0x00's in p_addr->b[] for :: shorthanding.
   */
  for ( i = IP6_ADDR_BYTES - 1; i >= 0; i-- )
    words[(IP6_ADDR_BYTES - 1 - i) / 2] |= (p_addr->b[i] << ((1 - ((IP6_ADDR_BYTES - 1  - i) % 2)) << 3));

  best.base = -1;
  cur.base = -1;

  for ( i = 0; i < NUM_WORDS; i++ )
  {
    if ( words[i] == 0 )
    {
      if ( cur.base == -1 )
        cur.base = i, cur.len = 1;
      else
        cur.len++;
    }
    else
    {
      if ( cur.base != -1 )
      {
        if ( best.base == -1 || cur.len > best.len )
            best = cur;

        cur.base = -1;
      }
    }
  }

  if ( cur.base != -1 )
  {
    if ( best.base == -1 || cur.len > best.len )
      best = cur;
  }

  if ( best.base != -1 && best.len < 2 )
    best.base = -1;

  // Format the result.

  tp = tmp;

  for ( i = 0; i < NUM_WORDS; i++ )
  {
    /* Are we inside the best run of 0x00's? */
    if ( best.base != -1 && i >= best.base && i < ( best.base + best.len ) )
    {
      if (i == best.base)
        *tp++ = ':';

      continue;
    }

    /* Are we following an initial run of 0x00s or any real hex? */
    if ( i != 0 )
      *tp++ = ':';

    /* Is this address an encapsulated IPv4? */
    if ( i == 6 && best.base == 0 && ( best.len == 6 || ( best.len == 5 && words[5] == 0xffff ) ) )
        return MBG_ERR_INV_PARM; // we don't support ecapsulated IPv4

    sprintf( tp, "%x", words[i] );
    tp += strlen( tp );
  }

  /* Was it a trailing run of 0x00's? */
  if ( best.base != -1 && ( best.base + best.len ) == NUM_WORDS )
    *tp++ = ':';

  *tp++ = '\0';

  /*
   * Check for overflow, copy, and we're done.
   */
  if ( ( tp - tmp ) > (int) max_len )
    return MBG_ERR_OVERFLOW;

  if ( info )
    n += snprintf_safe( s, max_len, "%s", info );

  n += snprintf_safe( &s[n], max_len - n, "%s", tmp );

  return n;

  #undef NUM_WORDS

}  // snprint_ip6_addr



/*HDR*/
/**
 * @brief Print an IPv6 address plus net mask to string in CIDR notation
 *
 * The printed CIDR string is something like "2001:0DB8:0:CD30:EF45::/64"
 *
 * @param[out] s        The string buffer to be filled
 * @param[in]  max_len  Size of the output buffer for 0-terminated string
 * @param[in]  p_addr   The IPv6 address to be evaluated
 * @param[in]  p_mask   The associated IPv6 net mask
 * @param[in]  info     An optional string which is prepended to the string, or NULL
 *
 * @return The overall number of characters printed to the string
 *
 * @see ::snprint_ip6_addr
 * @see ::snprint_ip6_cidr_mask_addr
 * @see ::str_to_ip6_addr
 * @see ::cidr_str_to_ip6_addr_and_cidr_bits
 * @see ::cidr_str_to_ip6_addr_and_net_mask
 */
size_t snprint_ip6_cidr_addr( char *s, size_t max_len, const IP6_ADDR *p_addr,
                              const IP6_ADDR *p_mask, const char *info )
{
  size_t n = snprint_ip6_addr( s, max_len, p_addr, info );

  int cidr_mask_bits = get_ip6_net_mask_bits( p_mask );

  if ( ( cidr_mask_bits >= MIN_IP6_CIDR_NETMASK_BITS ) &&
       ( cidr_mask_bits <= MAX_IP6_CIDR_NETMASK_BITS ) )
    n += snprintf_safe( &s[n], max_len - n, "/%i", cidr_mask_bits );

  return n;

}  // snprint_ip6_cidr_addr



/*HDR*/
/**
 * @brief Print an IPv6 address plus number of net mask bits to string in CIDR notation
 *
 * The printed CIDR string is something like "2001:0DB8:0:CD30:EF45::/64"
 *
 * @param[out] s               The string buffer to be filled
 * @param[in]  max_len         Size of the output buffer for 0-terminated string
 * @param[in]  p_addr          The IPv6 address to be evaluated
 * @param[in]  cidr_mask_bits  The CIDR number of bits specifying the IPv6 net mask
 * @param[in]  info            An optional string which is prepended to the string, or NULL
 *
 * @return The overall number of characters printed to the string
 *
 * @see ::snprint_ip6_addr
 * @see ::snprint_ip6_cidr_addr
 * @see ::str_to_ip6_addr
 * @see ::cidr_str_to_ip6_addr_and_cidr_bits
 * @see ::cidr_str_to_ip6_addr_and_net_mask
 */
size_t snprint_ip6_cidr_mask_addr( char *s, size_t max_len, const IP6_ADDR *p_addr,
                                   const int cidr_mask_bits, const char* info )
{
  size_t n;
  IP6_ADDR mask;

  ip6_net_mask_from_cidr( &mask, cidr_mask_bits );

  n = snprint_ip6_addr( s, max_len, p_addr, info );

  if ( ( cidr_mask_bits >= MIN_IP6_CIDR_NETMASK_BITS ) &&
        ( cidr_mask_bits <= MAX_IP6_CIDR_NETMASK_BITS ) )
    n += snprintf_safe( &s[n], max_len - n, "/%i", cidr_mask_bits );

  return n;

}  // snprint_ip6_cidr_mask_addr



/*HDR*/
/**
 * @brief Convert a string to an ::IP6_ADDR
 *
 * If the output parameter is specified as NULL then this function
 * can be used to check if the string is formally correct.
 *
 * On success ::IP6_ADDR variable contains the IPv6 address
 * in little endian byte order.
 *
 * @param[out] p_addr  Pointer to the ::IP6_ADDR variable, or NULL
 * @param[in]  s       A string containing an IPv6 address
 *
 * @return  A number >= 0 (::MBG_SUCCESS) according to the number of characters evaluated
 *          from the input string, or one of the @ref MBG_ERROR_CODES on error,
 *          specifically ::MBG_ERR_INV_PARM if an invalid number or character was found in the string.
 *
 * @see ::snprint_ip6_addr
 * @see ::snprint_ip6_cidr_addr
 * @see ::snprint_ip6_cidr_mask_addr
 * @see ::str_to_ip6_addr
 * @see ::cidr_str_to_ip6_addr_and_cidr_bits
 * @see ::cidr_str_to_ip6_addr_and_net_mask
 */
int str_to_ip6_addr( IP6_ADDR *p_addr, const char *s )
{
  // copied from inet_pton.c and reversed byte order
  IP6_ADDR tmp = { { 0 } };
  static const char xdigits[] = "0123456789abcdef";
  uint8_t *tp;
  uint8_t *startp;
  uint8_t *colonp;
  int ch;
  int saw_xdigit;
  int read_cnt = 0;
  unsigned int val;

  if ( p_addr )
    memset( p_addr, 0, sizeof( *p_addr ) );  // set IP address to ::

  startp = tmp.b - 1;
  tp = startp + sizeof( tmp );

  colonp = NULL;

  /* Leading :: requires some special handling. */
  if ( *s == ':' )
  {
    read_cnt++;

    if ( *++s != ':' )
      return MBG_ERR_INV_PARM;
  }

  saw_xdigit = 0;
  val = 0;

  while ( ( ch = tolower( *s++ ) ) != '\0' )
  {
    const char *pch;

    read_cnt++;

    pch = strchr( xdigits, ch );

    if ( pch != NULL )
    {
      val <<= 4;
      val |= ( pch - xdigits );

      if ( val > 0xffff )    //### TODO signed? unsigned?
        return MBG_ERR_INV_PARM;

      saw_xdigit = 1;
      continue;
    }

    if ( ch == ':' )
    {
      if ( !saw_xdigit )
      {
        if ( colonp )
          return MBG_ERR_INV_PARM;

        colonp = tp;
        continue;

      }
      else
        if ( *s == '\0' )
          return MBG_ERR_INV_PARM;

      if ( tp - sizeof( uint16_t ) < startp )
        return MBG_ERR_INV_PARM;

      *tp-- = (uint8_t) ( val >> 8 ) & 0xff;
      *tp-- = (uint8_t) val & 0xff;
      saw_xdigit = 0;
      val = 0;
      continue;
    }

    if ( ch == '/' )  // cidr notation. we reached the end
    {
      read_cnt--;
      break;
    }

    return MBG_ERR_INV_PARM;
  }

  if ( saw_xdigit )
  {
    if ( tp - sizeof( uint16_t ) < startp )
      return MBG_ERR_INV_PARM;

    *tp-- = (uint8_t) (val >> 8) & 0xff;
    *tp-- = (uint8_t) val & 0xff;
  }

  if ( colonp != NULL )
  {
    /*
     * Since some memmove()'s erroneously fail to handle
     * overlapping regions, we'll do the shift by hand.
     */
    const size_t n = colonp - tp;
    size_t i;

    if ( tp == startp )
      return MBG_ERR_INV_PARM;

    for ( i = 0; i <= n; i++ )
    {
      startp[i] = colonp[i - n];
      colonp[i - n] = 0;
    }

    tp = startp;
  }

  if ( tp != startp )
    return MBG_ERR_INV_PARM;

  if ( p_addr )
    *p_addr = tmp;

  return read_cnt;

}  // str_to_ip6_addr



/*HDR*/
/**
 * @brief Convert a string in CIDR notation to an ::IP6_ADDR and net mask
 *
 * If output parameters are specified as NULL then this function
 * can be used to check if the CIDR string is formally correct.
 *
 * @param[out] p_addr  Pointer to an ::IP6_ADDR variable to be filled up
 *                     with the IPv6 address, or NULL
 * @param[out] p_mask  Pointer to an ::IP6_ADDR variable to be filled up
                       with the net mask bits, or NULL
 * @param[in] cidr_str The string to be converted, in CIDR format, e.g. "2001:0DB8:0:CD30::/64"
 *
 * @return  A number >= 0 (::MBG_SUCCESS) according to the number of characters evaluated
 *          from the input string, or one of the @ref MBG_ERROR_CODES on error,
 *          specifically ::MBG_ERR_INV_PARM if an invalid number or character was found in the string.
 *
 * @see ::snprint_ip4_addr
 * @see ::snprint_ip4_cidr_addr
 * @see ::str_to_ip4_addr
 */
int cidr_str_to_ip6_addr_and_net_mask( IP6_ADDR *p_addr, IP6_ADDR *p_mask, const char *cidr_str )
{
  int mask = 0;
  int rc = cidr_str_to_ip6_addr_and_cidr_bits( p_addr, &mask, cidr_str );

  if ( mbg_rc_is_error( rc ) )
    return rc;

  if ( p_mask )
    ip6_net_mask_from_cidr( p_mask, mask );

  return rc;

}  // cidr_str_to_ip6_addr_and_net_mask



/*HDR*/
/**
 * @brief Convert a string in CIDR notation to an ::IP6_ADDR and net mask bits
 *
 * If output parameters are specified as NULL then this function
 * can be used to check if the CIDR string is formally correct.
 *
 * @param[out] p_addr    Pointer to an ::IP6_ADDR variable for the IPv6 address, or NULL
 * @param[out] p_cidr    Pointer to an int variable for the net mask bits, or NULL
 * @param[in]  cidr_str  The string to be converted, in CIDR format, e.g. "2001:0DB8:0:CD30::/64"
 *
 * @return  A number >= 0 (::MBG_SUCCESS) according to the number of characters evaluated
 *          from the input string, or one of the @ref MBG_ERROR_CODES on error,
 *          specifically ::MBG_ERR_INV_PARM if an invalid number or character was found in the string.
 *
 * @see ::snprint_ip6_addr
 * @see ::snprint_ip6_cidr_addr
 * @see ::str_to_ip6_addr
 */
int cidr_str_to_ip6_addr_and_cidr_bits( IP6_ADDR *p_addr, int *p_cidr,
                                        const char *cidr_str )
{
  long cidr_mask_bits;
  const char *cp;
  ssize_t l;
  int rc = str_to_ip6_addr( p_addr, cidr_str );

  if ( mbg_rc_is_error( rc ) )
    return rc;

  l = strlen( cidr_str );

  if ( l < rc )  // input string too short
    return MBG_ERR_INV_PARM;

  cp = &cidr_str[rc];

  if ( *cp == 0 )  // end of string
  {
    // The string has no CIDR extension, so
    // assume "/0", i.e. host mask ::
    cidr_mask_bits = 0;
    goto done;
  }

  if ( *cp != '/' )
    return MBG_ERR_INV_PARM;

  cp++;
  cidr_mask_bits = strtol( (char *) cp, (char **) &cp, 10 );

  if ( ( cidr_mask_bits < MIN_IP6_CIDR_NETMASK_BITS ) ||
       ( cidr_mask_bits > MAX_IP6_CIDR_NETMASK_BITS ) )
    return MBG_ERR_RANGE;

done:
  if ( p_cidr )
    *p_cidr = (int) cidr_mask_bits;

  // success: return the number of evaluated chars
  return (int) ( cp - cidr_str );

}  // cidr_str_to_ip6_addr_and_cidr_bits



/*HDR*/
/**
 * @brief Compute an IPv6 net mask according to the number of CIDR netmask bits
 *
 * E.g. the 64 bits mentioned in "2001:0DB8:0:CD30::/64" result in 2^64,
 * corresponding to FFFF:FFFF:FFFF:FFFF:: in IPv6 notation.
 *
 * @param[out] p_mask        Pointer to an ::IP6_ADDR variable for the IPv6 netmask
 * @param[in]  netmask_bits  Number of netmask bits from CIDR notation
 *
 * @see ::get_ip6_net_mask_bits
 */
void ip6_net_mask_from_cidr( IP6_ADDR *p_mask, int netmask_bits )
{
  int i = 0;

  if ( p_mask )
  {
    memset( p_mask, 0, sizeof( *p_mask ) );

    if ( netmask_bits < 0 )
      netmask_bits = 0;
    else
      if ( netmask_bits >= IP6_ADDR_BITS )
        netmask_bits = IP6_ADDR_BITS;

    for ( i = IP6_ADDR_BYTES - 1; i >= 0; i-- )
    {
      if ( netmask_bits > 8 )
      {
        p_mask->b[i] = 0xff;
        netmask_bits -= 8;
      }
      else
      {
        p_mask->b[i] = (0xff << ( 8 - netmask_bits ) ) & 0xff;
        netmask_bits = 0;
      }
    }
  }

}  // ip6_net_mask_from_cidr



/*HDR*/
/**
 * @brief Determine the network part of an IPv6 address based on the net mask
 *
 * E.g. IP "2001:0DB8:0:CD30::", net mask "FFFF:FFFF::" yields network part "2001:0DB8::".
 *
 * @param[out] p_net_part The extracted network part of the IPv6 address
 * @param[in]  p_addr     The IPv6 address to be evaluated
 * @param[in]  p_mask     The associated IPv6 net mask
 */
void ip6_net_part_from_addr( IP6_ADDR *p_net_part, const IP6_ADDR *p_addr,
                             const IP6_ADDR *p_mask )
{
  int i;

  for ( i = IP6_ADDR_BYTES; i-- > 0; )
    p_net_part->b[i] = p_addr->b[i] & p_mask->b[i];

}  // ip6_net_part_from_addr



/*HDR*/
/**
 * @brief Print a MAC ID or similar array of octets to a string
 *
 * @param[out] s           The string buffer to be filled
 * @param[in]  max_len     Maximum length of the string, i.e. size of the buffer
 * @param[in]  octets      An array of octets
 * @param[in]  num_octets  The number of octets to be printed from the array
 * @param[in]  sep         The separator printed between the bytes, or 0
 * @param[in]  info        An optional string which is prepended to the output, or NULL
 *
 * @return  The overall number of characters printed to the string
 *
 * @see ::snprint_mac_addr
 * @see ::str_to_octets
 * @see ::octets_are_all_zero
 */
size_t snprint_octets( char *s, size_t max_len, const uint8_t *octets,
                       int num_octets, char sep, const char *info )
{
  size_t n = 0;
  int i;

  if ( info )
    n += snprintf_safe( s, max_len, "%s", info );

  for ( i = 0; i < num_octets; i++ )
  {
    if ( i && sep )
      n += snprintf_safe( &s[n], max_len - n, "%c", sep );

    n += snprintf_safe( &s[n], max_len - n, "%02X", octets[i] );
  }

  return n;

}  // snprint_octets



/*HDR*/
/**
 * @brief Print a ::PTP_CLOCK_ID to a string
 *
 * @todo Eventually this function should be moved to a different module.
 *
 * @param[out] s        The string buffer to be filled
 * @param[in]  max_len  Maximum length of the string, i.e. size of the buffer
 * @param[in]  p        The ::PTP_CLOCK_ID to be printed
 *
 * @return  The overall number of characters printed to the string
 *
 * @see ::snprint_octets
 */
size_t snprint_ptp_clock_id( char *s, size_t max_len, const PTP_CLOCK_ID *p )
{
  return snprint_octets( s, max_len, p->b, sizeof( *p ), ':', NULL );

}  // snprint_ptp_clock_id



/*HDR*/
/**
 * @brief Print a MAC address to a string
 *
 * @param[out] s           The string buffer to be filled
 * @param[in]  max_len     Maximum length of the string, i.e. size of the buffer
 * @param[in]  p_mac_addr  The MAC address to be printed
 *
 * @return  The overall number of characters printed to the string
 *
 * @see ::snprint_octets
 * @see ::str_to_octets
 * @see ::octets_are_all_zero
 */
size_t snprint_mac_addr( char *s, size_t max_len, const MBG_MAC_ADDR *p_mac_addr )
{
  return snprint_octets( s, max_len, p_mac_addr->b, sizeof( *p_mac_addr ), MAC_SEP_CHAR, NULL );

}  // snprint_mac_addr



/*HDR*/
/**
 * @brief Set a MAC ID or a similar array of octets from a string
 *
 * @param[out] octets      An array of octets to be set up
 * @param[in]  num_octets  The number of octets which can be stored
 * @param[in]  s           The string to be converted
 *
 * @return  The overall number of octets decoded from the string
 *
 * @see ::snprint_octets
 * @see ::snprint_mac_addr
 * @see ::octets_are_all_zero
 */
int str_to_octets( uint8_t *octets, int num_octets, const char *s )
{
  char *cp = (char *) s;
  int i;

  // don't use strtok() since that functions modifies the original string
  for ( i = 0; i < num_octets; )
  {
    octets[i] = (uint8_t) strtoul( cp, &cp, 16 );
    i++;

    if ( *cp == 0 )
      break;      // end of string

    if ( ( *cp != MAC_SEP_CHAR ) && ( *cp != MAC_SEP_CHAR_ALT ) )
      break;      // invalid character

    cp++;
  }

  return i;

}  // str_to_octets



/*HDR*/
/**
 * @brief Check if an array of octets is all zero
 *
 * @param[in] octets      Pointer to the array of octets
 * @param[in] num_octets  Number of octets
 *
 * @return  true if all bytes are 0, else false
 *
 * @see ::snprint_octets
 * @see ::snprint_mac_addr
 * @see ::str_to_octets
 */
bool octets_are_all_zero( const uint8_t *octets, int num_octets )
{
  int i;

  // check if any of the bytes is != 0
  for ( i = 0; i < num_octets; i++ )
    if ( octets[i] != 0 )
      break;

  return i == num_octets;  // true if *all* bytes are 0

}  // octets_are_all_zero



/*HDR*/
/**
 * @brief Check if a MAC address is all zero
 *
 * @param[in] p_addr  Pointer to a MAC address to be checked
 *
 * @return  true if all bytes of the MAC address are 0, else false
 *
 * @see ::octets_are_all_zero
 */
bool mac_addr_is_all_zero( const MBG_MAC_ADDR *p_addr )
{
  return octets_are_all_zero( p_addr->b, sizeof( p_addr->b ) );

}  // mac_addr_is_all_zero



#if defined( MBG_TGT_POSIX )

/*HDR*/
/**
 * @brief Do a SIOCGxxx IOCTL call to read specific information from a LAN interface
 *
 * @param[in]  if_name     Name of the interface
 * @param[in]  ioctl_code  One of the predefined system SIOCGxxx IOCTL codes
 * @param[out] p_ifreq     Pointer to a request buffer
 *
 * @return One of the @ref MBG_RETURN_CODES
 */
int do_siocg_ioctl( const char *if_name, int ioctl_code, struct ifreq *p_ifreq )
{
  int sock_fd;
  int rc;

  if ( strlen( if_name ) > ( IFNAMSIZ - 1 ) )
    return MBG_ERR_INV_PARM;

  sock_fd = socket( AF_INET, SOCK_DGRAM, 0 );   //### TODO: or AF_INET6/PF_INET6 for IPv6

  if ( sock_fd == -1 )  // failed to open socket
    return mbg_get_last_socket_error( "failed to open socket in do_siocg_ioctl" );

  strncpy_safe( p_ifreq->ifr_name, if_name, sizeof( p_ifreq->ifr_name ) );

  rc = ioctl( sock_fd, ioctl_code, p_ifreq );

  if ( rc == -1 )  // ioctl failed, errno has been set appropriately
    rc = mbg_get_last_socket_error( "ioctl failed in do_siocg_ioctl" );
  else
    rc = MBG_SUCCESS;

  close( sock_fd );

  return rc;

}  // do_siocg_ioctl

#endif  //  defined( MBG_TGT_POSIX )



/*HDR*/
/**
 * @brief Retrieve the index of a specific network interface
 *
 * @param[in]  if_name     Name of the interface
 * @param[out] p_intf_idx  Pointer to a variable to be filled up
 *
 * @return One of the @ref MBG_RETURN_CODES.
 *         On error, *p_intf_idx is set to -1.
 */
int get_port_intf_idx( const char *if_name, int *p_intf_idx )
{
  int rc = MBG_ERR_NOT_SUPP_ON_OS;

  #if defined( MBG_TGT_LINUX )
    struct ifreq ifr = { { { 0 } } };

    rc = do_siocg_ioctl( if_name, SIOCGIFINDEX, &ifr );

    if ( mbg_rc_is_success( rc ) )
    {
      *p_intf_idx = ifr.ifr_ifindex;
      return rc;
    }
  #endif

  // we get here on error only
  *p_intf_idx = -1;

  return rc;

}  // get_port_intf_idx



/*HDR*/
/**
 * @brief Retrieve the MAC address of a network interface
 *
 * @param[in]  if_name     Name of the interface
 * @param[out] p_mac_addr  Pointer to the MAC address buffer to be filled up
 *
 * @return One of the @ref MBG_RETURN_CODES
 *         On error, the MAC address is set to all 0
 */
int get_port_mac_addr( const char *if_name, MBG_MAC_ADDR *p_mac_addr )
{
  int rc = MBG_ERR_NOT_SUPP_ON_OS;

  #if defined( MBG_TGT_LINUX )
    struct ifreq ifr = { { { 0 } } };

    rc = do_siocg_ioctl( if_name, SIOCGIFHWADDR, &ifr );

    if ( mbg_rc_is_success( rc ) )
    {
      memcpy( p_mac_addr, ifr.ifr_hwaddr.sa_data, sizeof( *p_mac_addr ) );
      return rc;
    }
  #endif

  // we get here on error only
  memset( p_mac_addr, 0, sizeof( *p_mac_addr ) );

  return rc;

}  // get_port_mac_addr



/*HDR*/
/**
 * @brief Check the link state of a network interface
 *
 * @param[in] if_name  Name of the interface
 *
 * @return 1 if link detected on port,
 *         0 if no link detected on port,
 *         one of the @ref MBG_ERROR_CODES in case of an error
 */
int check_port_link( const char *if_name )
{
  int rc = MBG_ERR_NOT_SUPP_ON_OS;

  #if defined( MBG_TGT_LINUX )
    struct ifreq ifr = { { { 0 } } };
    struct ethtool_value edata = { 0 };

    edata.cmd = ETHTOOL_GLINK; // defined in ethtool.h
    ifr.ifr_data = (caddr_t) &edata;

    rc = do_siocg_ioctl( if_name, SIOCETHTOOL, &ifr );

    if ( mbg_rc_is_success( rc ) )
      rc = ( edata.data == 0 ) ? 0 : 1;
  #endif

  return rc;

}  // check_port_link



static /*HDR*/
/**
 * @brief Retrieve some IPv4 address-like info from a network interface
 *
 * @param[in]  if_name      Name of the interface
 * @param[out] p_addr       Pointer to address field to be filled up
 * @param[in]  sigioc_code  The IOCTL code associated with the address
 *
 * @return  One of the @ref MBG_RETURN_CODES
 *          On error, *p_addr is set to all 0.
 *
 * @see ::get_port_ip4_settings
 * @see ::get_port_ip4_addr
 * @see ::get_port_ip4_addr_str
 * @see ::get_port_ip4_netmask
 * @see ::get_port_ip4_netmask_str
 * @see ::get_port_ip4_broad_addr
 * @see ::get_port_ip4_broad_addr_str
 */
int get_specific_port_ip4_addr( const char *if_name, IP4_ADDR *p_addr, int sigioc_code )
{
  int rc = MBG_ERR_NOT_SUPP_ON_OS;

  #if defined( MBG_TGT_LINUX )
    struct ifreq ifr = { { { 0 } } };

    rc = do_siocg_ioctl( if_name, sigioc_code, &ifr );

    if ( mbg_rc_is_success( rc ) )
    {
      *p_addr = ntohl( ( (struct sockaddr_in *) &ifr.ifr_addr )->sin_addr.s_addr );
      return rc;
    }
  #endif

  // we get here on error only
  *p_addr = 0;  // make empty address

  return rc;

}  // get_specific_port_ip4_addr



/*HDR*/
/**
 * @brief Retrieve the IPv4 address of a network interface
 *
 * @param[in]  if_name  Name of the interface
 * @param[out] p_addr   Pointer to address field to be filled up
 *
 * @return  One of the @ref MBG_RETURN_CODES
 *          On error, *p_addr is set to all 0.
 *
 * @see ::get_port_ip4_settings
 * @see ::get_port_ip4_addr_str
 * @see ::get_port_ip4_netmask
 * @see ::get_port_ip4_netmask_str
 * @see ::get_port_ip4_broad_addr
 * @see ::get_port_ip4_broad_addr_str
 * @see ::get_specific_port_ip4_addr
 */
int get_port_ip4_addr( const char *if_name, IP4_ADDR *p_addr )
{
  return get_specific_port_ip4_addr( if_name, p_addr, SIOCGIFADDR );

}  // get_port_ip4_addr



/*HDR*/
/**
 * @brief Retrieve the IPv4 net mask of a network interface
 *
 * @param[in]  if_name  Name of the interface
 * @param[out] p_addr   Pointer to address field to be filled up
 *
 * @return  One of the @ref MBG_RETURN_CODES
 *          On error, *p_addr is set to all 0.
 *
 * @see ::get_port_ip4_settings
 * @see ::get_port_ip4_addr
 * @see ::get_port_ip4_addr_str
 * @see ::get_port_ip4_netmask_str
 * @see ::get_port_ip4_broad_addr
 * @see ::get_port_ip4_broad_addr_str
 * @see ::get_specific_port_ip4_addr
 */
int get_port_ip4_netmask( const char *if_name, IP4_ADDR *p_addr )
{
  return get_specific_port_ip4_addr( if_name, p_addr, SIOCGIFNETMASK );

}  // get_port_ip4_netmask



/*HDR*/
/**
 * @brief Retrieve the IPv4 broadcast address of a network interface
 *
 * @param[in]  if_name  Name of the interface
 * @param[out] p_addr   Pointer to address field to be filled up
 *
 * @return  One of the @ref MBG_RETURN_CODES
 *          On error, *p_addr is set to all 0.
 *
 * @see ::get_port_ip4_settings
 * @see ::get_port_ip4_addr
 * @see ::get_port_ip4_addr_str
 * @see ::get_port_ip4_netmask
 * @see ::get_port_ip4_netmask_str
 * @see ::get_port_ip4_broad_addr_str
 * @see ::get_specific_port_ip4_addr
 */
int get_port_ip4_broad_addr( const char *if_name, IP4_ADDR *p_addr )
{
  return get_specific_port_ip4_addr( if_name, p_addr, SIOCGIFBRDADDR );

}  // get_port_ip4_broad_addr



#if defined( MBG_TGT_LINUX )

static /*HDR*/
/**
 * @brief Read a requested message from the netlink socket
 *
 * @return Message length (>= 0) on success, or of the @ref MBG_ERROR_CODES
 */
int nl_read( int sock_fd, char *buf_ptr, size_t buf_size, int seq_num, int pid )
{
  struct nlmsghdr *nl_hdr;
  int read_len = 0;
  int msg_len = 0;

  do
  {
    // receive response from the kernel, can be several chunks
    if ( ( read_len = recv( sock_fd, buf_ptr, buf_size - msg_len, 0 ) ) == -1 )
    {
      int rc = mbg_get_last_socket_error( NULL );
      #if DEBUG_NETLINK
        mbglog( LOG_ERR, "%s: Failed to receive netlink packet: %s",
                __func__, mbg_strerror( rc ) );
      #endif
      return rc;
    }

    nl_hdr = (struct nlmsghdr *) buf_ptr;

    // check if the header is valid
    if ( ( NLMSG_OK( nl_hdr, read_len ) == 0 ) || ( nl_hdr->nlmsg_type == NLMSG_ERROR ) )
    {
      #if DEBUG_NETLINK
        mbglog( LOG_ERR, "%s: Invalid header in received netlink packet",
                __func__ );
      #endif
      return MBG_ERR_DATA_FMT;
    }

    // check if the its the last message
    if ( nl_hdr->nlmsg_type == NLMSG_DONE )
    {
      #if DEBUG_NETLINK
        mbglog( LOG_ERR, "%s: Reached last message in received packet",
                __func__ );
      #endif
      break;
    }

    // move the pointer to buffer appropriately
    buf_ptr += read_len;
    msg_len += read_len;

    // check if its a multi part message
    if ( ( nl_hdr->nlmsg_flags & NLM_F_MULTI ) == 0 )
    {
      // return if it's not a multi part message
      #if DEBUG_NETLINK
        mbglog( LOG_ERR, "%s: Received packet is not a multi part message",
                __func__ );
      #endif
      break;
    }

  } while ( ( nl_hdr->nlmsg_seq != seq_num ) || ( nl_hdr->nlmsg_pid != pid ) );

  #if DEBUG_NETLINK
    mbglog( LOG_ERR, "%s: Received packet has len %i",
            __func__, msg_len );
  #endif

  return msg_len;

}  // nl_read



#if DEBUG_NETLINK

static /*HDR*/
void nl_log_bytes( const char *fnc,  const char *info, const void *p, int n_bytes )
{
  char ws[80];
  size_t n = 0;
  int i;

  for ( i = 0; i < n_bytes; i++ )
    n += snprintf_safe( &ws[n], sizeof( ws ) - n, " %i", BYTE_OF( * (uint8_t *) p, i ) );

  mbglog( LOG_INFO, "%s: attibute %s, copying %i bytes:%s",
          fnc, info, n_bytes, ws );

}  // nl_log_bytes

#endif



static /*HDR*/
int nl_parse_routes( struct nlmsghdr *nl_hdr, struct route_info *rt_info )
{
  // parse the route info returned
  struct rtmsg *rt_msg;
  struct rtattr *rt_attr;
  int rt_len;

  rt_msg = (struct rtmsg *) NLMSG_DATA( nl_hdr );

  // If the route is not for AF_INET then return.
  // This could be also IPv6 routes.
  if ( rt_msg->rtm_family != AF_INET )   //##++ TODO: PF_INET6 for IPv6
  {
    #if DEBUG_NETLINK
      mbglog( LOG_ERR, "%s: Route is not AF_INET (%li), but %li",
              __func__, (long) AF_INET, (long) rt_msg->rtm_family );
    #endif
    return -1;
  }

  // If the route does not belong to main routing table then return.
  if ( rt_msg->rtm_table != RT_TABLE_MAIN )
  {
    #if DEBUG_NETLINK
      mbglog( LOG_ERR, "%s: Route does not belong to main table (%li), but %li",
              __func__, (long) RT_TABLE_MAIN, (long) rt_msg->rtm_table );
    #endif
    return -1;
  }


  // get the rtattr field
  rt_attr = (struct rtattr *) RTM_RTA( rt_msg );
  rt_len = RTM_PAYLOAD( nl_hdr );

  for ( ; RTA_OK( rt_attr, rt_len ); rt_attr = RTA_NEXT( rt_attr, rt_len ) )
  {
    #if DEBUG_NETLINK
      mbglog( LOG_ERR, "rt_attr at %p, %i bytes left", rt_attr, rt_len );
    #endif

    switch ( rt_attr->rta_type )
    {
      case RTA_OIF:
        if_indextoname( *(int *)RTA_DATA( rt_attr ), rt_info->ifName );
        #if DEBUG_NETLINK
          mbglog( LOG_ERR, "%s: attibute RTA_OIF, IF name: %s",
                  __func__, rt_info->ifName );
        #endif
        break;

      case RTA_GATEWAY:
        memcpy( &rt_info->gateWay, RTA_DATA( rt_attr ), sizeof( rt_info->gateWay ) );
        #if DEBUG_NETLINK
          nl_log_bytes( __func__, "RTA_GATEWAY", &rt_info->gateWay,  sizeof( rt_info->gateWay ) );
        #endif
        break;

      case RTA_PREFSRC:
        memcpy( &rt_info->srcAddr , RTA_DATA( rt_attr ), sizeof( rt_info->srcAddr ) );
        #if DEBUG_NETLINK
          nl_log_bytes( __func__, "RTA_PREFSRC", &rt_info->srcAddr,  sizeof( rt_info->srcAddr ) );
        #endif
        break;

      case RTA_DST:
        memcpy( &rt_info->dstAddr, RTA_DATA( rt_attr ), sizeof( rt_info->dstAddr ) );
        #if DEBUG_NETLINK
          nl_log_bytes( __func__, "RTA_DST", &rt_info->dstAddr,  sizeof( rt_info->dstAddr ) );
        #endif
        break;

      #if DEBUG_NETLINK
      case RTA_TABLE:
        {
          // The RTA_TABLE attribute was added to the kernel source in 2006 to support
          // more than 255 routing tables. Originally the number of the routing table
          // to which an entry belongs had been passed only in struct rtmsg::rtm_table,
          // which is only 8 bits wide and should still hold the 8 LSBs of the full
          // routing table number for compatibility, so this should still work for the
          // standard routing tables, including the main table we are inspecting here.
          //
          // Whether this can be compiled in depends on the version of linux/rtnetlink.h
          // used by the compiler. Unfortunately RTA_TABLE is part of an enum, so you
          // can't simply use #ifdef RTA_TABLE to include this code conditionally.
          uint32_t rta_table;
          memcpy( &rta_table, RTA_DATA( rt_attr ), sizeof( rta_table ) );
          mbglog( LOG_ERR, "%s: attibute RTA_TABLE %i (%i)",
                  __func__, rta_table, rt_msg->rtm_table );
        }
        break;

      default:
        mbglog( LOG_ERR, "%s: Found unknown route type %li",
                __func__, (long) rt_attr->rta_type );
      #endif
    }
  }

  return 0;

}  // nl_parse_routes

#endif  // defined( MBG_TGT_LINUX )



/*HDR*/
/**
 * @brief Retrieve the IPv4 gateway (default route)
 *
 * @param[out] p_addr  Pointer to address field to be filled up
 *
 * @return  One of the @ref MBG_RETURN_CODES
 *          On error, *p_addr is set to all 0.
 */
int get_ip4_gateway( IP4_ADDR *p_addr )
{
  int rc = MBG_ERR_NOT_SUPP_ON_OS;

#if defined( MBG_TGT_LINUX )
  struct nlmsghdr *nlmsg;
  struct route_info route_info;
  char msg_buf[8192];   // pretty large buffer, why 8192 ?
  int sock_fd;
  int len;
  int msg_seq = 0;
  int idx;

  // create socket
  if ( ( sock_fd = socket( PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE ) ) == -1 )
  {
    rc = mbg_get_last_socket_error( NULL );
    #if DEBUG_NETLINK
      mbglog( LOG_ERR, "%s: Failed to create netlink socket: %s",
              __func__, mbg_strerror( rc ) );
    #endif
    goto out;
  }


  // initialize buffer with request message
  memset( msg_buf, 0, sizeof( msg_buf ) );

  // point the header and the msg structure pointers into the buffer
  nlmsg = (struct nlmsghdr *) msg_buf;

  // fill in the nlmsg header
  nlmsg->nlmsg_len = NLMSG_LENGTH( sizeof( struct rtmsg ) );  // length of message
  nlmsg->nlmsg_type = RTM_GETROUTE;                 // get the routes from kernel routing table

  nlmsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;  // the message is a request for dump
  nlmsg->nlmsg_seq = msg_seq++;                     // sequence of the message packet
  nlmsg->nlmsg_pid = getpid();                      // PID of process sending the request

  // send the request
  if ( send( sock_fd, nlmsg, nlmsg->nlmsg_len, 0 ) == -1 )
  {
    rc = mbg_get_last_socket_error( NULL );
    #if DEBUG_NETLINK
      mbglog( LOG_ERR, "%s: Failed to write to netlink socket: %s",
              __func__, mbg_strerror( rc ) );
    #endif
    goto out;
  }

  // read the response
  if ( ( len = nl_read( sock_fd, msg_buf, sizeof( msg_buf ), msg_seq, getpid() ) ) < 0 )
  {
    #if DEBUG_NETLINK
      mbglog( LOG_ERR, "%s: Failed to read from netlink socket",
              __func__ );
    #endif
    rc = len;
    goto out;
  }

  #if DEBUG_NETLINK
    mbglog( LOG_ERR, "%s: Read %i bytes from netlink socket", __func__, len );
  #endif

  // parse and print the response
  for ( idx = 0; NLMSG_OK( nlmsg, len ); nlmsg = NLMSG_NEXT( nlmsg, len ), idx++ )
  {
    memset( &route_info, 0, sizeof( route_info ) );

    #if DEBUG_NETLINK
      mbglog( LOG_ERR, "\nnl_msg at %p, %i bytes left", nlmsg, len );
    #endif


    if ( nl_parse_routes( nlmsg, &route_info ) < 0 )
      continue;  // don't check route_info if it has not been set up

    #if DEBUG_NETLINK
    {
      char ws[100];
      int l = sizeof( ws );
      int n = 0;

      // inet_ntoa() uses a static buffer which is overwritten on every call
      //##++ TODO: rather than inet_ntoa use inet_ntop which can also handle IPv6
      n += snprintf_safe( &ws[n], l - n, "src %s", (char *) inet_ntoa( route_info.srcAddr ) );
      n += snprintf_safe( &ws[n], l - n, ", dst %s", (char *) inet_ntoa( route_info.dstAddr ) );
      n += snprintf_safe( &ws[n], l - n, ", gw %s", (char *) inet_ntoa( route_info.gateWay ) );

      mbglog( LOG_ERR, "%s: route %i: %s, if \"%s\"",
              __func__, idx, ws, route_info.ifName );
    }
    #endif

    // check if default IPv4 gateway
    //##++ TODO: rather than inet_ntoa use inet_ntop which can also handle IPv6
    if ( strstr( (char *) inet_ntoa( route_info.dstAddr ), "0.0.0.0" ) )
    {
      *p_addr = ntohl( route_info.gateWay.s_addr );
      rc = MBG_SUCCESS;
      // Actually we could stop searching now. However, in case of debug
      // we'll continue to examine the rest of the routing message.
      #if DEBUG_NETLINK
      //##++ TODO: rather than inet_ntoa use inet_ntop which can also handle IPv6
        mbglog( LOG_ERR, "%s: Default gateway found: %s",
                __func__, (char *) inet_ntoa( route_info.gateWay ) );
      #else
        break;
      #endif
    }
  }

out:
  if ( sock_fd >= 0 )
    close( sock_fd );

#endif  // defined( MBG_TGT_LINUX )

  if ( mbg_rc_is_error( rc ) )
    *p_addr = 0;

  return rc;

}  // get_ip4_gateway



/*HDR*/
/**
 * @brief Retrieve the IPv4 address of a network interface as string
 *
 * @param[in] if_name     Name of the interface
 * @param[out] p_addr_buf  Pointer to the string buffer to be filled up
 * @param[in] buf_size    size of the string buffer
 *
 * @return  One of the @ref MBG_RETURN_CODES
 *          On error, a string according to "0.0.0.0" is generated.
 *
 * @see ::get_port_ip4_settings
 * @see ::get_port_ip4_addr
 * @see ::get_port_ip4_netmask
 * @see ::get_port_ip4_netmask_str
 * @see ::get_port_ip4_broad_addr
 * @see ::get_port_ip4_broad_addr_str
 * @see ::get_specific_port_ip4_addr
 */
int get_port_ip4_addr_str( const char *if_name, char *p_addr_buf, int buf_size )
{
  IP4_ADDR addr;

  int rc = get_port_ip4_addr( if_name, &addr );

  snprint_ip4_addr( p_addr_buf, buf_size, &addr, NULL );

  return rc;

}  // get_port_ip4_addr_str



/*HDR*/
/**
 * @brief Retrieve the IPv4 net mask of a network interface as string
 *
 * @param[in] if_name     Name of the interface
 * @param[out] p_addr_buf  Pointer to the string buffer to be filled up
 * @param[in] buf_size    size of the string buffer
 *
 * @return  One of the @ref MBG_RETURN_CODES
 *          On error, a string according to "0.0.0.0" is generated.
 *
 * @see ::get_port_ip4_settings
 * @see ::get_port_ip4_addr
 * @see ::get_port_ip4_addr_str
 * @see ::get_port_ip4_netmask
 * @see ::get_port_ip4_broad_addr
 * @see ::get_port_ip4_broad_addr_str
 * @see ::get_specific_port_ip4_addr
 */
int get_port_ip4_netmask_str( const char *if_name, char *p_addr_buf, int buf_size )
{
  IP4_ADDR addr;

  int rc = get_port_ip4_netmask( if_name, &addr );

  snprint_ip4_addr( p_addr_buf, buf_size, &addr, NULL );

  return rc;

}  // get_port_ip4_netmask_str



/*HDR*/
/**
 * @brief Retrieve the IPv4 broadcast address of a network interface as string
 *
 * @param[in] if_name     Name of the interface
 * @param[out] p_addr_buf  Pointer to the string buffer to be filled up
 * @param[in] buf_size    size of the string buffer
 *
 * @return  One of the @ref MBG_RETURN_CODES
 *          On error, a string according to "0.0.0.0" is generated.
 *
 * @see ::get_port_ip4_settings
 * @see ::get_port_ip4_addr
 * @see ::get_port_ip4_addr_str
 * @see ::get_port_ip4_netmask
 * @see ::get_port_ip4_netmask_str
 * @see ::get_port_ip4_broad_addr
 * @see ::get_specific_port_ip4_addr
 */
int get_port_ip4_broad_addr_str( const char *if_name, char *p_addr_buf, int buf_size )
{
  IP4_ADDR addr;

  int rc = get_port_ip4_broad_addr( if_name, &addr );

  snprint_ip4_addr( p_addr_buf, buf_size, &addr, NULL );

  return rc;

}  // get_port_ip4_broad_addr_str



/*HDR*/
/**
 * @brief Retrieve the current IPv4 settings of a network interface
 *
 * @param[in] if_name  Name of the interface
 * @param[out] p        Pointer to a IP4_SETTINGS structure to be filled up
 *
 * @return  One of the @ref MBG_RETURN_CODES
 *
 * @see ::get_port_ip4_addr
 * @see ::get_port_ip4_addr_str
 * @see ::get_port_ip4_netmask
 * @see ::get_port_ip4_netmask_str
 * @see ::get_port_ip4_broad_addr
 * @see ::get_port_ip4_broad_addr_str
 * @see ::get_specific_port_ip4_addr
 */
int get_port_ip4_settings( const char *if_name, IP4_SETTINGS *p )
{
  int link_up;
  int rc;

  memset( p, 0, sizeof( *p ) );

  rc = get_port_ip4_addr( if_name, &p->ip_addr );

  if ( mbg_rc_is_error( rc ) )
    goto out;


  rc = get_port_ip4_netmask( if_name, &p->netmask );

  if ( mbg_rc_is_error( rc ) )
    goto out;


  rc = get_port_ip4_broad_addr( if_name, &p->broad_addr );

  if ( mbg_rc_is_error( rc ) )
    goto out;


#ifndef USE_MBG_TSU
  rc = get_ip4_gateway( &p->gateway );

  if ( mbg_rc_is_error( rc ) )
    goto out;
#endif

  link_up = check_port_link( if_name );

  if ( mbg_rc_is_success( rc ) )
    if ( link_up )
      p->flags |= IP4_MSK_LINK;

#if 0  //### TODO
  // We could also try to check VLAN and DHCP settings here,
  // but as of now, this is specific to an application.

  // ##++++ The VLAN and DHCP status info collected below
  // just return what has been configured previously by this program,
  // however, it does not reflect any changes which have been made
  // manually, e.g. via the command line.
  if ( vlan_enabled )
  {
    p->flags |= IP4_MSK_VLAN;
    p->vlan_cfg = vlan_cfg;
  }

  if ( dhcp_enabled )
    p->flags |= IP4_MSK_DHCP;
#endif

out:
  return rc;

}  // get_port_ip4_settings