crdhcpc 0.1.1

Standalone DHCP Client for Linux with DHCPv4, DHCPv6, PXE, and Dynamic DNS support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
//! Raw socket implementation for DHCP client
//!
//! This module provides low-level raw socket functionality for sending DHCP packets
//! with source IP 0.0.0.0 (required for DHCP DISCOVER when client has no IP address).
//!
//! Two approaches are provided:
//! 1. IP Layer (SOCK_RAW) - simpler but less control
//! 2. Link Layer (AF_PACKET) - recommended for DHCP, full control

use std::net::Ipv4Addr;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::time::Duration;
use std::mem::MaybeUninit;
use anyhow::{Context, Result, anyhow};

// Import tracing macros when debug feature is enabled
#[cfg(feature = "dhcp-debug")]
use tracing::{debug, info};

// Conditional debug logging macro with line numbers
#[cfg(feature = "dhcp-debug")]
macro_rules! dhcp_debug {
    ($($arg:tt)*) => {
        debug!("[{}:{}] {}", file!(), line!(), format!($($arg)*))
    };
}

#[cfg(not(feature = "dhcp-debug"))]
macro_rules! dhcp_debug {
    ($($arg:tt)*) => {};
}

#[cfg(feature = "dhcp-debug")]
macro_rules! dhcp_info {
    ($($arg:tt)*) => {
        info!("[{}:{}] {}", file!(), line!(), format!($($arg)*))
    };
}

#[cfg(not(feature = "dhcp-debug"))]
macro_rules! dhcp_info {
    ($($arg:tt)*) => {};
}

/// Raw socket types for DHCP
pub enum RawSocketType {
    /// IP layer raw socket (Layer 3)
    IpLayer,
    /// Link layer packet socket (Layer 2) - recommended for DHCP
    LinkLayer,
}

/// Raw socket wrapper for DHCP operations
pub struct DhcpRawSocket {
    socket: socket2::Socket,
    socket_type: RawSocketType,
    interface: Option<String>,
}

impl DhcpRawSocket {
    /// Create a new raw socket for DHCP
    ///
    /// # Arguments
    /// * `socket_type` - Type of raw socket to create
    /// * `interface` - Network interface name (required for LinkLayer, ignored for IpLayer)
    ///
    /// # Returns
    /// A new DhcpRawSocket instance
    ///
    /// # Errors
    /// Returns error if socket creation fails or if running without CAP_NET_RAW/root
    pub fn new(socket_type: RawSocketType, interface: Option<&str>) -> Result<Self> {
        dhcp_debug!("DEBUG: DhcpRawSocket::new() called");
        dhcp_debug!("  socket_type: {:?}", match &socket_type {
            RawSocketType::IpLayer => "IpLayer",
            RawSocketType::LinkLayer => "LinkLayer",
        });
        dhcp_debug!("  interface: {:?}", interface);

        let socket = match &socket_type {
            RawSocketType::IpLayer => {
                dhcp_debug!("DEBUG: Creating IP layer socket");
                Self::create_ip_layer_socket()?
            },
            RawSocketType::LinkLayer => {
                let iface = interface.ok_or_else(|| {
                    anyhow!("Interface name required for LinkLayer socket")
                })?;
                dhcp_debug!("DEBUG: Creating link layer socket for interface: {}", iface);
                Self::create_link_layer_socket(iface)?
            }
        };

        dhcp_debug!("DEBUG: DhcpRawSocket created successfully");
        Ok(Self {
            socket,
            socket_type,
            interface: interface.map(String::from),
        })
    }

    /// Create IP layer raw socket (SOCK_RAW with IPPROTO_RAW)
    ///
    /// This creates a Layer 3 socket where we provide the IP header.
    /// Kernel handles routing based on destination IP.
    fn create_ip_layer_socket() -> Result<socket2::Socket> {
        dhcp_debug!("DEBUG: create_ip_layer_socket() - Creating raw socket");
        dhcp_debug!("  AF_INET={}, SOCK_RAW={}, IPPROTO_RAW={}",
               libc::AF_INET, libc::SOCK_RAW, libc::IPPROTO_RAW);

        // Create raw socket with IPPROTO_RAW
        let socket_fd = unsafe {
            libc::socket(libc::AF_INET, libc::SOCK_RAW, libc::IPPROTO_RAW)
        };

        dhcp_debug!("DEBUG: socket() returned fd={}", socket_fd);

        if socket_fd < 0 {
            let errno = unsafe { *libc::__errno_location() };
            dhcp_debug!("DEBUG: socket() FAILED with errno={}", errno);
            return Err(anyhow!(
                "Failed to create raw socket (errno={}). Requires CAP_NET_RAW or root privileges",
                errno
            ));
        }

        let socket = unsafe { socket2::Socket::from_raw_fd(socket_fd) };
        dhcp_debug!("DEBUG: Socket created successfully, fd={}", socket_fd);

        // Set IP_HDRINCL - we will provide the IP header
        dhcp_debug!("DEBUG: Setting IP_HDRINCL=1");
        unsafe {
            let optval: libc::c_int = 1;
            let ret = libc::setsockopt(
                socket.as_raw_fd(),
                libc::IPPROTO_IP,
                libc::IP_HDRINCL,
                &optval as *const _ as *const libc::c_void,
                std::mem::size_of_val(&optval) as libc::socklen_t,
            );
            dhcp_debug!("DEBUG: setsockopt(IP_HDRINCL) returned {}", ret);
            if ret < 0 {
                let _errno = *libc::__errno_location();
                dhcp_debug!("DEBUG: setsockopt(IP_HDRINCL) FAILED with errno={}", _errno);
                return Err(anyhow!("Failed to set IP_HDRINCL"));
            }
        }

        // Set SO_BROADCAST to allow broadcast packets (required for DHCP)
        dhcp_debug!("DEBUG: Setting SO_BROADCAST=1");
        unsafe {
            let optval: libc::c_int = 1;
            let ret = libc::setsockopt(
                socket.as_raw_fd(),
                libc::SOL_SOCKET,
                libc::SO_BROADCAST,
                &optval as *const _ as *const libc::c_void,
                std::mem::size_of_val(&optval) as libc::socklen_t,
            );
            dhcp_debug!("DEBUG: setsockopt(SO_BROADCAST) returned {}", ret);
            if ret < 0 {
                let _errno = *libc::__errno_location();
                dhcp_debug!("DEBUG: setsockopt(SO_BROADCAST) FAILED with errno={}", _errno);
                return Err(anyhow!("Failed to set SO_BROADCAST"));
            }
        }

        dhcp_debug!("DEBUG: IP layer socket created and configured successfully");
        Ok(socket)
    }

    /// Create link layer packet socket (AF_PACKET)
    ///
    /// This creates a Layer 2 socket where we provide the complete Ethernet frame.
    /// This is the recommended approach for DHCP.
    fn create_link_layer_socket(interface: &str) -> Result<socket2::Socket> {
        dhcp_debug!("DEBUG: create_link_layer_socket() - Creating AF_PACKET socket");
        dhcp_debug!("  interface: {}", interface);

        // Get interface index
        let if_index = Self::get_interface_index(interface)?;
        dhcp_debug!("DEBUG: Interface index for {}: {}", interface, if_index);

        // Create AF_PACKET socket
        // ETH_P_IP = 0x0800 in network byte order (big endian)
        let protocol = (libc::ETH_P_IP as u16).to_be() as i32;
        dhcp_debug!("DEBUG: Protocol (ETH_P_IP in network order): 0x{:04x}", protocol);
        dhcp_debug!("  AF_PACKET={}, SOCK_RAW={}", libc::AF_PACKET, libc::SOCK_RAW);

        let socket_fd = unsafe {
            libc::socket(libc::AF_PACKET, libc::SOCK_RAW, protocol)
        };

        dhcp_debug!("DEBUG: socket() returned fd={}", socket_fd);

        if socket_fd < 0 {
            let errno = unsafe { *libc::__errno_location() };
            dhcp_debug!("DEBUG: socket() FAILED with errno={}", errno);
            return Err(anyhow!(
                "Failed to create AF_PACKET socket (errno={}). Requires CAP_NET_RAW or root privileges",
                errno
            ));
        }

        let socket = unsafe { socket2::Socket::from_raw_fd(socket_fd) };
        dhcp_debug!("DEBUG: AF_PACKET socket created successfully, fd={}", socket_fd);

        // Bind to specific interface
        let mut sll: libc::sockaddr_ll = unsafe { std::mem::zeroed() };
        sll.sll_family = libc::AF_PACKET as u16;
        sll.sll_protocol = protocol as u16;
        sll.sll_ifindex = if_index;

        dhcp_debug!("DEBUG: Binding socket to interface");
        dhcp_debug!("  sll_family: {}", sll.sll_family);
        dhcp_debug!("  sll_protocol: 0x{:04x}", sll.sll_protocol);
        dhcp_debug!("  sll_ifindex: {}", sll.sll_ifindex);

        let ret = unsafe {
            libc::bind(
                socket.as_raw_fd(),
                &sll as *const _ as *const libc::sockaddr,
                std::mem::size_of::<libc::sockaddr_ll>() as libc::socklen_t,
            )
        };

        dhcp_debug!("DEBUG: bind() returned {}", ret);

        if ret < 0 {
            let errno = unsafe { *libc::__errno_location() };
            dhcp_debug!("DEBUG: bind() FAILED with errno={}", errno);
            return Err(anyhow!(
                "Failed to bind to interface {} (errno={})",
                interface,
                errno
            ));
        }

        dhcp_debug!("DEBUG: Link layer socket created and bound successfully");
        Ok(socket)
    }

    /// Get network interface index by name
    fn get_interface_index(interface: &str) -> Result<i32> {
        use std::ffi::CString;

        dhcp_debug!("DEBUG: get_interface_index() called for: {}", interface);

        let iface_cstr = CString::new(interface)
            .context("Invalid interface name")?;

        let index = unsafe { libc::if_nametoindex(iface_cstr.as_ptr()) };

        dhcp_debug!("DEBUG: if_nametoindex() returned: {}", index);

        if index == 0 {
            dhcp_debug!("DEBUG: Interface {} not found (index=0)", interface);
            return Err(anyhow!("Interface {} not found", interface));
        }

        dhcp_debug!("DEBUG: Interface {} has index {}", interface, index);
        Ok(index as i32)
    }

    /// Send a raw packet
    ///
    /// For IpLayer: packet should contain IP header + UDP header + DHCP message
    /// For LinkLayer: packet should contain Ethernet header + IP header + UDP header + DHCP message
    pub fn send(&self, packet: &[u8]) -> Result<usize> {
        dhcp_debug!("DEBUG: DhcpRawSocket::send() called");
        dhcp_debug!("  packet length: {} bytes", packet.len());
        dhcp_debug!("  socket_type: {:?}", match self.socket_type {
            RawSocketType::IpLayer => "IpLayer",
            RawSocketType::LinkLayer => "LinkLayer",
        });
        dhcp_debug!("  interface: {:?}", self.interface);

        match self.socket_type {
            RawSocketType::IpLayer => {
                dhcp_debug!("DEBUG: Sending via IP layer socket");
                // For IP layer, we need to sendto with destination address
                // Extract destination IP from the packet (offset 16-19 in IP header)
                if packet.len() < 20 {
                    dhcp_debug!("DEBUG: ERROR - Packet too short ({} bytes)", packet.len());
                    return Err(anyhow!("Packet too short for IP header"));
                }

                let dst_ip = Ipv4Addr::new(packet[16], packet[17], packet[18], packet[19]);
                dhcp_debug!("DEBUG: Extracted destination IP from packet: {}", dst_ip);

                let dest_addr = std::net::SocketAddr::new(
                    std::net::IpAddr::V4(dst_ip),
                    0
                );
                let dest_sockaddr = socket2::SockAddr::from(dest_addr);

                dhcp_debug!("DEBUG: Calling sendto() with {} bytes to {}", packet.len(), dst_ip);

                // DEBUG: Print packet just before sending
                eprintln!(">>> SENDING DHCP PACKET (IP LAYER) <<<");
                eprintln!("  Destination: {}", dst_ip);
                eprintln!("  Length: {} bytes", packet.len());
                eprintln!("  Packet hex (first 256 bytes): {}", hex::encode(&packet[..packet.len().min(256)]));
                if packet.len() > 256 {
                    eprintln!("  (truncated, showing first 256 of {} total bytes)", packet.len());
                }
                eprintln!();

                let result = self.socket
                    .send_to(packet, &dest_sockaddr)
                    .context("Failed to send packet");

                match &result {
                    Ok(_bytes_sent) => {
                        dhcp_debug!("DEBUG: sendto() SUCCESS - sent {} bytes", _bytes_sent);
                        dhcp_info!("PACKET SENT: {} bytes via IP layer to {}", _bytes_sent, dst_ip);
                    }
                    Err(_e) => {
                        dhcp_debug!("DEBUG: sendto() FAILED: {}", _e);
                    }
                }

                result
            }
            RawSocketType::LinkLayer => {
                dhcp_debug!("DEBUG: Sending via link layer socket");
                dhcp_debug!("DEBUG: First 14 bytes (Ethernet header): {:02x?}", &packet[..14.min(packet.len())]);

                dhcp_debug!("DEBUG: Calling send() with {} bytes", packet.len());

                // DEBUG: Print packet just before sending
                eprintln!(">>> SENDING DHCP PACKET (LINK LAYER) <<<");
                eprintln!("  Interface: {:?}", self.interface);
                eprintln!("  Length: {} bytes", packet.len());
                eprintln!();

                // Print hex in 8-byte chunks for readability
                eprintln!("  Packet hex (8-byte chunks):");
                for (i, chunk) in packet.chunks(8).enumerate() {
                    eprint!("    {:04x}: ", i * 8);
                    for byte in chunk {
                        eprint!("{:02x} ", byte);
                    }
                    eprintln!();

                    // Only show first 256 bytes
                    if (i + 1) * 8 >= 256 {
                        if packet.len() > 256 {
                            eprintln!("    ... (truncated, showing first 256 of {} total bytes)", packet.len());
                        }
                        break;
                    }
                }
                eprintln!();

                // Decode packet structure if it's long enough
                if packet.len() >= 14 + 20 + 8 + 240 {
                    eprintln!("  Packet structure:");
                    eprintln!("    Ethernet Header (14 bytes):");
                    eprintln!("      Dst MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
                        packet[0], packet[1], packet[2], packet[3], packet[4], packet[5]);
                    eprintln!("      Src MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
                        packet[6], packet[7], packet[8], packet[9], packet[10], packet[11]);
                    eprintln!("      EtherType: 0x{:02x}{:02x}", packet[12], packet[13]);

                    let ip_start = 14;
                    eprintln!("    IP Header (20 bytes at offset {}):", ip_start);
                    eprintln!("      Src IP: {}.{}.{}.{}", packet[ip_start+12], packet[ip_start+13], packet[ip_start+14], packet[ip_start+15]);
                    eprintln!("      Dst IP: {}.{}.{}.{}", packet[ip_start+16], packet[ip_start+17], packet[ip_start+18], packet[ip_start+19]);

                    let udp_start = ip_start + 20;
                    eprintln!("    UDP Header (8 bytes at offset {}):", udp_start);
                    let src_port = u16::from_be_bytes([packet[udp_start], packet[udp_start+1]]);
                    let dst_port = u16::from_be_bytes([packet[udp_start+2], packet[udp_start+3]]);
                    eprintln!("      Src Port: {}", src_port);
                    eprintln!("      Dst Port: {}", dst_port);

                    let dhcp_start = udp_start + 8;
                    eprintln!("    DHCP Message (at offset {}):", dhcp_start);
                    eprintln!("      op: {} (1=BOOTREQUEST, 2=BOOTREPLY)", packet[dhcp_start]);
                    eprintln!("      htype: {}", packet[dhcp_start+1]);
                    eprintln!("      hlen: {}", packet[dhcp_start+2]);
                    eprintln!("      hops: {}", packet[dhcp_start+3]);
                    let xid = u32::from_be_bytes([packet[dhcp_start+4], packet[dhcp_start+5], packet[dhcp_start+6], packet[dhcp_start+7]]);
                    eprintln!("      xid: 0x{:08x}", xid);
                }
                eprintln!();

                let result = self.socket
                    .send(packet)
                    .context("Failed to send frame");

                match &result {
                    Ok(_bytes_sent) => {
                        dhcp_debug!("DEBUG: send() SUCCESS - sent {} bytes", _bytes_sent);
                        dhcp_info!("PACKET SENT: {} bytes via link layer on {:?}", _bytes_sent, self.interface);
                    }
                    Err(_e) => {
                        dhcp_debug!("DEBUG: send() FAILED: {}", _e);
                    }
                }

                result
            }
        }
    }

    /// Receive a raw packet with timeout
    ///
    /// Returns the packet data and source address
    pub fn recv(&self, buf: &mut [u8], timeout: Duration) -> std::io::Result<usize> {
        dhcp_debug!("DEBUG: DhcpRawSocket::recv() called");
        dhcp_debug!("  buffer size: {} bytes", buf.len());
        dhcp_debug!("  timeout: {:?}", timeout);
        dhcp_debug!("  socket_type: {:?}", match self.socket_type {
            RawSocketType::IpLayer => "IpLayer",
            RawSocketType::LinkLayer => "LinkLayer",
        });

        // Set receive timeout
        self.socket.set_read_timeout(Some(timeout))?;

        dhcp_debug!("DEBUG: Calling recv() to read packet");

        // Create MaybeUninit buffer for recv_from
        let mut uninit_buf = vec![MaybeUninit::<u8>::uninit(); buf.len()];
        let (bytes_received, _addr) = self.socket.recv_from(&mut uninit_buf)?;

        // Copy initialized bytes to output buffer
        for (i, byte) in uninit_buf.iter().take(bytes_received).enumerate() {
            unsafe {
                buf[i] = byte.assume_init();
            }
        }

        dhcp_debug!("DEBUG: recv() SUCCESS - received {} bytes", bytes_received);
        dhcp_info!("PACKET RECEIVED: {} bytes", bytes_received);

        // DEBUG: Print packet right after receiving
        eprintln!("<<< RECEIVED DHCP PACKET >>>");
        eprintln!("  Length: {} bytes", bytes_received);
        eprintln!();

        // Print hex in 8-byte chunks for readability
        eprintln!("  Packet hex (8-byte chunks):");
        for (i, chunk) in buf[..bytes_received].chunks(8).enumerate() {
            eprint!("    {:04x}: ", i * 8);
            for byte in chunk {
                eprint!("{:02x} ", byte);
            }
            eprintln!();

            // Only show first 256 bytes
            if (i + 1) * 8 >= 256 {
                if bytes_received > 256 {
                    eprintln!("    ... (truncated, showing first 256 of {} total bytes)", bytes_received);
                }
                break;
            }
        }
        eprintln!();

        // Decode packet structure based on socket type
        match self.socket_type {
            RawSocketType::LinkLayer => {
                if bytes_received >= 14 + 20 + 8 + 240 {
                    eprintln!("  Packet structure (Link Layer):");
                    eprintln!("    Ethernet Header (14 bytes):");
                    eprintln!("      Dst MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
                        buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
                    eprintln!("      Src MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
                        buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]);
                    eprintln!("      EtherType: 0x{:02x}{:02x}", buf[12], buf[13]);

                    let ip_start = 14;
                    eprintln!("    IP Header (20 bytes at offset {}):", ip_start);
                    eprintln!("      Src IP: {}.{}.{}.{}", buf[ip_start+12], buf[ip_start+13], buf[ip_start+14], buf[ip_start+15]);
                    eprintln!("      Dst IP: {}.{}.{}.{}", buf[ip_start+16], buf[ip_start+17], buf[ip_start+18], buf[ip_start+19]);

                    let udp_start = ip_start + 20;
                    eprintln!("    UDP Header (8 bytes at offset {}):", udp_start);
                    let src_port = u16::from_be_bytes([buf[udp_start], buf[udp_start+1]]);
                    let dst_port = u16::from_be_bytes([buf[udp_start+2], buf[udp_start+3]]);
                    eprintln!("      Src Port: {}", src_port);
                    eprintln!("      Dst Port: {}", dst_port);

                    let dhcp_start = udp_start + 8;
                    eprintln!("    DHCP Message (at offset {}):", dhcp_start);
                    eprintln!("      op: {} (1=BOOTREQUEST, 2=BOOTREPLY)", buf[dhcp_start]);
                    eprintln!("      htype: {}", buf[dhcp_start+1]);
                    eprintln!("      hlen: {}", buf[dhcp_start+2]);
                    eprintln!("      hops: {}", buf[dhcp_start+3]);
                    let xid = u32::from_be_bytes([buf[dhcp_start+4], buf[dhcp_start+5], buf[dhcp_start+6], buf[dhcp_start+7]]);
                    eprintln!("      xid: 0x{:08x}", xid);
                    eprintln!("      yiaddr (offered IP): {}.{}.{}.{}",
                        buf[dhcp_start+16], buf[dhcp_start+17], buf[dhcp_start+18], buf[dhcp_start+19]);
                    eprintln!("      Magic cookie at offset {}: {:02x} {:02x} {:02x} {:02x}",
                        dhcp_start+236, buf[dhcp_start+236], buf[dhcp_start+237], buf[dhcp_start+238], buf[dhcp_start+239]);
                }
            }
            RawSocketType::IpLayer => {
                if bytes_received >= 20 + 8 + 240 {
                    eprintln!("  Packet structure (IP Layer):");
                    let ip_start = 0;
                    eprintln!("    IP Header (20 bytes at offset {}):", ip_start);
                    eprintln!("      Src IP: {}.{}.{}.{}", buf[ip_start+12], buf[ip_start+13], buf[ip_start+14], buf[ip_start+15]);
                    eprintln!("      Dst IP: {}.{}.{}.{}", buf[ip_start+16], buf[ip_start+17], buf[ip_start+18], buf[ip_start+19]);

                    let udp_start = ip_start + 20;
                    eprintln!("    UDP Header (8 bytes at offset {}):", udp_start);
                    let src_port = u16::from_be_bytes([buf[udp_start], buf[udp_start+1]]);
                    let dst_port = u16::from_be_bytes([buf[udp_start+2], buf[udp_start+3]]);
                    eprintln!("      Src Port: {}", src_port);
                    eprintln!("      Dst Port: {}", dst_port);

                    let dhcp_start = udp_start + 8;
                    eprintln!("    DHCP Message (at offset {}):", dhcp_start);
                    eprintln!("      op: {} (1=BOOTREQUEST, 2=BOOTREPLY)", buf[dhcp_start]);
                    eprintln!("      htype: {}", buf[dhcp_start+1]);
                    eprintln!("      hlen: {}", buf[dhcp_start+2]);
                    eprintln!("      hops: {}", buf[dhcp_start+3]);
                    let xid = u32::from_be_bytes([buf[dhcp_start+4], buf[dhcp_start+5], buf[dhcp_start+6], buf[dhcp_start+7]]);
                    eprintln!("      xid: 0x{:08x}", xid);
                    eprintln!("      yiaddr (offered IP): {}.{}.{}.{}",
                        buf[dhcp_start+16], buf[dhcp_start+17], buf[dhcp_start+18], buf[dhcp_start+19]);
                    eprintln!("      Magic cookie at offset {}: {:02x} {:02x} {:02x} {:02x}",
                        dhcp_start+236, buf[dhcp_start+236], buf[dhcp_start+237], buf[dhcp_start+238], buf[dhcp_start+239]);
                }
            }
        }
        eprintln!();

        Ok(bytes_received)
    }

    /// Get the underlying socket file descriptor
    pub fn as_raw_fd(&self) -> i32 {
        self.socket.as_raw_fd()
    }
}

/// Build DHCP DISCOVER packet for IP layer socket
///
/// Constructs: IP header + UDP header + DHCP message
/// Source IP: 0.0.0.0
/// Destination IP: 255.255.255.255
pub fn build_dhcp_discover_ip_packet(
    mac_address: [u8; 6],
    xid: u32,
    hostname: Option<&str>,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_discover_ip_packet() called");
    dhcp_debug!("  MAC address: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
           mac_address[0], mac_address[1], mac_address[2],
           mac_address[3], mac_address[4], mac_address[5]);
    dhcp_debug!("  Transaction ID (xid): 0x{:08x}", xid);
    dhcp_debug!("  Hostname: {:?}", hostname);

    let src_ip = Ipv4Addr::new(0, 0, 0, 0);  // 0.0.0.0 - no IP yet
    let dst_ip = Ipv4Addr::new(255, 255, 255, 255);  // Broadcast
    let src_port: u16 = 68;  // DHCP client port
    let dst_port: u16 = 67;  // DHCP server port

    dhcp_debug!("DEBUG: IP layer - src={} dst={}", src_ip, dst_ip);
    dhcp_debug!("DEBUG: UDP layer - src_port={} dst_port={}", src_port, dst_port);

    // Build DHCP message
    let dhcp_msg = build_dhcp_message(mac_address, xid, hostname);
    dhcp_debug!("DEBUG: DHCP message built, size={} bytes", dhcp_msg.len());

    // Build UDP header
    let udp_len = (8 + dhcp_msg.len()) as u16;
    dhcp_debug!("DEBUG: UDP total length: {} bytes", udp_len);
    let mut udp_header = Vec::new();
    udp_header.extend_from_slice(&src_port.to_be_bytes());
    udp_header.extend_from_slice(&dst_port.to_be_bytes());
    udp_header.extend_from_slice(&udp_len.to_be_bytes());
    udp_header.extend_from_slice(&0u16.to_be_bytes());  // checksum (0 for now)

    // Build IP header
    let total_len = (20 + 8 + dhcp_msg.len()) as u16;
    dhcp_debug!("DEBUG: IP total length: {} bytes (IP header=20, UDP header=8, DHCP={})",
           total_len, dhcp_msg.len());
    let mut packet = Vec::new();
    packet.push(0x45);  // Version 4, IHL 5 (20 bytes)
    packet.push(0x00);  // DSCP/ECN
    packet.extend_from_slice(&total_len.to_be_bytes());
    packet.extend_from_slice(&0u16.to_be_bytes());  // Identification
    packet.extend_from_slice(&0u16.to_be_bytes());  // Flags/Fragment offset
    packet.push(64);  // TTL
    packet.push(17);  // Protocol: UDP
    packet.extend_from_slice(&0u16.to_be_bytes());  // Checksum (calculate later)
    packet.extend_from_slice(&src_ip.octets());  // Source: 0.0.0.0
    packet.extend_from_slice(&dst_ip.octets());  // Dest: 255.255.255.255

    // Calculate and insert IP checksum
    let ip_checksum = calculate_checksum(&packet[0..20]);
    dhcp_debug!("DEBUG: Calculated IP checksum: 0x{:04x}", ip_checksum);
    packet[10] = (ip_checksum >> 8) as u8;
    packet[11] = (ip_checksum & 0xFF) as u8;

    // Append UDP header and DHCP message
    packet.extend_from_slice(&udp_header);
    packet.extend_from_slice(&dhcp_msg);

    dhcp_debug!("DEBUG: Complete packet built, total size={} bytes", packet.len());
    dhcp_debug!("DEBUG: Packet breakdown - IP:20 + UDP:8 + DHCP:{} = {}",
           dhcp_msg.len(), packet.len());

    packet
}

/// Build DHCP DISCOVER frame for link layer socket
///
/// Constructs: Ethernet header + IP header + UDP header + DHCP message
pub fn build_dhcp_discover_link_frame(
    src_mac: [u8; 6],
    xid: u32,
    hostname: Option<&str>,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_discover_link_frame() called");
    dhcp_debug!("  Source MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
           src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5]);
    dhcp_debug!("  Transaction ID (xid): 0x{:08x}", xid);
    dhcp_debug!("  Hostname: {:?}", hostname);

    let dst_mac = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff];  // Broadcast MAC
    let src_ip = Ipv4Addr::new(0, 0, 0, 0);
    let dst_ip = Ipv4Addr::new(255, 255, 255, 255);
    let src_port: u16 = 68;
    let dst_port: u16 = 67;

    dhcp_debug!("DEBUG: Ethernet - dst_mac=ff:ff:ff:ff:ff:ff (broadcast)");
    dhcp_debug!("DEBUG: IP layer - src={} dst={}", src_ip, dst_ip);
    dhcp_debug!("DEBUG: UDP layer - src_port={} dst_port={}", src_port, dst_port);

    let mut frame = Vec::new();

    // Ethernet Header (14 bytes)
    frame.extend_from_slice(&dst_mac);  // Destination MAC: broadcast
    frame.extend_from_slice(&src_mac);  // Source MAC
    frame.extend_from_slice(&[0x08, 0x00]);  // EtherType: IPv4
    dhcp_debug!("DEBUG: Ethernet header built (14 bytes)");

    // Build DHCP message
    let dhcp_msg = build_dhcp_message(src_mac, xid, hostname);
    dhcp_debug!("DEBUG: DHCP message built, size={} bytes", dhcp_msg.len());

    // UDP Header
    let udp_len = (8 + dhcp_msg.len()) as u16;
    dhcp_debug!("DEBUG: UDP total length: {} bytes", udp_len);
    let mut udp_header = Vec::new();
    udp_header.extend_from_slice(&src_port.to_be_bytes());
    udp_header.extend_from_slice(&dst_port.to_be_bytes());
    udp_header.extend_from_slice(&udp_len.to_be_bytes());
    udp_header.extend_from_slice(&0u16.to_be_bytes());  // checksum

    // IP Header
    let total_len = (20 + 8 + dhcp_msg.len()) as u16;
    dhcp_debug!("DEBUG: IP total length: {} bytes", total_len);
    let ip_start = frame.len();  // Save position for checksum calculation

    frame.push(0x45);
    frame.push(0x00);
    frame.extend_from_slice(&total_len.to_be_bytes());
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.push(64);
    frame.push(17);  // UDP
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.extend_from_slice(&src_ip.octets());  // 0.0.0.0
    frame.extend_from_slice(&dst_ip.octets());  // 255.255.255.255

    // Calculate IP checksum
    let ip_checksum = calculate_checksum(&frame[ip_start..ip_start + 20]);
    dhcp_debug!("DEBUG: Calculated IP checksum: 0x{:04x}", ip_checksum);
    frame[ip_start + 10] = (ip_checksum >> 8) as u8;
    frame[ip_start + 11] = (ip_checksum & 0xFF) as u8;

    // Append UDP and DHCP
    frame.extend_from_slice(&udp_header);
    frame.extend_from_slice(&dhcp_msg);

    dhcp_debug!("DEBUG: Complete frame built, total size={} bytes", frame.len());
    dhcp_debug!("DEBUG: Frame breakdown - Ethernet:14 + IP:20 + UDP:8 + DHCP:{} = {}",
           dhcp_msg.len(), frame.len());

    frame
}

/// Build basic DHCP DISCOVER message (RFC 2131)
fn build_dhcp_message(mac: [u8; 6], xid: u32, hostname: Option<&str>) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_message() called");
    dhcp_debug!("  MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
           mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    dhcp_debug!("  XID: 0x{:08x}", xid);
    dhcp_debug!("  Hostname: {:?}", hostname);

    let mut msg = Vec::new();

    // BOOTP header (236 bytes fixed)
    dhcp_debug!("DEBUG: Building BOOTP header (236 bytes)");
    msg.push(0x01);  // op: BOOTREQUEST (1)
    msg.push(0x01);  // htype: Ethernet (1)
    msg.push(0x06);  // hlen: MAC address length (6)
    msg.push(0x00);  // hops: 0

    msg.extend_from_slice(&xid.to_be_bytes());  // xid: transaction ID
    msg.extend_from_slice(&0u16.to_be_bytes());  // secs: 0
    msg.extend_from_slice(&0x8000u16.to_be_bytes());  // flags: broadcast (0x8000)
    dhcp_debug!("  op=1 (BOOTREQUEST), htype=1 (Ethernet), hlen=6, hops=0");
    dhcp_debug!("  xid=0x{:08x}, secs=0, flags=0x8000 (broadcast)", xid);

    msg.extend_from_slice(&[0; 4]);  // ciaddr: 0.0.0.0 (client IP)
    msg.extend_from_slice(&[0; 4]);  // yiaddr: 0.0.0.0 (your IP)
    msg.extend_from_slice(&[0; 4]);  // siaddr: 0.0.0.0 (server IP)
    msg.extend_from_slice(&[0; 4]);  // giaddr: 0.0.0.0 (gateway IP)
    dhcp_debug!("  ciaddr=0.0.0.0, yiaddr=0.0.0.0, siaddr=0.0.0.0, giaddr=0.0.0.0");

    msg.extend_from_slice(&mac);     // chaddr: client MAC
    msg.extend_from_slice(&[0; 10]); // chaddr padding (16 bytes total)
    dhcp_debug!("  chaddr (client MAC): {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
           mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    msg.extend_from_slice(&[0; 64]);  // sname: server name (empty)
    msg.extend_from_slice(&[0; 128]); // file: boot file name (empty)

    // DHCP magic cookie (RFC 2131)
    msg.extend_from_slice(&[0x63, 0x82, 0x53, 0x63]);
    dhcp_debug!("DEBUG: BOOTP header complete, size={} bytes", msg.len());
    dhcp_debug!("DEBUG: Adding DHCP magic cookie: 63 82 53 63");

    // DHCP Options
    // Option 53: DHCP Message Type = DISCOVER (1)
    msg.extend_from_slice(&[53, 1, 1]);
    dhcp_debug!("DEBUG: Added Option 53 (Message Type): DISCOVER (1)");

    // Option 61: Client Identifier (MAC address)
    msg.push(61);  // option code
    msg.push(7);   // length
    msg.push(0x01);  // hardware type: Ethernet
    msg.extend_from_slice(&mac);
    dhcp_debug!("DEBUG: Added Option 61 (Client ID): hwtype=1, MAC={:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
           mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    // Option 12: Hostname (if provided)
    if let Some(name) = hostname {
        let name_bytes = name.as_bytes();
        if name_bytes.len() <= 255 {
            msg.push(12);  // option code
            msg.push(name_bytes.len() as u8);  // length
            msg.extend_from_slice(name_bytes);
            dhcp_debug!("DEBUG: Added Option 12 (Hostname): \"{}\"", name);
        }
    }

    // Option 55: Parameter Request List
    msg.push(55);  // option code
    #[cfg(not(feature = "dhcp4-options"))]
    {
        msg.push(6);   // length
        msg.push(1);   // Subnet Mask
        msg.push(3);   // Router
        msg.push(6);   // DNS Server
        msg.push(15);  // Domain Name
        msg.push(42);  // NTP Server
        msg.push(121); // Classless Static Route
        dhcp_debug!("DEBUG: Added Option 55 (Parameter Request List): [1,3,6,15,42,121]");
    }
    #[cfg(feature = "dhcp4-options")]
    {
        msg.push(18);  // length (extended options)
        msg.push(1);   // Subnet Mask
        msg.push(3);   // Router
        msg.push(6);   // DNS Server
        msg.push(15);  // Domain Name
        msg.push(42);  // NTP Server
        msg.push(121); // Classless Static Route
        msg.push(41);  // NIS Servers
        msg.push(65);  // NIS+ Server
        msg.push(66);  // TFTP Server Name
        msg.push(67);  // Boot File Name
        msg.push(69);  // SMTP Servers
        msg.push(70);  // POP3 Servers
        msg.push(71);  // NNTP Servers
        msg.push(72);  // WWW Servers
        msg.push(77);  // User Class
        msg.push(81);  // Client FQDN
        msg.push(95);  // LDAP Servers
        msg.push(119); // Domain Search List
        dhcp_debug!("DEBUG: Added Option 55 (Parameter Request List): [1,3,6,15,42,121,41,65,66,67,69,70,71,72,77,81,95,119]");
    }

    // Option 255: End
    msg.push(255);
    dhcp_debug!("DEBUG: Added Option 255 (End)");

    dhcp_debug!("DEBUG: DHCP message complete, total size={} bytes", msg.len());

    msg
}

/// Build DHCP REQUEST packet for IP layer socket
pub fn build_dhcp_request_ip_packet(
    mac_address: [u8; 6],
    xid: u32,
    requested_ip: Ipv4Addr,
    server_id: Ipv4Addr,
    hostname: Option<&str>,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_request_ip_packet() called");
    dhcp_debug!("  MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
           mac_address[0], mac_address[1], mac_address[2],
           mac_address[3], mac_address[4], mac_address[5]);
    dhcp_debug!("  XID: 0x{:08x}", xid);
    dhcp_debug!("  Requested IP: {}", requested_ip);
    dhcp_debug!("  Server ID: {}", server_id);

    let src_ip = Ipv4Addr::new(0, 0, 0, 0);
    let dst_ip = Ipv4Addr::new(255, 255, 255, 255);
    let src_port: u16 = 68;
    let dst_port: u16 = 67;

    // Build DHCP REQUEST message
    let dhcp_msg = build_dhcp_request_message(mac_address, xid, requested_ip, server_id, hostname);
    dhcp_debug!("DEBUG: DHCP REQUEST message built, size={} bytes", dhcp_msg.len());

    // Build UDP header
    let udp_len = (8 + dhcp_msg.len()) as u16;
    let mut udp_header = Vec::new();
    udp_header.extend_from_slice(&src_port.to_be_bytes());
    udp_header.extend_from_slice(&dst_port.to_be_bytes());
    udp_header.extend_from_slice(&udp_len.to_be_bytes());
    udp_header.extend_from_slice(&0u16.to_be_bytes());

    // Build IP header
    let total_len = (20 + 8 + dhcp_msg.len()) as u16;
    let mut packet = Vec::new();
    packet.push(0x45);
    packet.push(0x00);
    packet.extend_from_slice(&total_len.to_be_bytes());
    packet.extend_from_slice(&0u16.to_be_bytes());
    packet.extend_from_slice(&0u16.to_be_bytes());
    packet.push(64);
    packet.push(17);
    packet.extend_from_slice(&0u16.to_be_bytes());
    packet.extend_from_slice(&src_ip.octets());
    packet.extend_from_slice(&dst_ip.octets());

    let ip_checksum = calculate_checksum(&packet[0..20]);
    packet[10] = (ip_checksum >> 8) as u8;
    packet[11] = (ip_checksum & 0xFF) as u8;

    packet.extend_from_slice(&udp_header);
    packet.extend_from_slice(&dhcp_msg);

    dhcp_debug!("DEBUG: Complete REQUEST packet built, total size={} bytes", packet.len());
    packet
}

/// Build DHCP REQUEST frame for link layer socket
pub fn build_dhcp_request_link_frame(
    src_mac: [u8; 6],
    xid: u32,
    requested_ip: Ipv4Addr,
    server_id: Ipv4Addr,
    hostname: Option<&str>,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_request_link_frame() called");

    let dst_mac = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff];  // Broadcast MAC
    let src_ip = Ipv4Addr::new(0, 0, 0, 0);
    let dst_ip = Ipv4Addr::new(255, 255, 255, 255);
    let src_port: u16 = 68;
    let dst_port: u16 = 67;

    let mut frame = Vec::new();

    // Ethernet Header (14 bytes)
    frame.extend_from_slice(&dst_mac);  // Destination MAC: broadcast
    frame.extend_from_slice(&src_mac);  // Source MAC
    frame.extend_from_slice(&[0x08, 0x00]);  // EtherType: IPv4

    // Build DHCP REQUEST message
    let dhcp_msg = build_dhcp_request_message(src_mac, xid, requested_ip, server_id, hostname);

    // UDP Header
    let udp_len = (8 + dhcp_msg.len()) as u16;
    let mut udp_header = Vec::new();
    udp_header.extend_from_slice(&src_port.to_be_bytes());
    udp_header.extend_from_slice(&dst_port.to_be_bytes());
    udp_header.extend_from_slice(&udp_len.to_be_bytes());
    udp_header.extend_from_slice(&0u16.to_be_bytes());  // checksum

    // IP Header
    let total_len = (20 + 8 + dhcp_msg.len()) as u16;
    let ip_start = frame.len();  // Save position for checksum calculation

    frame.push(0x45);
    frame.push(0x00);
    frame.extend_from_slice(&total_len.to_be_bytes());
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.push(64);
    frame.push(17);  // UDP
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.extend_from_slice(&src_ip.octets());  // 0.0.0.0
    frame.extend_from_slice(&dst_ip.octets());  // 255.255.255.255

    // Calculate IP checksum
    let ip_checksum = calculate_checksum(&frame[ip_start..ip_start + 20]);
    frame[ip_start + 10] = (ip_checksum >> 8) as u8;
    frame[ip_start + 11] = (ip_checksum & 0xFF) as u8;

    // Append UDP and DHCP
    frame.extend_from_slice(&udp_header);
    frame.extend_from_slice(&dhcp_msg);

    dhcp_debug!("DEBUG: Complete REQUEST frame built, total size={} bytes", frame.len());
    frame
}

/// Build DHCP REQUEST message (RFC 2131)
fn build_dhcp_request_message(
    mac: [u8; 6],
    xid: u32,
    requested_ip: Ipv4Addr,
    server_id: Ipv4Addr,
    hostname: Option<&str>,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_request_message() called");

    let mut msg = Vec::new();

    // BOOTP header
    msg.push(0x01);
    msg.push(0x01);
    msg.push(0x06);
    msg.push(0x00);
    msg.extend_from_slice(&xid.to_be_bytes());
    msg.extend_from_slice(&0u16.to_be_bytes());
    msg.extend_from_slice(&0x8000u16.to_be_bytes());
    msg.extend_from_slice(&[0; 4]);  // ciaddr
    msg.extend_from_slice(&[0; 4]);  // yiaddr
    msg.extend_from_slice(&[0; 4]);  // siaddr
    msg.extend_from_slice(&[0; 4]);  // giaddr
    msg.extend_from_slice(&mac);
    msg.extend_from_slice(&[0; 10]);
    msg.extend_from_slice(&[0; 64]);
    msg.extend_from_slice(&[0; 128]);
    msg.extend_from_slice(&[0x63, 0x82, 0x53, 0x63]);

    // Option 53: DHCP Message Type = REQUEST (3)
    msg.extend_from_slice(&[53, 1, 3]);

    // Option 50: Requested IP Address
    msg.push(50);
    msg.push(4);
    msg.extend_from_slice(&requested_ip.octets());
    dhcp_debug!("DEBUG: Added Option 50 (Requested IP): {}", requested_ip);

    // Option 54: Server Identifier
    msg.push(54);
    msg.push(4);
    msg.extend_from_slice(&server_id.octets());
    dhcp_debug!("DEBUG: Added Option 54 (Server ID): {}", server_id);

    // Option 61: Client Identifier
    msg.push(61);
    msg.push(7);
    msg.push(0x01);
    msg.extend_from_slice(&mac);

    // Option 12: Hostname
    if let Some(name) = hostname {
        let name_bytes = name.as_bytes();
        if name_bytes.len() <= 255 {
            msg.push(12);
            msg.push(name_bytes.len() as u8);
            msg.extend_from_slice(name_bytes);
        }
    }

    // Option 55: Parameter Request List
    msg.push(55);
    #[cfg(not(feature = "dhcp4-options"))]
    {
        msg.push(6);
        msg.push(1);   // Subnet Mask
        msg.push(3);   // Router
        msg.push(6);   // DNS Server
        msg.push(15);  // Domain Name
        msg.push(42);  // NTP Server
        msg.push(121); // Classless Static Route
    }
    #[cfg(feature = "dhcp4-options")]
    {
        msg.push(18);  // length (extended options)
        msg.push(1);   // Subnet Mask
        msg.push(3);   // Router
        msg.push(6);   // DNS Server
        msg.push(15);  // Domain Name
        msg.push(42);  // NTP Server
        msg.push(121); // Classless Static Route
        msg.push(41);  // NIS Servers
        msg.push(65);  // NIS+ Server
        msg.push(66);  // TFTP Server Name
        msg.push(67);  // Boot File Name
        msg.push(69);  // SMTP Servers
        msg.push(70);  // POP3 Servers
        msg.push(71);  // NNTP Servers
        msg.push(72);  // WWW Servers
        msg.push(77);  // User Class
        msg.push(81);  // Client FQDN
        msg.push(95);  // LDAP Servers
        msg.push(119); // Domain Search List
    }

    // Option 255: End
    msg.push(255);

    dhcp_debug!("DEBUG: DHCP REQUEST message complete, size={} bytes", msg.len());
    msg
}

/// Build DHCP RELEASE packet for IP layer socket
pub fn build_dhcp_release_ip_packet(
    mac_address: [u8; 6],
    xid: u32,
    client_ip: Ipv4Addr,
    server_id: Ipv4Addr,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_release_ip_packet() called");

    let src_ip = client_ip;
    let dst_ip = server_id;
    let src_port: u16 = 68;
    let dst_port: u16 = 67;

    // Build DHCP RELEASE message
    let mut msg = Vec::new();
    msg.push(0x01);
    msg.push(0x01);
    msg.push(0x06);
    msg.push(0x00);
    msg.extend_from_slice(&xid.to_be_bytes());
    msg.extend_from_slice(&0u16.to_be_bytes());
    msg.extend_from_slice(&0u16.to_be_bytes());
    msg.extend_from_slice(&client_ip.octets());  // ciaddr
    msg.extend_from_slice(&[0; 4]);  // yiaddr
    msg.extend_from_slice(&[0; 4]);  // siaddr
    msg.extend_from_slice(&[0; 4]);  // giaddr
    msg.extend_from_slice(&mac_address);
    msg.extend_from_slice(&[0; 10]);
    msg.extend_from_slice(&[0; 64]);
    msg.extend_from_slice(&[0; 128]);
    msg.extend_from_slice(&[0x63, 0x82, 0x53, 0x63]);

    // Option 53: DHCP Message Type = RELEASE (7)
    msg.extend_from_slice(&[53, 1, 7]);

    // Option 54: Server Identifier
    msg.push(54);
    msg.push(4);
    msg.extend_from_slice(&server_id.octets());

    // Option 61: Client Identifier
    msg.push(61);
    msg.push(7);
    msg.push(0x01);
    msg.extend_from_slice(&mac_address);

    // Option 255: End
    msg.push(255);

    dhcp_debug!("DEBUG: DHCP RELEASE message built, size={} bytes", msg.len());

    // Build UDP header
    let udp_len = (8 + msg.len()) as u16;
    let mut udp_header = Vec::new();
    udp_header.extend_from_slice(&src_port.to_be_bytes());
    udp_header.extend_from_slice(&dst_port.to_be_bytes());
    udp_header.extend_from_slice(&udp_len.to_be_bytes());
    udp_header.extend_from_slice(&0u16.to_be_bytes());

    // Build IP header
    let total_len = (20 + 8 + msg.len()) as u16;
    let mut packet = Vec::new();
    packet.push(0x45);
    packet.push(0x00);
    packet.extend_from_slice(&total_len.to_be_bytes());
    packet.extend_from_slice(&0u16.to_be_bytes());
    packet.extend_from_slice(&0u16.to_be_bytes());
    packet.push(64);
    packet.push(17);
    packet.extend_from_slice(&0u16.to_be_bytes());
    packet.extend_from_slice(&src_ip.octets());
    packet.extend_from_slice(&dst_ip.octets());

    let ip_checksum = calculate_checksum(&packet[0..20]);
    packet[10] = (ip_checksum >> 8) as u8;
    packet[11] = (ip_checksum & 0xFF) as u8;

    packet.extend_from_slice(&udp_header);
    packet.extend_from_slice(&msg);

    packet
}

/// Build DHCP DECLINE packet for IP layer socket
///
/// DHCPDECLINE is sent when the client detects the offered IP is already in use
pub fn build_dhcp_decline_ip_packet(
    mac_address: [u8; 6],
    xid: u32,
    declined_ip: Ipv4Addr,
    server_id: Ipv4Addr,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_decline_ip_packet() called");

    let src_ip = Ipv4Addr::new(0, 0, 0, 0);
    let dst_ip = Ipv4Addr::new(255, 255, 255, 255);
    let src_port: u16 = 68;
    let dst_port: u16 = 67;

    // Build DHCP DECLINE message
    let dhcp_msg = build_dhcp_decline_message(mac_address, xid, declined_ip, server_id);
    dhcp_debug!("DEBUG: DHCP DECLINE message built, size={} bytes", dhcp_msg.len());

    // Build UDP header
    let udp_len = (8 + dhcp_msg.len()) as u16;
    let mut udp_header = Vec::new();
    udp_header.extend_from_slice(&src_port.to_be_bytes());
    udp_header.extend_from_slice(&dst_port.to_be_bytes());
    udp_header.extend_from_slice(&udp_len.to_be_bytes());
    udp_header.extend_from_slice(&0u16.to_be_bytes());

    // Build IP header
    let total_len = (20 + 8 + dhcp_msg.len()) as u16;
    let mut packet = Vec::new();
    packet.push(0x45);
    packet.push(0x00);
    packet.extend_from_slice(&total_len.to_be_bytes());
    packet.extend_from_slice(&0u16.to_be_bytes());
    packet.extend_from_slice(&0u16.to_be_bytes());
    packet.push(64);
    packet.push(17);
    packet.extend_from_slice(&0u16.to_be_bytes());
    packet.extend_from_slice(&src_ip.octets());
    packet.extend_from_slice(&dst_ip.octets());

    let ip_checksum = calculate_checksum(&packet[0..20]);
    packet[10] = (ip_checksum >> 8) as u8;
    packet[11] = (ip_checksum & 0xFF) as u8;

    packet.extend_from_slice(&udp_header);
    packet.extend_from_slice(&dhcp_msg);

    packet
}

/// Build DHCP DECLINE frame for link layer socket
///
/// DHCPDECLINE is sent when the client detects the offered IP is already in use
pub fn build_dhcp_decline_link_frame(
    src_mac: [u8; 6],
    xid: u32,
    declined_ip: Ipv4Addr,
    server_id: Ipv4Addr,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_decline_link_frame() called");

    let dst_mac = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff];  // Broadcast MAC
    let src_ip = Ipv4Addr::new(0, 0, 0, 0);
    let dst_ip = Ipv4Addr::new(255, 255, 255, 255);
    let src_port: u16 = 68;
    let dst_port: u16 = 67;

    let mut frame = Vec::new();

    // Ethernet Header (14 bytes)
    frame.extend_from_slice(&dst_mac);  // Destination MAC: broadcast
    frame.extend_from_slice(&src_mac);  // Source MAC
    frame.extend_from_slice(&[0x08, 0x00]);  // EtherType: IPv4

    // Build DHCP DECLINE message
    let dhcp_msg = build_dhcp_decline_message(src_mac, xid, declined_ip, server_id);

    // UDP Header
    let udp_len = (8 + dhcp_msg.len()) as u16;
    let mut udp_header = Vec::new();
    udp_header.extend_from_slice(&src_port.to_be_bytes());
    udp_header.extend_from_slice(&dst_port.to_be_bytes());
    udp_header.extend_from_slice(&udp_len.to_be_bytes());
    udp_header.extend_from_slice(&0u16.to_be_bytes());

    // IP Header
    let total_len = (20 + 8 + dhcp_msg.len()) as u16;
    let ip_start = frame.len();

    frame.push(0x45);
    frame.push(0x00);
    frame.extend_from_slice(&total_len.to_be_bytes());
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.push(64);
    frame.push(17);
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.extend_from_slice(&src_ip.octets());
    frame.extend_from_slice(&dst_ip.octets());

    let ip_checksum = calculate_checksum(&frame[ip_start..ip_start + 20]);
    frame[ip_start + 10] = (ip_checksum >> 8) as u8;
    frame[ip_start + 11] = (ip_checksum & 0xFF) as u8;

    frame.extend_from_slice(&udp_header);
    frame.extend_from_slice(&dhcp_msg);

    dhcp_debug!("DEBUG: Complete DECLINE frame built, total size={} bytes", frame.len());
    frame
}

/// Build DHCP DECLINE message (RFC 2131)
///
/// DHCPDECLINE must include:
/// - Option 53: DHCP Message Type = DECLINE (4)
/// - Option 50: Requested IP Address (the declined IP)
/// - Option 54: Server Identifier
/// - Option 61: Client Identifier (optional but recommended)
fn build_dhcp_decline_message(
    mac: [u8; 6],
    xid: u32,
    declined_ip: Ipv4Addr,
    server_id: Ipv4Addr,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_decline_message() called");
    dhcp_debug!("  Declined IP: {}", declined_ip);
    dhcp_debug!("  Server ID: {}", server_id);

    let mut msg = Vec::new();

    // BOOTP header (236 bytes fixed)
    msg.push(0x01);  // op: BOOTREQUEST (1)
    msg.push(0x01);  // htype: Ethernet (1)
    msg.push(0x06);  // hlen: MAC address length (6)
    msg.push(0x00);  // hops: 0

    msg.extend_from_slice(&xid.to_be_bytes());  // xid: transaction ID
    msg.extend_from_slice(&0u16.to_be_bytes());  // secs: 0
    msg.extend_from_slice(&0u16.to_be_bytes());  // flags: 0 (no broadcast needed for DECLINE)

    msg.extend_from_slice(&[0; 4]);  // ciaddr: 0.0.0.0 (MUST be zero per RFC 2131)
    msg.extend_from_slice(&[0; 4]);  // yiaddr: 0.0.0.0
    msg.extend_from_slice(&[0; 4]);  // siaddr: 0.0.0.0
    msg.extend_from_slice(&[0; 4]);  // giaddr: 0.0.0.0

    msg.extend_from_slice(&mac);     // chaddr: client MAC
    msg.extend_from_slice(&[0; 10]); // chaddr padding (16 bytes total)

    msg.extend_from_slice(&[0; 64]);  // sname: server name (empty)
    msg.extend_from_slice(&[0; 128]); // file: boot file name (empty)

    // DHCP magic cookie
    msg.extend_from_slice(&[0x63, 0x82, 0x53, 0x63]);

    // Option 53: DHCP Message Type = DECLINE (4)
    msg.extend_from_slice(&[53, 1, 4]);
    dhcp_debug!("DEBUG: Added Option 53 (Message Type): DECLINE (4)");

    // Option 50: Requested IP Address (the IP we're declining)
    msg.push(50);
    msg.push(4);
    msg.extend_from_slice(&declined_ip.octets());
    dhcp_debug!("DEBUG: Added Option 50 (Requested IP): {}", declined_ip);

    // Option 54: Server Identifier
    msg.push(54);
    msg.push(4);
    msg.extend_from_slice(&server_id.octets());
    dhcp_debug!("DEBUG: Added Option 54 (Server ID): {}", server_id);

    // Option 61: Client Identifier
    msg.push(61);
    msg.push(7);
    msg.push(0x01);  // hardware type: Ethernet
    msg.extend_from_slice(&mac);
    dhcp_debug!("DEBUG: Added Option 61 (Client ID)");

    // Option 255: End
    msg.push(255);

    dhcp_debug!("DEBUG: DHCP DECLINE message complete, size={} bytes", msg.len());
    msg
}

/// Build DHCP RELEASE frame for link layer socket
pub fn build_dhcp_release_link_frame(
    src_mac: [u8; 6],
    xid: u32,
    client_ip: Ipv4Addr,
    server_id: Ipv4Addr,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_dhcp_release_link_frame() called");

    let dst_mac = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff];  // Broadcast MAC
    let src_ip = client_ip;
    let dst_ip = server_id;
    let src_port: u16 = 68;
    let dst_port: u16 = 67;

    let mut frame = Vec::new();

    // Ethernet Header (14 bytes)
    frame.extend_from_slice(&dst_mac);  // Destination MAC: broadcast
    frame.extend_from_slice(&src_mac);  // Source MAC
    frame.extend_from_slice(&[0x08, 0x00]);  // EtherType: IPv4

    // Build DHCP RELEASE message
    let mut msg = Vec::new();
    msg.push(0x01);
    msg.push(0x01);
    msg.push(0x06);
    msg.push(0x00);
    msg.extend_from_slice(&xid.to_be_bytes());
    msg.extend_from_slice(&0u16.to_be_bytes());
    msg.extend_from_slice(&0u16.to_be_bytes());
    msg.extend_from_slice(&client_ip.octets());  // ciaddr
    msg.extend_from_slice(&[0; 4]);  // yiaddr
    msg.extend_from_slice(&[0; 4]);  // siaddr
    msg.extend_from_slice(&[0; 4]);  // giaddr
    msg.extend_from_slice(&src_mac);
    msg.extend_from_slice(&[0; 10]);
    msg.extend_from_slice(&[0; 64]);
    msg.extend_from_slice(&[0; 128]);
    msg.extend_from_slice(&[0x63, 0x82, 0x53, 0x63]);

    // Option 53: DHCP Message Type = RELEASE (7)
    msg.extend_from_slice(&[53, 1, 7]);

    // Option 54: Server Identifier
    msg.push(54);
    msg.push(4);
    msg.extend_from_slice(&server_id.octets());

    // Option 61: Client Identifier
    msg.push(61);
    msg.push(7);
    msg.push(0x01);
    msg.extend_from_slice(&src_mac);

    // Option 255: End
    msg.push(255);

    // UDP Header
    let udp_len = (8 + msg.len()) as u16;
    let mut udp_header = Vec::new();
    udp_header.extend_from_slice(&src_port.to_be_bytes());
    udp_header.extend_from_slice(&dst_port.to_be_bytes());
    udp_header.extend_from_slice(&udp_len.to_be_bytes());
    udp_header.extend_from_slice(&0u16.to_be_bytes());

    // IP Header
    let total_len = (20 + 8 + msg.len()) as u16;
    let ip_start = frame.len();

    frame.push(0x45);
    frame.push(0x00);
    frame.extend_from_slice(&total_len.to_be_bytes());
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.push(64);
    frame.push(17);
    frame.extend_from_slice(&0u16.to_be_bytes());
    frame.extend_from_slice(&src_ip.octets());
    frame.extend_from_slice(&dst_ip.octets());

    let ip_checksum = calculate_checksum(&frame[ip_start..ip_start + 20]);
    frame[ip_start + 10] = (ip_checksum >> 8) as u8;
    frame[ip_start + 11] = (ip_checksum & 0xFF) as u8;

    frame.extend_from_slice(&udp_header);
    frame.extend_from_slice(&msg);

    dhcp_debug!("DEBUG: Complete RELEASE frame built, total size={} bytes", frame.len());
    frame
}

/// Parse DHCP response packet (Link Layer format with Ethernet header)
/// Returns (message_type, xid, options_data) if valid DHCP packet
pub fn parse_dhcp_packet(packet: &[u8]) -> Result<(u8, u32, Vec<u8>)> {
    dhcp_debug!("DEBUG: parse_dhcp_packet() called, packet size={} bytes", packet.len());

    // For Link Layer packets: Ethernet (14) + IP (20) + UDP (8) = 42 bytes before DHCP
    let dhcp_start = 42;
    if packet.len() < dhcp_start + 240 {
        dhcp_debug!("DEBUG: Packet too short - need {} bytes, got {}", dhcp_start + 240, packet.len());
        return Err(anyhow!("Packet too short for DHCP message"));
    }

    dhcp_debug!("DEBUG: DHCP message starts at offset {}", dhcp_start);
    let dhcp_msg = &packet[dhcp_start..];

    // Verify BOOTP reply
    if dhcp_msg[0] != 0x02 {
        dhcp_debug!("DEBUG: Not a BOOTP reply (op={})", dhcp_msg[0]);
        return Err(anyhow!("Not a BOOTP reply"));
    }

    // Extract transaction ID
    let xid = u32::from_be_bytes([dhcp_msg[4], dhcp_msg[5], dhcp_msg[6], dhcp_msg[7]]);
    dhcp_debug!("DEBUG: Transaction ID: 0x{:08x}", xid);

    // Verify magic cookie at offset 236
    if &dhcp_msg[236..240] != &[0x63, 0x82, 0x53, 0x63] {
        dhcp_debug!("DEBUG: Invalid DHCP magic cookie");
        return Err(anyhow!("Invalid DHCP magic cookie"));
    }

    // Parse options to find message type
    let mut msg_type: Option<u8> = None;
    let mut i = 240;  // Start of options

    while i < dhcp_msg.len() {
        let option = dhcp_msg[i];

        if option == 255 {
            break;  // End option
        }

        if option == 0 {
            i += 1;  // Pad option
            continue;
        }

        if i + 1 >= dhcp_msg.len() {
            break;
        }

        let length = dhcp_msg[i + 1] as usize;

        if option == 53 && length == 1 {
            msg_type = Some(dhcp_msg[i + 2]);
            dhcp_debug!("DEBUG: Found DHCP message type: {}", dhcp_msg[i + 2]);
        }

        i += 2 + length;
    }

    let msg_type = msg_type.ok_or_else(|| anyhow!("No DHCP message type option found"))?;

    // Return the full DHCP message for further parsing
    Ok((msg_type, xid, dhcp_msg.to_vec()))
}

/// Extract offered IP address from DHCP message
pub fn extract_offered_ip(dhcp_msg: &[u8]) -> Result<Ipv4Addr> {
    if dhcp_msg.len() < 20 {
        return Err(anyhow!("DHCP message too short"));
    }

    // yiaddr is at offset 16-19
    let ip = Ipv4Addr::new(dhcp_msg[16], dhcp_msg[17], dhcp_msg[18], dhcp_msg[19]);
    dhcp_debug!("DEBUG: Extracted offered IP: {}", ip);
    Ok(ip)
}

/// Extract server identifier from DHCP options
pub fn extract_server_id(dhcp_msg: &[u8]) -> Result<Ipv4Addr> {
    let mut i = 240;  // Start of options

    while i < dhcp_msg.len() {
        let option = dhcp_msg[i];

        if option == 255 {
            break;
        }

        if option == 0 {
            i += 1;
            continue;
        }

        if i + 1 >= dhcp_msg.len() {
            break;
        }

        let length = dhcp_msg[i + 1] as usize;

        // Option 54: Server Identifier
        if option == 54 && length == 4 {
            let server_id = Ipv4Addr::new(
                dhcp_msg[i + 2],
                dhcp_msg[i + 3],
                dhcp_msg[i + 4],
                dhcp_msg[i + 5],
            );
            dhcp_debug!("DEBUG: Extracted server ID: {}", server_id);
            return Ok(server_id);
        }

        i += 2 + length;
    }

    Err(anyhow!("Server ID option not found"))
}

/// Client FQDN option (Option 81, RFC 4702)
#[cfg(feature = "dhcp4-options")]
#[derive(Debug, Clone)]
pub struct ClientFqdn {
    pub flags: u8,
    pub rcode1: u8,
    pub rcode2: u8,
    pub domain_name: String,
}

/// Classless Static Route (Option 121, RFC 3442)
#[cfg(feature = "dhcp4-options")]
#[derive(Debug, Clone)]
pub struct ClasslessRoute {
    pub destination: Ipv4Addr,
    pub prefix_len: u8,
    pub gateway: Ipv4Addr,
}

/// Lease information extracted from DHCP ACK
#[derive(Debug, Clone)]
pub struct DhcpLeaseInfo {
    pub ip_address: Ipv4Addr,
    pub subnet_mask: Option<Ipv4Addr>,
    pub router: Option<Ipv4Addr>,
    pub dns_servers: Vec<Ipv4Addr>,
    pub domain_name: Option<String>,
    pub ntp_servers: Vec<Ipv4Addr>,
    pub lease_time: u32,
    pub renewal_time: Option<u32>,
    pub rebinding_time: Option<u32>,
    pub server_id: Ipv4Addr,
    // Extended options (enabled with dhcp4-options feature)
    #[cfg(feature = "dhcp4-options")]
    pub nis_servers: Vec<Ipv4Addr>,           // Option 41
    #[cfg(feature = "dhcp4-options")]
    pub nisplus_domain: Option<String>,        // Option 65
    #[cfg(feature = "dhcp4-options")]
    pub tftp_server_name: Option<String>,      // Option 66
    #[cfg(feature = "dhcp4-options")]
    pub bootfile_name: Option<String>,         // Option 67
    #[cfg(feature = "dhcp4-options")]
    pub smtp_servers: Vec<Ipv4Addr>,           // Option 69
    #[cfg(feature = "dhcp4-options")]
    pub pop3_servers: Vec<Ipv4Addr>,           // Option 70
    #[cfg(feature = "dhcp4-options")]
    pub nntp_servers: Vec<Ipv4Addr>,           // Option 71
    #[cfg(feature = "dhcp4-options")]
    pub www_servers: Vec<Ipv4Addr>,            // Option 72
    #[cfg(feature = "dhcp4-options")]
    pub user_class: Option<Vec<u8>>,           // Option 77
    #[cfg(feature = "dhcp4-options")]
    pub client_fqdn: Option<ClientFqdn>,       // Option 81
    #[cfg(feature = "dhcp4-options")]
    pub ldap_servers: Option<String>,          // Option 95
    #[cfg(feature = "dhcp4-options")]
    pub domain_search: Vec<String>,            // Option 119
    #[cfg(feature = "dhcp4-options")]
    pub classless_routes: Vec<ClasslessRoute>, // Option 121
}

/// Extract full lease information from DHCP ACK message
pub fn extract_lease_info(dhcp_msg: &[u8]) -> Result<DhcpLeaseInfo> {
    dhcp_debug!("DEBUG: extract_lease_info() called");

    // Extract IP address (yiaddr at offset 16-19)
    let ip_address = extract_offered_ip(dhcp_msg)?;
    dhcp_debug!("DEBUG: IP address: {}", ip_address);

    let mut subnet_mask: Option<Ipv4Addr> = None;
    let mut router: Option<Ipv4Addr> = None;
    let mut dns_servers: Vec<Ipv4Addr> = Vec::new();
    let mut domain_name: Option<String> = None;
    let mut ntp_servers: Vec<Ipv4Addr> = Vec::new();
    let mut lease_time: Option<u32> = None;
    let mut renewal_time: Option<u32> = None;
    let mut rebinding_time: Option<u32> = None;
    let mut server_id: Option<Ipv4Addr> = None;

    // Extended options (dhcp4-options feature)
    #[cfg(feature = "dhcp4-options")]
    let mut nis_servers: Vec<Ipv4Addr> = Vec::new();
    #[cfg(feature = "dhcp4-options")]
    let mut nisplus_domain: Option<String> = None;
    #[cfg(feature = "dhcp4-options")]
    let mut tftp_server_name: Option<String> = None;
    #[cfg(feature = "dhcp4-options")]
    let mut bootfile_name: Option<String> = None;
    #[cfg(feature = "dhcp4-options")]
    let mut smtp_servers: Vec<Ipv4Addr> = Vec::new();
    #[cfg(feature = "dhcp4-options")]
    let mut pop3_servers: Vec<Ipv4Addr> = Vec::new();
    #[cfg(feature = "dhcp4-options")]
    let mut nntp_servers: Vec<Ipv4Addr> = Vec::new();
    #[cfg(feature = "dhcp4-options")]
    let mut www_servers: Vec<Ipv4Addr> = Vec::new();
    #[cfg(feature = "dhcp4-options")]
    let mut user_class: Option<Vec<u8>> = None;
    #[cfg(feature = "dhcp4-options")]
    let mut client_fqdn: Option<ClientFqdn> = None;
    #[cfg(feature = "dhcp4-options")]
    let mut ldap_servers: Option<String> = None;
    #[cfg(feature = "dhcp4-options")]
    let mut domain_search: Vec<String> = Vec::new();
    #[cfg(feature = "dhcp4-options")]
    let mut classless_routes: Vec<ClasslessRoute> = Vec::new();

    // Parse options
    let mut i = 240;
    while i < dhcp_msg.len() {
        let option = dhcp_msg[i];

        if option == 255 {
            break;
        }

        if option == 0 {
            i += 1;
            continue;
        }

        if i + 1 >= dhcp_msg.len() {
            break;
        }

        let length = dhcp_msg[i + 1] as usize;

        if i + 2 + length > dhcp_msg.len() {
            break;
        }

        match option {
            1 => {
                // Subnet Mask
                if length == 4 {
                    subnet_mask = Some(Ipv4Addr::new(
                        dhcp_msg[i + 2],
                        dhcp_msg[i + 3],
                        dhcp_msg[i + 4],
                        dhcp_msg[i + 5],
                    ));
                    dhcp_debug!("DEBUG: Subnet mask: {:?}", subnet_mask);
                }
            }
            3 => {
                // Router
                if length >= 4 {
                    router = Some(Ipv4Addr::new(
                        dhcp_msg[i + 2],
                        dhcp_msg[i + 3],
                        dhcp_msg[i + 4],
                        dhcp_msg[i + 5],
                    ));
                    dhcp_debug!("DEBUG: Router: {:?}", router);
                }
            }
            6 => {
                // DNS Servers
                let mut j = 0;
                while j + 4 <= length {
                    let dns = Ipv4Addr::new(
                        dhcp_msg[i + 2 + j],
                        dhcp_msg[i + 3 + j],
                        dhcp_msg[i + 4 + j],
                        dhcp_msg[i + 5 + j],
                    );
                    dns_servers.push(dns);
                    j += 4;
                }
                dhcp_debug!("DEBUG: DNS servers: {:?}", dns_servers);
            }
            15 => {
                // Domain Name
                if let Ok(name) = String::from_utf8(dhcp_msg[i + 2..i + 2 + length].to_vec()) {
                    domain_name = Some(name.clone());
                    dhcp_debug!("DEBUG: Domain name: {}", name);
                }
            }
            42 => {
                // NTP Servers
                let mut j = 0;
                while j + 4 <= length {
                    let ntp = Ipv4Addr::new(
                        dhcp_msg[i + 2 + j],
                        dhcp_msg[i + 3 + j],
                        dhcp_msg[i + 4 + j],
                        dhcp_msg[i + 5 + j],
                    );
                    ntp_servers.push(ntp);
                    j += 4;
                }
                dhcp_debug!("DEBUG: NTP servers: {:?}", ntp_servers);
            }
            51 => {
                // Lease Time
                if length == 4 {
                    lease_time = Some(u32::from_be_bytes([
                        dhcp_msg[i + 2],
                        dhcp_msg[i + 3],
                        dhcp_msg[i + 4],
                        dhcp_msg[i + 5],
                    ]));
                    dhcp_debug!("DEBUG: Lease time: {} seconds", lease_time.unwrap());
                }
            }
            54 => {
                // Server Identifier
                if length == 4 {
                    server_id = Some(Ipv4Addr::new(
                        dhcp_msg[i + 2],
                        dhcp_msg[i + 3],
                        dhcp_msg[i + 4],
                        dhcp_msg[i + 5],
                    ));
                    dhcp_debug!("DEBUG: Server ID: {:?}", server_id);
                }
            }
            58 => {
                // Renewal Time (T1)
                if length == 4 {
                    renewal_time = Some(u32::from_be_bytes([
                        dhcp_msg[i + 2],
                        dhcp_msg[i + 3],
                        dhcp_msg[i + 4],
                        dhcp_msg[i + 5],
                    ]));
                    dhcp_debug!("DEBUG: Renewal time (T1): {} seconds", renewal_time.unwrap());
                }
            }
            59 => {
                // Rebinding Time (T2)
                if length == 4 {
                    rebinding_time = Some(u32::from_be_bytes([
                        dhcp_msg[i + 2],
                        dhcp_msg[i + 3],
                        dhcp_msg[i + 4],
                        dhcp_msg[i + 5],
                    ]));
                    dhcp_debug!("DEBUG: Rebinding time (T2): {} seconds", rebinding_time.unwrap());
                }
            }
            // Extended options (dhcp4-options feature)
            #[cfg(feature = "dhcp4-options")]
            41 => {
                // NIS Servers
                let mut j = 0;
                while j + 4 <= length {
                    let addr = Ipv4Addr::new(
                        dhcp_msg[i + 2 + j], dhcp_msg[i + 3 + j],
                        dhcp_msg[i + 4 + j], dhcp_msg[i + 5 + j],
                    );
                    nis_servers.push(addr);
                    j += 4;
                }
                dhcp_debug!("DEBUG: NIS servers: {:?}", nis_servers);
            }
            #[cfg(feature = "dhcp4-options")]
            65 => {
                // NIS+ Domain Name
                if let Ok(name) = String::from_utf8(dhcp_msg[i + 2..i + 2 + length].to_vec()) {
                    nisplus_domain = Some(name.clone());
                    dhcp_debug!("DEBUG: NIS+ domain: {}", name);
                }
            }
            #[cfg(feature = "dhcp4-options")]
            66 => {
                // TFTP Server Name
                if let Ok(name) = String::from_utf8(dhcp_msg[i + 2..i + 2 + length].to_vec()) {
                    tftp_server_name = Some(name.trim_end_matches('\0').to_string());
                    dhcp_debug!("DEBUG: TFTP server: {:?}", tftp_server_name);
                }
            }
            #[cfg(feature = "dhcp4-options")]
            67 => {
                // Bootfile Name
                if let Ok(name) = String::from_utf8(dhcp_msg[i + 2..i + 2 + length].to_vec()) {
                    bootfile_name = Some(name.trim_end_matches('\0').to_string());
                    dhcp_debug!("DEBUG: Bootfile: {:?}", bootfile_name);
                }
            }
            #[cfg(feature = "dhcp4-options")]
            69 => {
                // SMTP Servers
                let mut j = 0;
                while j + 4 <= length {
                    let addr = Ipv4Addr::new(
                        dhcp_msg[i + 2 + j], dhcp_msg[i + 3 + j],
                        dhcp_msg[i + 4 + j], dhcp_msg[i + 5 + j],
                    );
                    smtp_servers.push(addr);
                    j += 4;
                }
                dhcp_debug!("DEBUG: SMTP servers: {:?}", smtp_servers);
            }
            #[cfg(feature = "dhcp4-options")]
            70 => {
                // POP3 Servers
                let mut j = 0;
                while j + 4 <= length {
                    let addr = Ipv4Addr::new(
                        dhcp_msg[i + 2 + j], dhcp_msg[i + 3 + j],
                        dhcp_msg[i + 4 + j], dhcp_msg[i + 5 + j],
                    );
                    pop3_servers.push(addr);
                    j += 4;
                }
                dhcp_debug!("DEBUG: POP3 servers: {:?}", pop3_servers);
            }
            #[cfg(feature = "dhcp4-options")]
            71 => {
                // NNTP Servers
                let mut j = 0;
                while j + 4 <= length {
                    let addr = Ipv4Addr::new(
                        dhcp_msg[i + 2 + j], dhcp_msg[i + 3 + j],
                        dhcp_msg[i + 4 + j], dhcp_msg[i + 5 + j],
                    );
                    nntp_servers.push(addr);
                    j += 4;
                }
                dhcp_debug!("DEBUG: NNTP servers: {:?}", nntp_servers);
            }
            #[cfg(feature = "dhcp4-options")]
            72 => {
                // WWW Servers
                let mut j = 0;
                while j + 4 <= length {
                    let addr = Ipv4Addr::new(
                        dhcp_msg[i + 2 + j], dhcp_msg[i + 3 + j],
                        dhcp_msg[i + 4 + j], dhcp_msg[i + 5 + j],
                    );
                    www_servers.push(addr);
                    j += 4;
                }
                dhcp_debug!("DEBUG: WWW servers: {:?}", www_servers);
            }
            #[cfg(feature = "dhcp4-options")]
            77 => {
                // User Class
                user_class = Some(dhcp_msg[i + 2..i + 2 + length].to_vec());
                dhcp_debug!("DEBUG: User class: {:?}", user_class);
            }
            #[cfg(feature = "dhcp4-options")]
            81 => {
                // Client FQDN (RFC 4702)
                if length >= 3 {
                    let flags = dhcp_msg[i + 2];
                    let rcode1 = dhcp_msg[i + 3];
                    let rcode2 = dhcp_msg[i + 4];
                    let name = if length > 3 {
                        String::from_utf8_lossy(&dhcp_msg[i + 5..i + 2 + length])
                            .trim_end_matches('\0').to_string()
                    } else {
                        String::new()
                    };
                    client_fqdn = Some(ClientFqdn { flags, rcode1, rcode2, domain_name: name });
                    dhcp_debug!("DEBUG: Client FQDN: {:?}", client_fqdn);
                }
            }
            #[cfg(feature = "dhcp4-options")]
            95 => {
                // LDAP Servers (RFC 3679 - URLs)
                if let Ok(urls) = String::from_utf8(dhcp_msg[i + 2..i + 2 + length].to_vec()) {
                    ldap_servers = Some(urls);
                    dhcp_debug!("DEBUG: LDAP servers: {:?}", ldap_servers);
                }
            }
            #[cfg(feature = "dhcp4-options")]
            119 => {
                // Domain Search List (RFC 3397) - compressed DNS names
                domain_search = parse_domain_search(&dhcp_msg[i + 2..i + 2 + length]);
                dhcp_debug!("DEBUG: Domain search: {:?}", domain_search);
            }
            #[cfg(feature = "dhcp4-options")]
            121 => {
                // Classless Static Routes (RFC 3442)
                classless_routes = parse_classless_routes(&dhcp_msg[i + 2..i + 2 + length]);
                dhcp_debug!("DEBUG: Classless routes: {:?}", classless_routes);
            }
            _ => {
                dhcp_debug!("DEBUG: Skipping option {}, length {}", option, length);
            }
        }

        i += 2 + length;
    }

    // Extract required fields
    let lease_time = lease_time.ok_or_else(|| anyhow!("Lease time not found"))?;
    let server_id = server_id.ok_or_else(|| anyhow!("Server ID not found"))?;

    // Calculate default renewal and rebinding times if not provided (RFC 2131)
    let renewal_time = renewal_time.unwrap_or(lease_time / 2);
    let rebinding_time = rebinding_time.unwrap_or(lease_time * 7 / 8);

    dhcp_debug!("DEBUG: Final renewal time: {} seconds", renewal_time);
    dhcp_debug!("DEBUG: Final rebinding time: {} seconds", rebinding_time);

    Ok(DhcpLeaseInfo {
        ip_address,
        subnet_mask,
        router,
        dns_servers,
        domain_name,
        ntp_servers,
        lease_time,
        renewal_time: Some(renewal_time),
        rebinding_time: Some(rebinding_time),
        server_id,
        #[cfg(feature = "dhcp4-options")]
        nis_servers,
        #[cfg(feature = "dhcp4-options")]
        nisplus_domain,
        #[cfg(feature = "dhcp4-options")]
        tftp_server_name,
        #[cfg(feature = "dhcp4-options")]
        bootfile_name,
        #[cfg(feature = "dhcp4-options")]
        smtp_servers,
        #[cfg(feature = "dhcp4-options")]
        pop3_servers,
        #[cfg(feature = "dhcp4-options")]
        nntp_servers,
        #[cfg(feature = "dhcp4-options")]
        www_servers,
        #[cfg(feature = "dhcp4-options")]
        user_class,
        #[cfg(feature = "dhcp4-options")]
        client_fqdn,
        #[cfg(feature = "dhcp4-options")]
        ldap_servers,
        #[cfg(feature = "dhcp4-options")]
        domain_search,
        #[cfg(feature = "dhcp4-options")]
        classless_routes,
    })
}

/// Parse Domain Search List (Option 119, RFC 3397)
#[cfg(feature = "dhcp4-options")]
fn parse_domain_search(data: &[u8]) -> Vec<String> {
    let mut domains = Vec::new();
    let mut i = 0;

    while i < data.len() {
        let mut domain_parts = Vec::new();
        let mut j = i;

        while j < data.len() {
            let len = data[j] as usize;
            if len == 0 {
                j += 1;
                break;
            }
            if len >= 192 {
                // Compression pointer - skip for simplicity
                j += 2;
                break;
            }
            if j + 1 + len > data.len() {
                break;
            }
            if let Ok(label) = String::from_utf8(data[j + 1..j + 1 + len].to_vec()) {
                domain_parts.push(label);
            }
            j += 1 + len;
        }

        if !domain_parts.is_empty() {
            domains.push(domain_parts.join("."));
        }

        if j <= i {
            break;
        }
        i = j;
    }

    domains
}

/// Parse Classless Static Routes (Option 121, RFC 3442)
#[cfg(feature = "dhcp4-options")]
fn parse_classless_routes(data: &[u8]) -> Vec<ClasslessRoute> {
    let mut routes = Vec::new();
    let mut i = 0;

    while i < data.len() {
        if i >= data.len() {
            break;
        }

        let prefix_len = data[i];
        i += 1;

        // Calculate bytes needed for network address
        let addr_bytes = ((prefix_len + 7) / 8) as usize;

        if i + addr_bytes + 4 > data.len() {
            break;
        }

        // Build destination address (pad with zeros)
        let mut dest = [0u8; 4];
        for (j, byte) in data[i..i + addr_bytes].iter().enumerate() {
            if j < 4 {
                dest[j] = *byte;
            }
        }
        let destination = Ipv4Addr::from(dest);
        i += addr_bytes;

        // Gateway address
        let gateway = Ipv4Addr::new(data[i], data[i + 1], data[i + 2], data[i + 3]);
        i += 4;

        routes.push(ClasslessRoute {
            destination,
            prefix_len,
            gateway,
        });
    }

    routes
}

/// ARP operation codes
pub const ARP_OP_REQUEST: u16 = 1;
pub const ARP_OP_REPLY: u16 = 2;

/// Build ARP probe frame for duplicate address detection (RFC 5227)
///
/// An ARP probe has:
/// - Sender hardware address: our MAC
/// - Sender protocol address: 0.0.0.0 (we don't have an IP yet)
/// - Target hardware address: 00:00:00:00:00:00
/// - Target protocol address: the IP we want to probe
pub fn build_arp_probe_frame(
    src_mac: [u8; 6],
    target_ip: Ipv4Addr,
) -> Vec<u8> {
    dhcp_debug!("DEBUG: build_arp_probe_frame() called");
    dhcp_debug!("  Source MAC: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
           src_mac[0], src_mac[1], src_mac[2], src_mac[3], src_mac[4], src_mac[5]);
    dhcp_debug!("  Target IP: {}", target_ip);

    let mut frame = Vec::new();

    // Ethernet Header (14 bytes)
    frame.extend_from_slice(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);  // Dst MAC: broadcast
    frame.extend_from_slice(&src_mac);  // Src MAC
    frame.extend_from_slice(&[0x08, 0x06]);  // EtherType: ARP (0x0806)

    // ARP Header (28 bytes for IPv4 over Ethernet)
    frame.extend_from_slice(&1u16.to_be_bytes());  // Hardware type: Ethernet (1)
    frame.extend_from_slice(&0x0800u16.to_be_bytes());  // Protocol type: IPv4 (0x0800)
    frame.push(6);  // Hardware address length: 6 (MAC)
    frame.push(4);  // Protocol address length: 4 (IPv4)
    frame.extend_from_slice(&ARP_OP_REQUEST.to_be_bytes());  // Operation: ARP Request (1)

    // Sender hardware address (our MAC)
    frame.extend_from_slice(&src_mac);
    // Sender protocol address: 0.0.0.0 (RFC 5227 - ARP probe uses all zeros)
    frame.extend_from_slice(&[0, 0, 0, 0]);

    // Target hardware address: 00:00:00:00:00:00 (unknown)
    frame.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
    // Target protocol address: the IP we're probing
    frame.extend_from_slice(&target_ip.octets());

    dhcp_debug!("DEBUG: ARP probe frame built, size={} bytes", frame.len());
    frame
}

/// Create a raw socket for ARP (link layer)
pub fn create_arp_socket(interface: &str) -> Result<socket2::Socket> {
    dhcp_debug!("DEBUG: create_arp_socket() called for interface: {}", interface);

    // Get interface index
    let if_index = DhcpRawSocket::get_interface_index(interface)?;

    // Create AF_PACKET socket for ARP (ETH_P_ARP = 0x0806)
    let protocol = (0x0806u16).to_be() as i32;

    let socket_fd = unsafe {
        libc::socket(libc::AF_PACKET, libc::SOCK_RAW, protocol)
    };

    if socket_fd < 0 {
        let errno = unsafe { *libc::__errno_location() };
        return Err(anyhow!(
            "Failed to create ARP socket (errno={}). Requires CAP_NET_RAW or root privileges",
            errno
        ));
    }

    let socket = unsafe { socket2::Socket::from_raw_fd(socket_fd) };

    // Bind to specific interface
    let mut sll: libc::sockaddr_ll = unsafe { std::mem::zeroed() };
    sll.sll_family = libc::AF_PACKET as u16;
    sll.sll_protocol = protocol as u16;
    sll.sll_ifindex = if_index;

    let ret = unsafe {
        libc::bind(
            socket.as_raw_fd(),
            &sll as *const _ as *const libc::sockaddr,
            std::mem::size_of::<libc::sockaddr_ll>() as libc::socklen_t,
        )
    };

    if ret < 0 {
        let errno = unsafe { *libc::__errno_location() };
        return Err(anyhow!(
            "Failed to bind ARP socket to interface {} (errno={})",
            interface,
            errno
        ));
    }

    dhcp_debug!("DEBUG: ARP socket created and bound successfully");
    Ok(socket)
}

/// Perform ARP probe to check if an IP address is in use (RFC 5227)
///
/// Sends ARP probes and listens for replies. Returns true if the address
/// appears to be in use (conflict detected), false if it's available.
///
/// Parameters:
/// - interface: Network interface name
/// - src_mac: Our MAC address
/// - target_ip: The IP address to probe
/// - probe_count: Number of probes to send (RFC 5227 recommends 3)
/// - probe_wait_ms: Time to wait between probes in milliseconds
/// - timeout_ms: Total timeout for receiving replies
pub fn arp_probe_address(
    interface: &str,
    src_mac: [u8; 6],
    target_ip: Ipv4Addr,
    probe_count: u32,
    probe_wait_ms: u64,
    timeout_ms: u64,
) -> Result<bool> {
    dhcp_info!("ARP probing {} on interface {} ({} probes)", target_ip, interface, probe_count);

    let socket = create_arp_socket(interface)?;

    // Build probe frame
    let probe_frame = build_arp_probe_frame(src_mac, target_ip);

    // Send probes
    for i in 0..probe_count {
        dhcp_debug!("DEBUG: Sending ARP probe {}/{} for {}", i + 1, probe_count, target_ip);

        let _sent = socket.send(&probe_frame)
            .map_err(|e| anyhow!("Failed to send ARP probe: {}", e))?;

        dhcp_debug!("DEBUG: ARP probe sent ({} bytes)", _sent);

        // Wait between probes (except after the last one)
        if i < probe_count - 1 {
            std::thread::sleep(Duration::from_millis(probe_wait_ms));
        }
    }

    // Listen for ARP replies
    dhcp_info!("Listening for ARP replies (timeout: {}ms)", timeout_ms);

    socket.set_read_timeout(Some(Duration::from_millis(timeout_ms)))
        .map_err(|e| anyhow!("Failed to set socket timeout: {}", e))?;

    let mut buf = [0u8; 64];  // ARP frames are small (42 bytes typical)
    let start = std::time::Instant::now();
    let timeout = Duration::from_millis(timeout_ms);

    while start.elapsed() < timeout {
        // Use MaybeUninit for recv_from
        let mut uninit_buf = vec![MaybeUninit::<u8>::uninit(); buf.len()];

        match socket.recv_from(&mut uninit_buf) {
            Ok((size, _)) => {
                // Copy to regular buffer
                for (i, byte) in uninit_buf.iter().take(size).enumerate() {
                    unsafe { buf[i] = byte.assume_init(); }
                }

                dhcp_debug!("DEBUG: Received packet ({} bytes)", size);

                // Parse ARP reply
                if let Some(conflict) = parse_arp_reply(&buf[..size], src_mac, target_ip) {
                    if conflict {
                        dhcp_info!("ARP conflict detected! IP {} is already in use", target_ip);
                        return Ok(true);  // Conflict detected
                    }
                }
            }
            Err(e) => {
                if e.kind() == std::io::ErrorKind::WouldBlock ||
                   e.kind() == std::io::ErrorKind::TimedOut {
                    // Timeout, no more packets
                    break;
                }
                dhcp_debug!("DEBUG: ARP recv error: {}", e);
            }
        }
    }

    dhcp_info!("No ARP conflict detected for {}", target_ip);
    Ok(false)  // No conflict
}

/// Parse ARP reply to check for address conflict
///
/// Returns Some(true) if conflict detected, Some(false) if reply but no conflict,
/// None if not a relevant ARP packet
fn parse_arp_reply(packet: &[u8], our_mac: [u8; 6], target_ip: Ipv4Addr) -> Option<bool> {
    // Minimum ARP frame: 14 (Ethernet) + 28 (ARP) = 42 bytes
    if packet.len() < 42 {
        return None;
    }

    // Check EtherType is ARP (0x0806)
    if packet[12] != 0x08 || packet[13] != 0x06 {
        return None;
    }

    // ARP header starts at offset 14
    let arp = &packet[14..];

    // Check hardware type (Ethernet = 1) and protocol type (IPv4 = 0x0800)
    if arp[0] != 0x00 || arp[1] != 0x01 || arp[2] != 0x08 || arp[3] != 0x00 {
        return None;
    }

    // Check hardware/protocol address lengths
    if arp[4] != 6 || arp[5] != 4 {
        return None;
    }

    // Get operation (offset 6-7)
    let _operation = u16::from_be_bytes([arp[6], arp[7]]);

    // Sender MAC (offset 8-13)
    let sender_mac: [u8; 6] = [arp[8], arp[9], arp[10], arp[11], arp[12], arp[13]];

    // Sender IP (offset 14-17)
    let sender_ip = Ipv4Addr::new(arp[14], arp[15], arp[16], arp[17]);

    dhcp_debug!("DEBUG: ARP packet - op={}, sender_mac={:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}, sender_ip={}",
           _operation, sender_mac[0], sender_mac[1], sender_mac[2],
           sender_mac[3], sender_mac[4], sender_mac[5], sender_ip);

    // Check for conflict:
    // 1. ARP Reply (op=2) with sender IP matching our target
    // 2. ARP Request (op=1) with sender IP matching our target (another host is probing/using it)
    // Exclude our own packets
    if sender_mac == our_mac {
        dhcp_debug!("DEBUG: Ignoring our own ARP packet");
        return Some(false);
    }

    if sender_ip == target_ip {
        dhcp_info!("ARP conflict: {} is being used by {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
              sender_ip, sender_mac[0], sender_mac[1], sender_mac[2],
              sender_mac[3], sender_mac[4], sender_mac[5]);
        return Some(true);  // Conflict!
    }

    Some(false)
}

/// Calculate IP checksum (RFC 1071)
fn calculate_checksum(data: &[u8]) -> u16 {
    let mut sum: u32 = 0;
    let mut i = 0;

    // Sum all 16-bit words
    while i < data.len() - 1 {
        let word = u16::from_be_bytes([data[i], data[i + 1]]) as u32;
        sum += word;
        i += 2;
    }

    // Add remaining byte if odd length
    if i < data.len() {
        sum += (data[i] as u32) << 8;
    }

    // Fold 32-bit sum to 16 bits
    while (sum >> 16) != 0 {
        sum = (sum & 0xFFFF) + (sum >> 16);
    }

    // One's complement
    !sum as u16
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg(feature = "dhcp4-options")]
    fn test_parse_domain_search() {
        // Test compressed domain name format (RFC 1035)
        // "example.com" = 7example3com0
        let data = vec![
            7, b'e', b'x', b'a', b'm', b'p', b'l', b'e',
            3, b'c', b'o', b'm', 0,
            4, b't', b'e', b's', b't',
            3, b'o', b'r', b'g', 0
        ];
        let domains = parse_domain_search(&data);
        assert_eq!(domains.len(), 2);
        assert_eq!(domains[0], "example.com");
        assert_eq!(domains[1], "test.org");
    }

    #[test]
    #[cfg(feature = "dhcp4-options")]
    fn test_parse_classless_routes() {
        // Test RFC 3442 classless static routes
        // Route 1: 10.0.0.0/8 via 192.168.1.1
        // Route 2: 192.168.0.0/16 via 192.168.1.254
        let data = vec![
            8,                              // prefix length /8
            10,                             // destination (1 octet for /8)
            192, 168, 1, 1,                 // gateway
            16,                             // prefix length /16
            192, 168,                       // destination (2 octets for /16)
            192, 168, 1, 254,               // gateway
        ];
        let routes = parse_classless_routes(&data);
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].prefix_len, 8);
        assert_eq!(routes[0].destination, Ipv4Addr::new(10, 0, 0, 0));
        assert_eq!(routes[0].gateway, Ipv4Addr::new(192, 168, 1, 1));
        assert_eq!(routes[1].prefix_len, 16);
        assert_eq!(routes[1].destination, Ipv4Addr::new(192, 168, 0, 0));
        assert_eq!(routes[1].gateway, Ipv4Addr::new(192, 168, 1, 254));
    }

    #[test]
    #[cfg(feature = "dhcp4-options")]
    fn test_client_fqdn_struct() {
        let fqdn = ClientFqdn {
            flags: 0x01,  // S bit set
            rcode1: 0,
            rcode2: 0,
            domain_name: "host.example.com".to_string(),
        };
        assert_eq!(fqdn.flags, 0x01);
        assert_eq!(fqdn.domain_name, "host.example.com");
    }

    #[test]
    #[cfg(feature = "dhcp4-options")]
    fn test_classless_route_struct() {
        let route = ClasslessRoute {
            destination: Ipv4Addr::new(10, 0, 0, 0),
            prefix_len: 8,
            gateway: Ipv4Addr::new(192, 168, 1, 1),
        };
        assert_eq!(route.prefix_len, 8);
        assert_eq!(route.destination, Ipv4Addr::new(10, 0, 0, 0));
        assert_eq!(route.gateway, Ipv4Addr::new(192, 168, 1, 1));
    }

    #[test]
    #[cfg(feature = "dhcp4-options")]
    fn test_extended_parameter_request_list() {
        let mac = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55];
        let xid = 0x12345678;
        let frame = build_dhcp_discover_link_frame(mac, xid, None);

        // Find Option 55 (Parameter Request List) in the frame
        // Skip Ethernet (14) + IP (20) + UDP (8) = 42 bytes + BOOTP header (236) + magic (4)
        let dhcp_options_start = 42 + 236 + 4;
        let options = &frame[dhcp_options_start..];

        // Find option 55
        let mut i = 0;
        let mut found_opt55 = false;
        let mut opt55_len = 0;
        while i < options.len() {
            if options[i] == 255 { break; }  // End option
            if options[i] == 0 { i += 1; continue; }  // Pad option
            let opt_code = options[i];
            let opt_len = options[i + 1] as usize;
            if opt_code == 55 {
                found_opt55 = true;
                opt55_len = opt_len;
                break;
            }
            i += 2 + opt_len;
        }

        assert!(found_opt55, "Option 55 not found");
        assert_eq!(opt55_len, 18, "Extended options should have 18 parameters");
    }

    #[test]
    fn test_checksum() {
        // Test vector: simple IP header
        let data = vec![
            0x45, 0x00, 0x00, 0x3c, 0x1c, 0x46, 0x40, 0x00,
            0x40, 0x06, 0x00, 0x00, 0xac, 0x10, 0x0a, 0x63,
            0xac, 0x10, 0x0a, 0x0c
        ];
        let checksum = calculate_checksum(&data);
        assert!(checksum != 0);
    }

    #[test]
    fn test_dhcp_message_structure() {
        let mac = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55];
        let xid = 0x12345678;
        let msg = build_dhcp_message(mac, xid, Some("testhost"));

        // Check minimum size (236 bytes BOOTP + 4 magic + options)
        assert!(msg.len() >= 240);

        // Check op code
        assert_eq!(msg[0], 0x01);  // BOOTREQUEST

        // Check magic cookie at offset 236
        assert_eq!(&msg[236..240], &[0x63, 0x82, 0x53, 0x63]);
    }

    #[test]
    fn test_ip_packet_structure() {
        let mac = [0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff];
        let xid = 0xabcdef01;
        let packet = build_dhcp_discover_ip_packet(mac, xid, None);

        // Check IP version and IHL
        assert_eq!(packet[0], 0x45);

        // Check protocol (UDP = 17)
        assert_eq!(packet[9], 17);

        // Check source IP (0.0.0.0)
        assert_eq!(&packet[12..16], &[0, 0, 0, 0]);

        // Check destination IP (255.255.255.255)
        assert_eq!(&packet[16..20], &[255, 255, 255, 255]);
    }

    #[test]
    fn test_link_frame_structure() {
        let mac = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
        let xid = 0x99887766;
        let frame = build_dhcp_discover_link_frame(mac, xid, None);

        // Check Ethernet header
        assert_eq!(&frame[0..6], &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);  // Dst MAC
        assert_eq!(&frame[6..12], &mac);  // Src MAC
        assert_eq!(&frame[12..14], &[0x08, 0x00]);  // EtherType

        // Check IP version at offset 14
        assert_eq!(frame[14], 0x45);
    }
}