tun-rs 2.8.8

Cross-platform TUN and TAP library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
#![allow(unused_imports)]
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

use pnet_packet::ip::IpNextHeaderProtocols;
use pnet_packet::Packet;
#[cfg(any(
    target_os = "windows",
    target_os = "macos",
    all(target_os = "linux", not(target_env = "ohos")),
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
))]
use tun_rs::DeviceBuilder;
use tun_rs::SyncDevice;

#[cfg(any(
    target_os = "windows",
    target_os = "macos",
    all(target_os = "linux", not(target_env = "ohos")),
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
))]
#[cfg(not(any(feature = "async_tokio", feature = "async_io")))]
#[test]
fn test_udp_v4() {
    let test_msg = "test udp";
    let device = DeviceBuilder::new()
        .ipv4("10.26.1.100", 24, None)
        .build_sync()
        .unwrap();
    let device = Arc::new(device);
    let _device = device.clone();
    let test_udp_v4 = Arc::new(AtomicBool::new(false));
    let test_udp_v4_c = test_udp_v4.clone();
    let recv_flag = Arc::new(AtomicBool::new(false));
    let recv_flag_c = recv_flag.clone();
    std::thread::spawn(move || {
        let mut buf = [0; 65535];
        loop {
            let len = device.recv(&mut buf).unwrap();
            if let Some(ipv4_packet) = pnet_packet::ipv4::Ipv4Packet::new(&buf[..len]) {
                if ipv4_packet.get_next_level_protocol() == IpNextHeaderProtocols::Udp {
                    if let Some(udp_packet) =
                        pnet_packet::udp::UdpPacket::new(ipv4_packet.payload())
                    {
                        if udp_packet.payload() == test_msg.as_bytes() {
                            test_udp_v4.store(true, Ordering::Relaxed);
                        }
                    }
                }
            }
            if test_udp_v4.load(Ordering::Relaxed) {
                recv_flag.store(true, Ordering::Release);
                break;
            }
        }
    });
    std::thread::sleep(Duration::from_secs(6));
    let udp_socket = std::net::UdpSocket::bind("10.26.1.100:0").unwrap();
    udp_socket
        .send_to(test_msg.as_bytes(), "10.26.1.101:8080")
        .unwrap();
    let time_now = std::time::Instant::now();
    // check whether the thread completes
    while !recv_flag_c.load(Ordering::Acquire) {
        if time_now.elapsed().as_secs() > 2 {
            // no promise due to the timeout
            let v4 = test_udp_v4_c.load(Ordering::Relaxed);
            assert!(v4, "timeout: test_udp_v4 = {v4}");
            return;
        }
    }
    // recv_flag_c == true
    // all modifications to test_udp_v4_c must be visible
    let v4 = test_udp_v4_c.load(Ordering::Relaxed);
    assert!(v4);
}

#[cfg(any(
    target_os = "windows",
    target_os = "macos",
    all(target_os = "linux", not(target_env = "ohos")),
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
))]
#[cfg(not(any(feature = "async_tokio", feature = "async_io")))]
#[test]
fn test_udp_v6() {
    let test_msg = "test udp";
    let device = DeviceBuilder::new()
        .ipv6("fd12:3456:789a:1111:2222:3333:4444:5555", 64)
        .build_sync()
        .unwrap();
    let device = Arc::new(device);
    let _device = device.clone();
    let test_udp_v6 = Arc::new(AtomicBool::new(false));
    let test_udp_v6_c = test_udp_v6.clone();
    let recv_flag = Arc::new(AtomicBool::new(false));
    let recv_flag_c = recv_flag.clone();
    std::thread::spawn(move || {
        let mut buf = [0; 65535];
        loop {
            let len = device.recv(&mut buf).unwrap();
            if let Some(ipv6_packet) = pnet_packet::ipv6::Ipv6Packet::new(&buf[..len]) {
                if ipv6_packet.get_next_header() == IpNextHeaderProtocols::Udp {
                    if let Some(udp_packet) =
                        pnet_packet::udp::UdpPacket::new(ipv6_packet.payload())
                    {
                        if udp_packet.payload() == test_msg.as_bytes() {
                            test_udp_v6.store(true, Ordering::Relaxed);
                        }
                    }
                }
            }
            if test_udp_v6.load(Ordering::Relaxed) {
                recv_flag.store(true, Ordering::Release);
                break;
            }
        }
    });
    std::thread::sleep(Duration::from_secs(6));
    let udp_socket =
        std::net::UdpSocket::bind("[fd12:3456:789a:1111:2222:3333:4444:5555]:0").unwrap();
    udp_socket
        .send_to(
            test_msg.as_bytes(),
            "[fd12:3456:789a:1111:2222:3333:4444:5556]:8080",
        )
        .unwrap();
    let time_now = std::time::Instant::now();
    // check whether the thread completes
    while !recv_flag_c.load(Ordering::Acquire) {
        if time_now.elapsed().as_secs() > 2 {
            // no promise due to the timeout
            let v6 = test_udp_v6_c.load(Ordering::Relaxed);
            assert!(v6, "timeout: test_udp_v6 = {v6}");
            return;
        }
    }
    // recv_flag_c == true
    // all modifications to test_udp_v6_c must be visible
    let v6 = test_udp_v6_c.load(Ordering::Relaxed);
    assert!(v6);
}
#[cfg(any(
    target_os = "windows",
    target_os = "macos",
    all(target_os = "linux", not(target_env = "ohos")),
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
))]
#[cfg(feature = "async_tokio")]
#[tokio::test]
async fn test_udp_v4() {
    let test_msg = "test udp";
    let device = DeviceBuilder::new()
        .ipv4("10.26.1.100", 24, None)
        .build_async()
        .unwrap();

    let device = Arc::new(device);
    let _device = device.clone();
    let test_udp_v4 = Arc::new(AtomicBool::new(false));
    let test_udp_v4_c = test_udp_v4.clone();
    let recv_flag = Arc::new(AtomicBool::new(false));
    let recv_flag_c = recv_flag.clone();
    let handler = tokio::spawn(async move {
        let mut buf = [0; 65535];
        loop {
            let len = device.recv(&mut buf).await.unwrap();
            if let Some(ipv4_packet) = pnet_packet::ipv4::Ipv4Packet::new(&buf[..len]) {
                if ipv4_packet.get_next_level_protocol() == IpNextHeaderProtocols::Udp {
                    if let Some(udp_packet) =
                        pnet_packet::udp::UdpPacket::new(ipv4_packet.payload())
                    {
                        if udp_packet.payload() == test_msg.as_bytes() {
                            test_udp_v4.store(true, Ordering::Relaxed);
                        }
                    }
                }
            }
            if test_udp_v4.load(Ordering::Relaxed) {
                recv_flag.store(true, Ordering::Release);
                break;
            }
        }
    });
    tokio::time::sleep(Duration::from_secs(6)).await;

    let udp_socket = tokio::net::UdpSocket::bind("10.26.1.200:0").await.unwrap();
    udp_socket
        .send_to(test_msg.as_bytes(), "10.26.1.101:8080")
        .await
        .unwrap();
    tokio::select! {
        _=tokio::time::sleep(Duration::from_secs(2))=>{
            // no promise due to the timeout
            let v4 = test_udp_v4_c.load(Ordering::Relaxed);
            assert!(v4, "timeout: test_udp_v4 = {v4}");
        }
        _=handler=>{
            // all modifications to test_udp_v4_c and test_udp_v6_c must be visible
            let flag = recv_flag_c.load(Ordering::Acquire); //synchronize
            assert!(flag, "recv_flag = {flag}");
            let v4 = test_udp_v4_c.load(Ordering::Relaxed);
            assert!(v4);
        }
    }
}
#[cfg(any(
    target_os = "windows",
    target_os = "macos",
    all(target_os = "linux", not(target_env = "ohos")),
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
))]
#[cfg(feature = "async_tokio")]
#[tokio::test]
async fn test_udp_v6() {
    let test_msg = "test udp";
    let device = DeviceBuilder::new()
        .ipv6("fd12:3456:789a:1111:2222:3333:4444:5555", 64)
        .build_async()
        .unwrap();

    let device = Arc::new(device);
    let _device = device.clone();
    let test_udp_v6 = Arc::new(AtomicBool::new(false));
    let test_udp_v6_c = test_udp_v6.clone();
    let recv_flag = Arc::new(AtomicBool::new(false));
    let recv_flag_c = recv_flag.clone();
    let handler = tokio::spawn(async move {
        let mut buf = [0; 65535];
        loop {
            let len = device.recv(&mut buf).await.unwrap();
            if let Some(ipv6_packet) = pnet_packet::ipv6::Ipv6Packet::new(&buf[..len]) {
                if ipv6_packet.get_next_header() == IpNextHeaderProtocols::Udp {
                    if let Some(udp_packet) =
                        pnet_packet::udp::UdpPacket::new(ipv6_packet.payload())
                    {
                        if udp_packet.payload() == test_msg.as_bytes() {
                            test_udp_v6.store(true, Ordering::Relaxed);
                        }
                    }
                }
            }

            if test_udp_v6.load(Ordering::Relaxed) {
                recv_flag.store(true, Ordering::Release);
                break;
            }
        }
    });
    tokio::time::sleep(Duration::from_secs(6)).await;
    let udp_socket = tokio::net::UdpSocket::bind("[fd12:3456:789a:1111:2222:3333:4444:5555]:0")
        .await
        .unwrap();
    udp_socket
        .send_to(
            test_msg.as_bytes(),
            "[fd12:3456:789a:1111:2222:3333:4444:5556]:8080",
        )
        .await
        .unwrap();

    tokio::select! {
        _=tokio::time::sleep(Duration::from_secs(2))=>{
            // no promise due to the timeout
            let v6 = test_udp_v6_c.load(Ordering::Relaxed);
            assert!(v6, "timeout: test_udp_v6 = {v6}");
        }
        _=handler=>{
            // all modifications to test_udp_v4_c and test_udp_v6_c must be visible
            let flag = recv_flag_c.load(Ordering::Acquire); //synchronize
            assert!(flag, "recv_flag = {flag}");
            let v6 = test_udp_v6_c.load(Ordering::Relaxed);
            assert!(v6 );
        }
    }
}

#[cfg(any(
    target_os = "windows",
    target_os = "macos",
    all(target_os = "linux", not(target_env = "ohos")),
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
))]
#[test]
fn test_op() {
    let device = DeviceBuilder::new()
        .ipv4("10.26.2.100", 24, None)
        .ipv6("fd12:3456:789a:5555:2222:3333:4444:5555", 120)
        .build_sync()
        .unwrap();

    #[cfg(any(target_os = "macos", target_os = "openbsd"))]
    device.set_ignore_packet_info(true);
    #[cfg(any(target_os = "macos", target_os = "openbsd"))]
    assert!(device.ignore_packet_info());

    device.set_mtu(1500).unwrap();
    assert_eq!(device.mtu().unwrap(), 1500);

    #[cfg(target_os = "macos")]
    device.set_associate_route(true);
    #[cfg(target_os = "macos")]
    assert!(device.associate_route());

    let vec = device.addresses().unwrap();
    assert!(vec
        .iter()
        .any(|ip| *ip == "10.26.2.100".parse::<std::net::Ipv4Addr>().unwrap()));
    assert!(vec.iter().any(|ip| *ip

        == "fd12:3456:789a:5555:2222:3333:4444:5555"
            .parse::<std::net::Ipv6Addr>()
            .unwrap()));

    device.set_network_address("10.26.3.200", 24, None).unwrap();
    let vec = device.addresses().unwrap();
    assert!(vec
        .iter()
        .any(|ip| *ip == "10.26.3.200".parse::<std::net::Ipv4Addr>().unwrap()));
    assert!(vec.iter().any(|ip| *ip

        == "fd12:3456:789a:5555:2222:3333:4444:5555"
            .parse::<std::net::Ipv6Addr>()
            .unwrap()));
    assert!(!vec.contains(&"10.26.2.100".parse::<std::net::IpAddr>().unwrap()));

    device.add_address_v4("10.6.0.1", 24).unwrap();
    let vec = device.addresses().unwrap();
    assert!(vec.contains(&"10.6.0.1".parse::<std::net::IpAddr>().unwrap()));
    assert!(vec.contains(&"10.26.3.200".parse::<std::net::IpAddr>().unwrap()));

    device
        .remove_address("10.6.0.1".parse::<std::net::IpAddr>().unwrap())
        .unwrap();
    let vec = device.addresses().unwrap();
    assert!(!vec.contains(&"10.6.0.1".parse::<std::net::IpAddr>().unwrap()));
    assert!(vec.contains(&"10.26.3.200".parse::<std::net::IpAddr>().unwrap()));

    device
        .add_address_v6("fdab:cdef:1234:5678:9abc:def0:1234:5678", 64)
        .unwrap();
    let vec = device.addresses().unwrap();
    assert!(vec.contains(
        &"fdab:cdef:1234:5678:9abc:def0:1234:5678"
            .parse::<std::net::IpAddr>()
            .unwrap()
    ));

    device.enabled(true).unwrap();

    #[cfg(any(
        target_os = "windows",
        all(target_os = "linux", not(target_env = "ohos"))
    ))]
    device.set_name("tun66").unwrap();
    std::thread::sleep(Duration::from_secs(3));

    #[cfg(any(
        target_os = "windows",
        all(target_os = "linux", not(target_env = "ohos"))
    ))]
    assert_eq!(device.name().unwrap(), "tun66");

    assert!(device.if_index().is_ok());

    // Windows-only configuration that was migrated from netsh/wmic commands to
    // windows-sys APIs. None of these expose a public read-back getter, so we assert
    // that the configure path succeeds: a malformed FFI call (wrong struct layout,
    // flags, GUID conversion, or a failed dynamic load) returns an error and fails here.
    #[cfg(target_os = "windows")]
    {
        // `if_luid()` is exposed for downstream crates; it must resolve to a LUID.
        assert!(device.if_luid().is_ok());

        // `set_metric` -> Get/SetIpInterfaceEntry.
        device
            .set_metric(100)
            .expect("set_metric(100) should succeed");

        // `set_dns_servers` -> SetInterfaceDnsSettings (resolved at run time) with a
        // netsh fallback. Exercise IPv4 (primary + secondary) and IPv6, then clear both.
        let v4_dns: [std::net::IpAddr; 2] =
            ["8.8.8.8".parse().unwrap(), "8.8.4.4".parse().unwrap()];
        device.set_dns_servers(&v4_dns).unwrap();
        let v6_dns: [std::net::IpAddr; 1] = ["2001:4860:4860::8888".parse().unwrap()];
        device.set_dns_servers(&v6_dns).unwrap();
        device.clear_dns_servers(true).unwrap();
        device.clear_dns_servers(false).unwrap();
    }

    #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
    assert!(device.is_running().unwrap());
}

#[cfg(any(
    target_os = "windows",
    target_os = "macos",
    all(target_os = "linux", not(target_env = "ohos")),
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
))]
#[test]
fn create_tun() {
    #[cfg(not(target_os = "macos"))]
    let name = "tun12";
    #[cfg(target_os = "macos")]
    let name = "utun12";

    let device = DeviceBuilder::new().name(name).build_sync().unwrap();
    let dev_name = device.name().unwrap();
    assert_eq!(dev_name.as_str(), name);
    #[cfg(unix)]
    {
        use std::os::fd::IntoRawFd;
        let fd = device.into_raw_fd();
        unsafe {
            let sync_device = SyncDevice::from_fd(fd).unwrap();
            let dev_name = sync_device.name().unwrap();
            assert_eq!(dev_name, name);
        }
    }
}

#[cfg(any(
    target_os = "windows",
    target_os = "macos",
    all(target_os = "linux", not(target_env = "ohos")),
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
))]
#[test]
fn create_tap() {
    #[cfg(not(target_os = "macos"))]
    let name = "tap12";
    #[cfg(target_os = "macos")]
    let name = "feth12";

    let device = DeviceBuilder::new()
        .name(name)
        .layer(tun_rs::Layer::L2)
        .build_sync()
        .unwrap();
    let dev_name = device.name().unwrap();
    assert_eq!(dev_name.as_str(), name);
    #[cfg(all(unix, not(target_os = "macos")))]
    {
        use std::os::fd::IntoRawFd;
        let fd = device.into_raw_fd();
        unsafe {
            let sync_device = SyncDevice::from_fd(fd).unwrap();
            let dev_name = sync_device.name().unwrap();
            assert_eq!(dev_name, name);
        }
    }
}

/// Dedicated Windows test covering every public API migrated from netsh/wmic to
/// windows-sys in PR `#140`.  Each section is labelled with the underlying Windows
/// API that was newly wired up.
#[cfg(target_os = "windows")]
#[test]
fn test_windows_new_apis() {
    use std::net::IpAddr;
    use tun_rs::DeviceBuilder;

    let device = DeviceBuilder::new()
        .ipv4("10.26.9.100", 24, None)
        .ipv6("fd12:3456:789a:9999:2222:3333:4444:5555", 64)
        .build_sync()
        .unwrap();

    // ── 1. if_luid() ─────────────────────────────────────────────────────────
    // New public API; a valid adapter LUID is never zero.
    let luid = device.if_luid().expect("if_luid() should succeed");
    let luid_value = unsafe { luid.Value };
    assert_ne!(luid_value, 0, "LUID must be non-zero for a live adapter");

    // ── 2. set_metric() ──────────────────────────────────────────────────────
    // Now uses GetIpInterfaceEntry / SetIpInterfaceEntry for both AF_INET and
    // AF_INET6.  No public read-back getter exists, so we assert the call
    // succeeds for two different values (exercises the full round-trip twice).
    device
        .set_metric(50)
        .expect("set_metric(50) should succeed");
    device
        .set_metric(100)
        .expect("set_metric(100) should succeed");

    // ── 3. set_mtu / mtu (IPv4) ──────────────────────────────────────────────
    // Now uses SetIpInterfaceEntry with NlMtu; read back via GetIpInterfaceTable.
    device.set_mtu(1400).expect("set_mtu(1400) should succeed");
    assert_eq!(
        device.mtu().expect("mtu() should succeed"),
        1400,
        "mtu() read-back should match the value written by set_mtu()"
    );

    // ── 4. set_mtu_v6 / mtu_v6 (IPv6) ───────────────────────────────────────
    // Same path but with is_v4=false; mtu_v6() reads back via GetIpInterfaceTable
    // with AF_INET6.
    device
        .set_mtu_v6(1380)
        .expect("set_mtu_v6(1380) should succeed");
    assert_eq!(
        device.mtu_v6().expect("mtu_v6() should succeed"),
        1380,
        "mtu_v6() read-back should match the value written by set_mtu_v6()"
    );

    // ── 5. set_network_address without gateway ───────────────────────────────
    // ffi::set_address clears all existing IPv4 unicast addresses and installs
    // the new one.  The old address must disappear.
    device
        .set_network_address("10.26.9.200", 24, None)
        .expect("set_network_address (no gateway) should succeed");
    let addrs = device.addresses().unwrap();
    assert!(
        addrs.contains(&"10.26.9.200".parse::<IpAddr>().unwrap()),
        "new address 10.26.9.200 should be present after set_network_address"
    );
    assert!(
        !addrs.contains(&"10.26.9.100".parse::<IpAddr>().unwrap()),
        "old address 10.26.9.100 should have been removed by set_network_address"
    );

    // ── 6. set_network_address WITH gateway ──────────────────────────────────
    // Exercises the default-route creation path in ffi::add_address that was
    // specifically fixed in this PR (DestinationPrefix address family +
    // SitePrefixLength=0 for CreateIpForwardEntry2).
    device
        .set_network_address("10.26.9.150", 24, Some("10.26.9.1"))
        .expect("set_network_address with gateway should succeed");
    let addrs = device.addresses().unwrap();
    assert!(
        addrs.contains(&"10.26.9.150".parse::<IpAddr>().unwrap()),
        "address 10.26.9.150 should be present after set_network_address with gateway"
    );
    assert!(
        !addrs.contains(&"10.26.9.200".parse::<IpAddr>().unwrap()),
        "previous address 10.26.9.200 should have been cleared"
    );

    // ── 7. add_address_v6 ────────────────────────────────────────────────────
    // ffi::add_address with None gateway; verifies the address appears in the
    // interface's address list.
    device
        .add_address_v6("fdab:cdef:1234:5678:9abc:def0:1234:0001", 64)
        .expect("add_address_v6 should succeed");
    let addrs = device.addresses().unwrap();
    assert!(
        addrs.contains(
            &"fdab:cdef:1234:5678:9abc:def0:1234:0001"
                .parse::<IpAddr>()
                .unwrap()
        ),
        "IPv6 address should be present after add_address_v6"
    );

    // ── 8. remove_address (IPv6) ─────────────────────────────────────────────
    // ffi::remove_address; confirms the address is gone after deletion.
    device
        .remove_address(
            "fdab:cdef:1234:5678:9abc:def0:1234:0001"
                .parse::<IpAddr>()
                .unwrap(),
        )
        .expect("remove_address (IPv6) should succeed");
    let addrs = device.addresses().unwrap();
    assert!(
        !addrs.contains(
            &"fdab:cdef:1234:5678:9abc:def0:1234:0001"
                .parse::<IpAddr>()
                .unwrap()
        ),
        "IPv6 address should be absent after remove_address"
    );

    // ── 9. set_dns_servers (IPv4) ────────────────────────────────────────────
    // dns::set_dns_servers → SetInterfaceDnsSettings (or netsh fallback).
    let ipv4_dns: &[IpAddr] = &["8.8.8.8".parse().unwrap(), "8.8.4.4".parse().unwrap()];
    device
        .set_dns_servers(ipv4_dns)
        .expect("set_dns_servers (IPv4 primary+secondary) should succeed");

    // ── 10. set_dns_servers (IPv6) ───────────────────────────────────────────
    let ipv6_dns: &[IpAddr] = &["2001:4860:4860::8888".parse().unwrap()];
    device
        .set_dns_servers(ipv6_dns)
        .expect("set_dns_servers (IPv6) should succeed");

    // ── 11. set_dns_servers — validation: empty list must be rejected ────────
    assert!(
        device.set_dns_servers(&[]).is_err(),
        "set_dns_servers with an empty slice must return Err (InvalidInput)"
    );

    // ── 12. set_dns_servers — validation: mixed families must be rejected ────
    let mixed: &[IpAddr] = &[
        "8.8.8.8".parse().unwrap(),
        "2001:4860:4860::8888".parse().unwrap(),
    ];
    assert!(
        device.set_dns_servers(mixed).is_err(),
        "set_dns_servers with mixed IPv4/IPv6 addresses must return Err (InvalidInput)"
    );

    // ── 13. clear_dns_servers ────────────────────────────────────────────────
    // dns::clear_dns_servers → SetInterfaceDnsSettings with empty NameServer
    // (or netsh fallback).
    device
        .clear_dns_servers(true)
        .expect("clear_dns_servers (IPv4) should succeed");
    device
        .clear_dns_servers(false)
        .expect("clear_dns_servers (IPv6) should succeed");
}

/// Regression test for the device-wide TUN_F_* offload mask not being
/// cleared on attach with `offload=false`.
///
/// The kernel keeps `tun->set_features` (TSO/HW_CSUM/etc.) state per
/// device, not per fd. When a persistent TUN is first attached with
/// `offload=true`, the kernel raises these features. A later attach with
/// `offload=false` correctly omits IFF_VNET_HDR on the new tfile, but if
/// the device-wide mask is not reset, the kernel still treats the device
/// as offload-capable and delivers GSO aggregates that the new (offload-
/// unaware) caller misinterprets as oversized single packets. The fix is
/// to issue `TUNSETOFFLOAD(0)` in the offload=false branch of
/// `DeviceImpl::new`.
///
/// Marked `#[ignore]`: requires `CAP_NET_ADMIN` (root) and `ethtool` in
/// PATH; creates and deletes a persistent TUN device named `tunoffldclr`.
/// Run with:
///   cargo test --test test_dev -- --ignored offload_mask_cleared
#[cfg(all(target_os = "linux", not(target_env = "ohos")))]
#[cfg(not(any(feature = "async_tokio", feature = "async_io")))]
#[test]
#[ignore]
fn test_offload_mask_cleared_on_reattach_without_offload() {
    use std::process::Command;

    const NAME: &str = "tunoffldclr";

    // Parse `ethtool -k <name>` output for a single feature flag's state.
    // Lines look like:
    //   tx-tcp-segmentation: on
    //   tx-checksum-ip-generic: off
    fn ethtool_feature(name: &str, feature: &str) -> bool {
        let output = Command::new("ethtool")
            .args(["-k", name])
            .output()
            .expect("run ethtool -k");
        assert!(
            output.status.success(),
            "ethtool -k {name} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            let trimmed = line.trim();
            if let Some(rest) = trimmed.strip_prefix(feature) {
                if let Some(value) = rest.strip_prefix(':') {
                    let value = value.trim();
                    if value.starts_with("on") {
                        return true;
                    }
                    if value.starts_with("off") {
                        return false;
                    }
                }
            }
        }
        panic!("feature `{feature}` not found in `ethtool -k {name}` output:\n{stdout}");
    }

    // Clean any leftover device from a previous failed run. Ignore errors.
    let _ = Command::new("ip").args(["link", "delete", NAME]).status();

    // ── Attach #1: offload=true, persisted ──────────────────────────────
    // Raises the device-wide TUN_F_* mask via TUNSETOFFLOAD.
    let dev1 = DeviceBuilder::new()
        .name(NAME)
        .offload(true)
        .build_sync()
        .expect("attach #1 with offload=true");
    dev1.persist().expect("set TUNSETPERSIST");

    // Sanity check: the features set by TUN_F_CSUM | TUN_F_TSO4 |
    // TUN_F_TSO6 should be visible to ethtool.
    let tso_after_offload = ethtool_feature(NAME, "tx-tcp-segmentation");
    let csum_after_offload = ethtool_feature(NAME, "tx-checksum-ip-generic");

    // Drop attach #1. The device persists; tun->set_features is unchanged.
    drop(dev1);

    // ── Attach #2: offload=false ────────────────────────────────────────
    // With the fix in DeviceImpl::new, TUNSETOFFLOAD(0) clears the mask.
    // Without the fix, ethtool still reports TSO/HW_CSUM on.
    let dev2 = DeviceBuilder::new()
        .name(NAME)
        .offload(false)
        .build_sync()
        .expect("attach #2 with offload=false");

    let tso_after_clear = ethtool_feature(NAME, "tx-tcp-segmentation");
    let csum_after_clear = ethtool_feature(NAME, "tx-checksum-ip-generic");

    drop(dev2);

    // Cleanup before asserting so a failed assert doesn't leak the device.
    let _ = Command::new("ip").args(["link", "delete", NAME]).status();

    assert!(
        tso_after_offload,
        "ethtool sanity: tx-tcp-segmentation should be ON after offload=true attach"
    );
    assert!(
        csum_after_offload,
        "ethtool sanity: tx-checksum-ip-generic should be ON after offload=true attach"
    );
    assert!(
        !tso_after_clear,
        "regression: tx-tcp-segmentation still ON after offload=false attach \
         (device-wide TUN_F_TSO* not cleared)"
    );
    assert!(
        !csum_after_clear,
        "regression: tx-checksum-ip-generic still ON after offload=false attach \
         (device-wide TUN_F_CSUM not cleared)"
    );
}